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/driver/rados/rgw_sync_trace.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <atomic> #include "common/ceph_mutex.h" #include "common/shunique_lock.h" #include "common/admin_socket.h" #include <set> #include <ostream> #include <string> #include <shared_mutex> #include <boost/circular_buffer.hpp> #define SSTR(o) ({ \ std::stringstream ss; \ ss << o; \ ss.str(); \ }) #define RGW_SNS_FLAG_ACTIVE 1 #define RGW_SNS_FLAG_ERROR 2 class RGWRados; class RGWSyncTraceManager; class RGWSyncTraceNode; class RGWSyncTraceServiceMapThread; using RGWSyncTraceNodeRef = std::shared_ptr<RGWSyncTraceNode>; class RGWSyncTraceNode final { friend class RGWSyncTraceManager; CephContext *cct; RGWSyncTraceNodeRef parent; uint16_t state{0}; std::string status; ceph::mutex lock = ceph::make_mutex("RGWSyncTraceNode::lock"); std::string type; std::string id; std::string prefix; std::string resource_name; uint64_t handle; boost::circular_buffer<std::string> history; // private constructor, create with RGWSyncTraceManager::add_node() RGWSyncTraceNode(CephContext *_cct, uint64_t _handle, const RGWSyncTraceNodeRef& _parent, const std::string& _type, const std::string& _id); public: void set_resource_name(const std::string& s) { resource_name = s; } const std::string& get_resource_name() { return resource_name; } void set_flag(uint16_t s) { state |= s; } void unset_flag(uint16_t s) { state &= ~s; } bool test_flags(uint16_t f) { return (state & f) == f; } void log(int level, const std::string& s); std::string to_str() { return prefix + " " + status; } const std::string& get_prefix() { return prefix; } std::ostream& operator<<(std::ostream& os) { os << to_str(); return os; } boost::circular_buffer<std::string>& get_history() { return history; } bool match(const std::string& search_term, bool search_history); }; class RGWSyncTraceManager : public AdminSocketHook { friend class RGWSyncTraceNode; mutable std::shared_timed_mutex lock; using shunique_lock = ceph::shunique_lock<decltype(lock)>; CephContext *cct; RGWSyncTraceServiceMapThread *service_map_thread{nullptr}; std::map<uint64_t, RGWSyncTraceNodeRef> nodes; boost::circular_buffer<RGWSyncTraceNodeRef> complete_nodes; std::atomic<uint64_t> count = { 0 }; std::list<std::array<std::string, 3> > admin_commands; uint64_t alloc_handle() { return ++count; } void finish_node(RGWSyncTraceNode *node); public: RGWSyncTraceManager(CephContext *_cct, int max_lru) : cct(_cct), complete_nodes(max_lru) {} ~RGWSyncTraceManager(); void init(RGWRados *store); const RGWSyncTraceNodeRef root_node; RGWSyncTraceNodeRef add_node(const RGWSyncTraceNodeRef& parent, const std::string& type, const std::string& id = ""); int hook_to_admin_command(); int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& out) override; std::string get_active_names(); };
3,267
22.014085
93
h
null
ceph-main/src/rgw/driver/rados/rgw_tools.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "common/errno.h" #include "librados/librados_asio.h" #include "include/stringify.h" #include "rgw_tools.h" #include "rgw_acl_s3.h" #include "rgw_aio_throttle.h" #include "rgw_compression.h" #include "common/BackTrace.h" #define dout_subsys ceph_subsys_rgw #define READ_CHUNK_LEN (512 * 1024) using namespace std; int rgw_init_ioctx(const DoutPrefixProvider *dpp, librados::Rados *rados, const rgw_pool& pool, librados::IoCtx& ioctx, bool create, bool mostly_omap, bool bulk) { int r = rados->ioctx_create(pool.name.c_str(), ioctx); if (r == -ENOENT && create) { r = rados->pool_create(pool.name.c_str()); if (r == -ERANGE) { ldpp_dout(dpp, 0) << __func__ << " ERROR: librados::Rados::pool_create returned " << cpp_strerror(-r) << " (this can be due to a pool or placement group misconfiguration, e.g." << " pg_num < pgp_num or mon_max_pg_per_osd exceeded)" << dendl; } if (r < 0 && r != -EEXIST) { return r; } r = rados->ioctx_create(pool.name.c_str(), ioctx); if (r < 0) { return r; } r = ioctx.application_enable(pg_pool_t::APPLICATION_NAME_RGW, false); if (r < 0 && r != -EOPNOTSUPP) { return r; } if (mostly_omap) { // set pg_autoscale_bias bufferlist inbl; float bias = g_conf().get_val<double>("rgw_rados_pool_autoscale_bias"); int r = rados->mon_command( "{\"prefix\": \"osd pool set\", \"pool\": \"" + pool.name + "\", \"var\": \"pg_autoscale_bias\", \"val\": \"" + stringify(bias) + "\"}", inbl, NULL, NULL); if (r < 0) { ldpp_dout(dpp, 10) << __func__ << " warning: failed to set pg_autoscale_bias on " << pool.name << dendl; } // set recovery_priority int p = g_conf().get_val<uint64_t>("rgw_rados_pool_recovery_priority"); r = rados->mon_command( "{\"prefix\": \"osd pool set\", \"pool\": \"" + pool.name + "\", \"var\": \"recovery_priority\": \"" + stringify(p) + "\"}", inbl, NULL, NULL); if (r < 0) { ldpp_dout(dpp, 10) << __func__ << " warning: failed to set recovery_priority on " << pool.name << dendl; } } if (bulk) { // set bulk bufferlist inbl; int r = rados->mon_command( "{\"prefix\": \"osd pool set\", \"pool\": \"" + pool.name + "\", \"var\": \"bulk\", \"val\": \"true\"}", inbl, NULL, NULL); if (r < 0) { ldpp_dout(dpp, 10) << __func__ << " warning: failed to set 'bulk' on " << pool.name << dendl; } } } else if (r < 0) { return r; } if (!pool.ns.empty()) { ioctx.set_namespace(pool.ns); } return 0; } map<string, bufferlist>* no_change_attrs() { static map<string, bufferlist> no_change; return &no_change; } int rgw_put_system_obj(const DoutPrefixProvider *dpp, RGWSI_SysObj* svc_sysobj, const rgw_pool& pool, const string& oid, bufferlist& data, bool exclusive, RGWObjVersionTracker *objv_tracker, real_time set_mtime, optional_yield y, map<string, bufferlist> *pattrs) { map<string,bufferlist> no_attrs; if (!pattrs) { pattrs = &no_attrs; } rgw_raw_obj obj(pool, oid); auto sysobj = svc_sysobj->get_obj(obj); int ret; if (pattrs != no_change_attrs()) { ret = sysobj.wop() .set_objv_tracker(objv_tracker) .set_exclusive(exclusive) .set_mtime(set_mtime) .set_attrs(*pattrs) .write(dpp, data, y); } else { ret = sysobj.wop() .set_objv_tracker(objv_tracker) .set_exclusive(exclusive) .set_mtime(set_mtime) .write_data(dpp, data, y); } return ret; } int rgw_stat_system_obj(const DoutPrefixProvider *dpp, RGWSI_SysObj* svc_sysobj, const rgw_pool& pool, const std::string& key, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, std::map<std::string, bufferlist> *pattrs) { rgw_raw_obj obj(pool, key); auto sysobj = svc_sysobj->get_obj(obj); return sysobj.rop() .set_attrs(pattrs) .set_last_mod(pmtime) .stat(y, dpp); } int rgw_get_system_obj(RGWSI_SysObj* svc_sysobj, const rgw_pool& pool, const string& key, bufferlist& bl, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp, map<string, bufferlist> *pattrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version> refresh_version, bool raw_attrs) { const rgw_raw_obj obj(pool, key); auto sysobj = svc_sysobj->get_obj(obj); auto rop = sysobj.rop(); return rop.set_attrs(pattrs) .set_last_mod(pmtime) .set_objv_tracker(objv_tracker) .set_raw_attrs(raw_attrs) .set_cache_info(cache_info) .set_refresh_version(refresh_version) .read(dpp, &bl, y); } int rgw_delete_system_obj(const DoutPrefixProvider *dpp, RGWSI_SysObj *sysobj_svc, const rgw_pool& pool, const string& oid, RGWObjVersionTracker *objv_tracker, optional_yield y) { auto sysobj = sysobj_svc->get_obj(rgw_raw_obj{pool, oid}); rgw_raw_obj obj(pool, oid); return sysobj.wop() .set_objv_tracker(objv_tracker) .remove(dpp, y); } int rgw_rados_operate(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, const std::string& oid, librados::ObjectReadOperation *op, bufferlist* pbl, optional_yield y, int flags) { // given a yield_context, call async_operate() to yield the coroutine instead // of blocking if (y) { auto& context = y.get_io_context(); auto& yield = y.get_yield_context(); boost::system::error_code ec; auto bl = librados::async_operate( context, ioctx, oid, op, flags, yield[ec]); if (pbl) { *pbl = std::move(bl); } return -ec.value(); } // work on asio threads should be asynchronous, so warn when they block if (is_asio_thread) { ldpp_dout(dpp, 20) << "WARNING: blocking librados call" << dendl; #ifdef _BACKTRACE_LOGGING ldpp_dout(dpp, 20) << "BACKTRACE: " << __func__ << ": " << ClibBackTrace(0) << dendl; #endif } return ioctx.operate(oid, op, nullptr, flags); } int rgw_rados_operate(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, const std::string& oid, librados::ObjectWriteOperation *op, optional_yield y, int flags) { if (y) { auto& context = y.get_io_context(); auto& yield = y.get_yield_context(); boost::system::error_code ec; librados::async_operate(context, ioctx, oid, op, flags, yield[ec]); return -ec.value(); } if (is_asio_thread) { ldpp_dout(dpp, 20) << "WARNING: blocking librados call" << dendl; #ifdef _BACKTRACE_LOGGING ldpp_dout(dpp, 20) << "BACKTRACE: " << __func__ << ": " << ClibBackTrace(0) << dendl; #endif } return ioctx.operate(oid, op, flags); } int rgw_rados_notify(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, const std::string& oid, bufferlist& bl, uint64_t timeout_ms, bufferlist* pbl, optional_yield y) { if (y) { auto& context = y.get_io_context(); auto& yield = y.get_yield_context(); boost::system::error_code ec; auto reply = librados::async_notify(context, ioctx, oid, bl, timeout_ms, yield[ec]); if (pbl) { *pbl = std::move(reply); } return -ec.value(); } if (is_asio_thread) { ldpp_dout(dpp, 20) << "WARNING: blocking librados call" << dendl; #ifdef _BACKTRACE_LOGGING ldpp_dout(dpp, 20) << "BACKTRACE: " << __func__ << ": " << ClibBackTrace(0) << dendl; #endif } return ioctx.notify2(oid, bl, timeout_ms, pbl); } void rgw_filter_attrset(map<string, bufferlist>& unfiltered_attrset, const string& check_prefix, map<string, bufferlist> *attrset) { attrset->clear(); map<string, bufferlist>::iterator iter; for (iter = unfiltered_attrset.lower_bound(check_prefix); iter != unfiltered_attrset.end(); ++iter) { if (!boost::algorithm::starts_with(iter->first, check_prefix)) break; (*attrset)[iter->first] = iter->second; } } RGWDataAccess::RGWDataAccess(rgw::sal::Driver* _driver) : driver(_driver) { } int RGWDataAccess::Bucket::finish_init() { auto iter = attrs.find(RGW_ATTR_ACL); if (iter == attrs.end()) { return 0; } bufferlist::const_iterator bliter = iter->second.begin(); try { policy.decode(bliter); } catch (buffer::error& err) { return -EIO; } return 0; } int RGWDataAccess::Bucket::init(const DoutPrefixProvider *dpp, optional_yield y) { std::unique_ptr<rgw::sal::Bucket> bucket; int ret = sd->driver->get_bucket(dpp, nullptr, tenant, name, &bucket, y); if (ret < 0) { return ret; } bucket_info = bucket->get_info(); mtime = bucket->get_modification_time(); attrs = bucket->get_attrs(); return finish_init(); } int RGWDataAccess::Bucket::init(const RGWBucketInfo& _bucket_info, const map<string, bufferlist>& _attrs) { bucket_info = _bucket_info; attrs = _attrs; return finish_init(); } int RGWDataAccess::Bucket::get_object(const rgw_obj_key& key, ObjectRef *obj) { obj->reset(new Object(sd, shared_from_this(), key)); return 0; } int RGWDataAccess::Object::put(bufferlist& data, map<string, bufferlist>& attrs, const DoutPrefixProvider *dpp, optional_yield y) { rgw::sal::Driver* driver = sd->driver; CephContext *cct = driver->ctx(); string tag; append_rand_alpha(cct, tag, tag, 32); RGWBucketInfo& bucket_info = bucket->bucket_info; rgw::BlockingAioThrottle aio(driver->ctx()->_conf->rgw_put_obj_min_window_size); std::unique_ptr<rgw::sal::Bucket> b; driver->get_bucket(NULL, bucket_info, &b); std::unique_ptr<rgw::sal::Object> obj = b->get_object(key); auto& owner = bucket->policy.get_owner(); string req_id = driver->zone_unique_id(driver->get_new_req_id()); std::unique_ptr<rgw::sal::Writer> processor; processor = driver->get_atomic_writer(dpp, y, obj.get(), owner.get_id(), nullptr, olh_epoch, req_id); int ret = processor->prepare(y); if (ret < 0) return ret; rgw::sal::DataProcessor *filter = processor.get(); CompressorRef plugin; boost::optional<RGWPutObj_Compress> compressor; const auto& compression_type = driver->get_compression_type(bucket_info.placement_rule); if (compression_type != "none") { plugin = Compressor::create(driver->ctx(), compression_type); if (!plugin) { ldpp_dout(dpp, 1) << "Cannot load plugin for compression type " << compression_type << dendl; } else { compressor.emplace(driver->ctx(), plugin, filter); filter = &*compressor; } } off_t ofs = 0; auto obj_size = data.length(); RGWMD5Etag etag_calc; do { size_t read_len = std::min(data.length(), (unsigned int)cct->_conf->rgw_max_chunk_size); bufferlist bl; data.splice(0, read_len, &bl); etag_calc.update(bl); ret = filter->process(std::move(bl), ofs); if (ret < 0) return ret; ofs += read_len; } while (data.length() > 0); ret = filter->process({}, ofs); if (ret < 0) { return ret; } bool has_etag_attr = false; auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { bufferlist& bl = iter->second; etag = bl.to_str(); has_etag_attr = true; } if (!aclbl) { RGWAccessControlPolicy_S3 policy(cct); policy.create_canned(bucket->policy.get_owner(), bucket->policy.get_owner(), string()); /* default private policy */ policy.encode(aclbl.emplace()); } if (etag.empty()) { etag_calc.finish(&etag); } if (!has_etag_attr) { bufferlist etagbl; etagbl.append(etag); attrs[RGW_ATTR_ETAG] = etagbl; } attrs[RGW_ATTR_ACL] = *aclbl; string *puser_data = nullptr; if (user_data) { puser_data = &(*user_data); } return processor->complete(obj_size, etag, &mtime, mtime, attrs, delete_at, nullptr, nullptr, puser_data, nullptr, nullptr, y); } void RGWDataAccess::Object::set_policy(const RGWAccessControlPolicy& policy) { policy.encode(aclbl.emplace()); } void rgw_complete_aio_completion(librados::AioCompletion* c, int r) { auto pc = c->pc; librados::CB_AioCompleteAndSafe cb(pc); cb(r); }
12,780
28.180365
130
cc
null
ceph-main/src/rgw/driver/rados/rgw_tools.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string> #include "include/types.h" #include "include/ceph_hash.h" #include "common/ceph_time.h" #include "rgw_common.h" #include "rgw_sal_fwd.h" class RGWSI_SysObj; class RGWRados; struct RGWObjVersionTracker; class optional_yield; struct obj_version; int rgw_init_ioctx(const DoutPrefixProvider *dpp, librados::Rados *rados, const rgw_pool& pool, librados::IoCtx& ioctx, bool create = false, bool mostly_omap = false, bool bulk = false); #define RGW_NO_SHARD -1 #define RGW_SHARDS_PRIME_0 7877 #define RGW_SHARDS_PRIME_1 65521 extern const std::string MP_META_SUFFIX; inline int rgw_shards_max() { return RGW_SHARDS_PRIME_1; } // only called by rgw_shard_id and rgw_bucket_shard_index static inline int rgw_shards_mod(unsigned hval, int max_shards) { if (max_shards <= RGW_SHARDS_PRIME_0) { return hval % RGW_SHARDS_PRIME_0 % max_shards; } return hval % RGW_SHARDS_PRIME_1 % max_shards; } // used for logging and tagging inline int rgw_shard_id(const std::string& key, int max_shards) { return rgw_shards_mod(ceph_str_hash_linux(key.c_str(), key.size()), max_shards); } void rgw_shard_name(const std::string& prefix, unsigned max_shards, const std::string& key, std::string& name, int *shard_id); void rgw_shard_name(const std::string& prefix, unsigned max_shards, const std::string& section, const std::string& key, std::string& name); void rgw_shard_name(const std::string& prefix, unsigned shard_id, std::string& name); int rgw_put_system_obj(const DoutPrefixProvider *dpp, RGWSI_SysObj* svc_sysobj, const rgw_pool& pool, const std::string& oid, bufferlist& data, bool exclusive, RGWObjVersionTracker *objv_tracker, real_time set_mtime, optional_yield y, std::map<std::string, bufferlist> *pattrs = nullptr); int rgw_get_system_obj(RGWSI_SysObj* svc_sysobj, const rgw_pool& pool, const std::string& key, bufferlist& bl, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp, std::map<std::string, bufferlist> *pattrs = nullptr, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none, bool raw_attrs=false); int rgw_delete_system_obj(const DoutPrefixProvider *dpp, RGWSI_SysObj *sysobj_svc, const rgw_pool& pool, const std::string& oid, RGWObjVersionTracker *objv_tracker, optional_yield y); int rgw_stat_system_obj(const DoutPrefixProvider *dpp, RGWSI_SysObj* svc_sysobj, const rgw_pool& pool, const std::string& key, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, std::map<std::string, bufferlist> *pattrs = nullptr); const char *rgw_find_mime_by_ext(std::string& ext); void rgw_filter_attrset(std::map<std::string, bufferlist>& unfiltered_attrset, const std::string& check_prefix, std::map<std::string, bufferlist> *attrset); /// indicates whether the current thread is in boost::asio::io_context::run(), /// used to log warnings if synchronous librados calls are made extern thread_local bool is_asio_thread; /// perform the rados operation, using the yield context when given int rgw_rados_operate(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, const std::string& oid, librados::ObjectReadOperation *op, bufferlist* pbl, optional_yield y, int flags = 0); int rgw_rados_operate(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, const std::string& oid, librados::ObjectWriteOperation *op, optional_yield y, int flags = 0); int rgw_rados_notify(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, const std::string& oid, bufferlist& bl, uint64_t timeout_ms, bufferlist* pbl, optional_yield y); int rgw_tools_init(const DoutPrefixProvider *dpp, CephContext *cct); void rgw_tools_cleanup(); template<class H, size_t S> class RGWEtag { H hash; public: RGWEtag() { if constexpr (std::is_same_v<H, MD5>) { // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } } void update(const char *buf, size_t len) { hash.Update((const unsigned char *)buf, len); } void update(bufferlist& bl) { if (bl.length() > 0) { update(bl.c_str(), bl.length()); } } void update(const std::string& s) { if (!s.empty()) { update(s.c_str(), s.size()); } } void finish(std::string *etag) { char etag_buf[S]; char etag_buf_str[S * 2 + 16]; hash.Final((unsigned char *)etag_buf); buf_to_hex((const unsigned char *)etag_buf, S, etag_buf_str); *etag = etag_buf_str; } }; using RGWMD5Etag = RGWEtag<MD5, CEPH_CRYPTO_MD5_DIGESTSIZE>; class RGWDataAccess { rgw::sal::Driver* driver; public: RGWDataAccess(rgw::sal::Driver* _driver); class Object; class Bucket; using BucketRef = std::shared_ptr<Bucket>; using ObjectRef = std::shared_ptr<Object>; class Bucket : public std::enable_shared_from_this<Bucket> { friend class RGWDataAccess; friend class Object; RGWDataAccess *sd{nullptr}; RGWBucketInfo bucket_info; std::string tenant; std::string name; std::string bucket_id; ceph::real_time mtime; std::map<std::string, bufferlist> attrs; RGWAccessControlPolicy policy; int finish_init(); Bucket(RGWDataAccess *_sd, const std::string& _tenant, const std::string& _name, const std::string& _bucket_id) : sd(_sd), tenant(_tenant), name(_name), bucket_id(_bucket_id) {} Bucket(RGWDataAccess *_sd) : sd(_sd) {} int init(const DoutPrefixProvider *dpp, optional_yield y); int init(const RGWBucketInfo& _bucket_info, const std::map<std::string, bufferlist>& _attrs); public: int get_object(const rgw_obj_key& key, ObjectRef *obj); }; class Object { RGWDataAccess *sd{nullptr}; BucketRef bucket; rgw_obj_key key; ceph::real_time mtime; std::string etag; uint64_t olh_epoch{0}; ceph::real_time delete_at; std::optional<std::string> user_data; std::optional<bufferlist> aclbl; Object(RGWDataAccess *_sd, BucketRef&& _bucket, const rgw_obj_key& _key) : sd(_sd), bucket(_bucket), key(_key) {} public: int put(bufferlist& data, std::map<std::string, bufferlist>& attrs, const DoutPrefixProvider *dpp, optional_yield y); /* might modify attrs */ void set_mtime(const ceph::real_time& _mtime) { mtime = _mtime; } void set_etag(const std::string& _etag) { etag = _etag; } void set_olh_epoch(uint64_t epoch) { olh_epoch = epoch; } void set_delete_at(ceph::real_time _delete_at) { delete_at = _delete_at; } void set_user_data(const std::string& _user_data) { user_data = _user_data; } void set_policy(const RGWAccessControlPolicy& policy); friend class Bucket; }; int get_bucket(const DoutPrefixProvider *dpp, const std::string& tenant, const std::string name, const std::string bucket_id, BucketRef *bucket, optional_yield y) { bucket->reset(new Bucket(this, tenant, name, bucket_id)); return (*bucket)->init(dpp, y); } int get_bucket(const RGWBucketInfo& bucket_info, const std::map<std::string, bufferlist>& attrs, BucketRef *bucket) { bucket->reset(new Bucket(this)); return (*bucket)->init(bucket_info, attrs); } friend class Bucket; friend class Object; }; using RGWDataAccessRef = std::shared_ptr<RGWDataAccess>; /// Complete an AioCompletion. To return error values or otherwise /// satisfy the caller. Useful for making complicated asynchronous /// calls and error handling. void rgw_complete_aio_completion(librados::AioCompletion* c, int r); /// This returns a static, non-NULL pointer, recognized only by /// rgw_put_system_obj(). When supplied instead of the attributes, the /// attributes will be unmodified. /// // (Currently providing nullptr will wipe all attributes.) std::map<std::string, ceph::buffer::list>* no_change_attrs();
8,832
30.888087
146
h
null
ceph-main/src/rgw/driver/rados/rgw_trim_bilog.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) 2017 Red Hat, Inc * * Author: Casey Bodley <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #include <mutex> #include <boost/circular_buffer.hpp> #include <boost/container/flat_map.hpp> #include "include/scope_guard.h" #include "common/bounded_key_counter.h" #include "common/errno.h" #include "rgw_trim_bilog.h" #include "rgw_cr_rados.h" #include "rgw_cr_rest.h" #include "rgw_cr_tools.h" #include "rgw_data_sync.h" #include "rgw_metadata.h" #include "rgw_sal.h" #include "rgw_zone.h" #include "rgw_sync.h" #include "rgw_bucket.h" #include "services/svc_zone.h" #include "services/svc_meta.h" #include "services/svc_bilog_rados.h" #include <boost/asio/yield.hpp> #include "include/ceph_assert.h" #define dout_subsys ceph_subsys_rgw #undef dout_prefix #define dout_prefix (*_dout << "trim: ") using namespace std; using rgw::BucketTrimConfig; using BucketChangeCounter = BoundedKeyCounter<std::string, int>; const std::string rgw::BucketTrimStatus::oid = "bilog.trim"; using rgw::BucketTrimStatus; // watch/notify api for gateways to coordinate about which buckets to trim enum TrimNotifyType { NotifyTrimCounters = 0, NotifyTrimComplete, }; WRITE_RAW_ENCODER(TrimNotifyType); struct TrimNotifyHandler { virtual ~TrimNotifyHandler() = default; virtual void handle(bufferlist::const_iterator& input, bufferlist& output) = 0; }; /// api to share the bucket trim counters between gateways in the same zone. /// each gateway will process different datalog shards, so the gateway that runs /// the trim process needs to accumulate their counters struct TrimCounters { /// counter for a single bucket struct BucketCounter { std::string bucket; //< bucket instance metadata key int count{0}; BucketCounter() = default; BucketCounter(const std::string& bucket, int count) : bucket(bucket), count(count) {} void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& p); }; using Vector = std::vector<BucketCounter>; /// request bucket trim counters from peer gateways struct Request { uint16_t max_buckets; //< maximum number of bucket counters to return void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& p); }; /// return the current bucket trim counters struct Response { Vector bucket_counters; void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& p); }; /// server interface to query the hottest buckets struct Server { virtual ~Server() = default; virtual void get_bucket_counters(int count, Vector& counters) = 0; virtual void reset_bucket_counters() = 0; }; /// notify handler class Handler : public TrimNotifyHandler { Server *const server; public: explicit Handler(Server *server) : server(server) {} void handle(bufferlist::const_iterator& input, bufferlist& output) override; }; }; std::ostream& operator<<(std::ostream& out, const TrimCounters::BucketCounter& rhs) { return out << rhs.bucket << ":" << rhs.count; } void TrimCounters::BucketCounter::encode(bufferlist& bl) const { using ceph::encode; // no versioning to save space encode(bucket, bl); encode(count, bl); } void TrimCounters::BucketCounter::decode(bufferlist::const_iterator& p) { using ceph::decode; decode(bucket, p); decode(count, p); } WRITE_CLASS_ENCODER(TrimCounters::BucketCounter); void TrimCounters::Request::encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(max_buckets, bl); ENCODE_FINISH(bl); } void TrimCounters::Request::decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(max_buckets, p); DECODE_FINISH(p); } WRITE_CLASS_ENCODER(TrimCounters::Request); void TrimCounters::Response::encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(bucket_counters, bl); ENCODE_FINISH(bl); } void TrimCounters::Response::decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(bucket_counters, p); DECODE_FINISH(p); } WRITE_CLASS_ENCODER(TrimCounters::Response); void TrimCounters::Handler::handle(bufferlist::const_iterator& input, bufferlist& output) { Request request; decode(request, input); auto count = std::min<uint16_t>(request.max_buckets, 128); Response response; server->get_bucket_counters(count, response.bucket_counters); encode(response, output); } /// api to notify peer gateways that trim has completed and their bucket change /// counters can be reset struct TrimComplete { struct Request { void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& p); }; struct Response { void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& p); }; /// server interface to reset bucket counters using Server = TrimCounters::Server; /// notify handler class Handler : public TrimNotifyHandler { Server *const server; public: explicit Handler(Server *server) : server(server) {} void handle(bufferlist::const_iterator& input, bufferlist& output) override; }; }; void TrimComplete::Request::encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); ENCODE_FINISH(bl); } void TrimComplete::Request::decode(bufferlist::const_iterator& p) { DECODE_START(1, p); DECODE_FINISH(p); } WRITE_CLASS_ENCODER(TrimComplete::Request); void TrimComplete::Response::encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); ENCODE_FINISH(bl); } void TrimComplete::Response::decode(bufferlist::const_iterator& p) { DECODE_START(1, p); DECODE_FINISH(p); } WRITE_CLASS_ENCODER(TrimComplete::Response); void TrimComplete::Handler::handle(bufferlist::const_iterator& input, bufferlist& output) { Request request; decode(request, input); server->reset_bucket_counters(); Response response; encode(response, output); } /// rados watcher for bucket trim notifications class BucketTrimWatcher : public librados::WatchCtx2 { rgw::sal::RadosStore* const store; const rgw_raw_obj& obj; rgw_rados_ref ref; uint64_t handle{0}; using HandlerPtr = std::unique_ptr<TrimNotifyHandler>; boost::container::flat_map<TrimNotifyType, HandlerPtr> handlers; public: BucketTrimWatcher(rgw::sal::RadosStore* store, const rgw_raw_obj& obj, TrimCounters::Server *counters) : store(store), obj(obj) { handlers.emplace(NotifyTrimCounters, std::make_unique<TrimCounters::Handler>(counters)); handlers.emplace(NotifyTrimComplete, std::make_unique<TrimComplete::Handler>(counters)); } ~BucketTrimWatcher() { stop(); } int start(const DoutPrefixProvider *dpp) { int r = store->getRados()->get_raw_obj_ref(dpp, obj, &ref); if (r < 0) { return r; } // register a watch on the realm's control object r = ref.pool.ioctx().watch2(ref.obj.oid, &handle, this); if (r == -ENOENT) { constexpr bool exclusive = true; r = ref.pool.ioctx().create(ref.obj.oid, exclusive); if (r == -EEXIST || r == 0) { r = ref.pool.ioctx().watch2(ref.obj.oid, &handle, this); } } if (r < 0) { ldpp_dout(dpp, -1) << "Failed to watch " << ref.obj << " with " << cpp_strerror(-r) << dendl; ref.pool.ioctx().close(); return r; } ldpp_dout(dpp, 10) << "Watching " << ref.obj.oid << dendl; return 0; } int restart() { int r = ref.pool.ioctx().unwatch2(handle); if (r < 0) { lderr(store->ctx()) << "Failed to unwatch on " << ref.obj << " with " << cpp_strerror(-r) << dendl; } r = ref.pool.ioctx().watch2(ref.obj.oid, &handle, this); if (r < 0) { lderr(store->ctx()) << "Failed to restart watch on " << ref.obj << " with " << cpp_strerror(-r) << dendl; ref.pool.ioctx().close(); } return r; } void stop() { if (handle) { ref.pool.ioctx().unwatch2(handle); ref.pool.ioctx().close(); } } /// respond to bucket trim notifications void handle_notify(uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) override { if (cookie != handle) { return; } bufferlist reply; try { auto p = bl.cbegin(); TrimNotifyType type; decode(type, p); auto handler = handlers.find(type); if (handler != handlers.end()) { handler->second->handle(p, reply); } else { lderr(store->ctx()) << "no handler for notify type " << type << dendl; } } catch (const buffer::error& e) { lderr(store->ctx()) << "Failed to decode notification: " << e.what() << dendl; } ref.pool.ioctx().notify_ack(ref.obj.oid, notify_id, cookie, reply); } /// reestablish the watch if it gets disconnected void handle_error(uint64_t cookie, int err) override { if (cookie != handle) { return; } if (err == -ENOTCONN) { ldout(store->ctx(), 4) << "Disconnected watch on " << ref.obj << dendl; restart(); } } }; /// Interface to communicate with the trim manager about completed operations struct BucketTrimObserver { virtual ~BucketTrimObserver() = default; virtual void on_bucket_trimmed(std::string&& bucket_instance) = 0; virtual bool trimmed_recently(const std::string_view& bucket_instance) = 0; }; /// trim each bilog shard to the given marker, while limiting the number of /// concurrent requests class BucketTrimShardCollectCR : public RGWShardCollectCR { static constexpr int MAX_CONCURRENT_SHARDS = 16; const DoutPrefixProvider *dpp; rgw::sal::RadosStore* const store; const RGWBucketInfo& bucket_info; rgw::bucket_index_layout_generation generation; const std::vector<std::string>& markers; //< shard markers to trim size_t i{0}; //< index of current shard marker int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "failed to trim bilog shard: " << cpp_strerror(r) << dendl; } return r; } public: BucketTrimShardCollectCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, const RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& generation, const std::vector<std::string>& markers) : RGWShardCollectCR(store->ctx(), MAX_CONCURRENT_SHARDS), dpp(dpp), store(store), bucket_info(bucket_info), generation(generation), markers(markers) {} bool spawn_next() override; }; bool BucketTrimShardCollectCR::spawn_next() { while (i < markers.size()) { const auto& marker = markers[i]; const auto shard_id = i++; // skip empty markers if (!marker.empty()) { ldpp_dout(dpp, 10) << "trimming bilog shard " << shard_id << " of " << bucket_info.bucket << " at marker " << marker << dendl; spawn(new RGWRadosBILogTrimCR(dpp, store, bucket_info, shard_id, generation, std::string{}, marker), false); return true; } } return false; } /// Delete a BI generation, limiting the number of requests in flight. class BucketCleanIndexCollectCR : public RGWShardCollectCR { static constexpr int MAX_CONCURRENT_SHARDS = 16; const DoutPrefixProvider *dpp; rgw::sal::RadosStore* const store; const RGWBucketInfo& bucket_info; rgw::bucket_index_layout_generation index; uint32_t shard = 0; const uint32_t num_shards = rgw::num_shards(index); int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "clean index: " << cpp_strerror(r) << dendl; } return r; } public: BucketCleanIndexCollectCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, const RGWBucketInfo& bucket_info, rgw::bucket_index_layout_generation index) : RGWShardCollectCR(store->ctx(), MAX_CONCURRENT_SHARDS), dpp(dpp), store(store), bucket_info(bucket_info), index(index) {} bool spawn_next() override { if (shard < num_shards) { RGWRados::BucketShard bs(store->getRados()); bs.init(dpp, bucket_info, index, shard, null_yield); spawn(new RGWRadosRemoveOidCR(store, std::move(bs.bucket_obj), nullptr), false); ++shard; return true; } else { return false; } } }; /// trim the bilog of all of the given bucket instance's shards class BucketTrimInstanceCR : public RGWCoroutine { static constexpr auto MAX_RETRIES = 25u; rgw::sal::RadosStore* const store; RGWHTTPManager *const http; BucketTrimObserver *const observer; std::string bucket_instance; rgw_bucket_get_sync_policy_params get_policy_params; std::shared_ptr<rgw_bucket_get_sync_policy_result> source_policy; rgw_bucket bucket; const std::string& zone_id; //< my zone id RGWBucketInfo _bucket_info; const RGWBucketInfo *pbucket_info; //< pointer to bucket instance info to locate bucket indices int child_ret = 0; const DoutPrefixProvider *dpp; public: struct StatusShards { uint64_t generation = 0; std::vector<rgw_bucket_shard_sync_info> shards; }; private: std::vector<StatusShards> peer_status; //< sync status for each peer std::vector<std::string> min_markers; //< min marker per shard /// The log generation to trim rgw::bucket_log_layout_generation totrim; /// Generation to be cleaned/New bucket info (if any) std::optional<std::pair<RGWBucketInfo, rgw::bucket_log_layout_generation>> clean_info; /// Maximum number of times to attempt to put bucket info unsigned retries = 0; int take_min_generation() { // Initialize the min_generation to the bucket's current // generation, used in case we have no peers. auto min_generation = pbucket_info->layout.logs.back().gen; // Determine the minimum generation if (auto m = std::min_element(peer_status.begin(), peer_status.end(), [](const StatusShards& l, const StatusShards& r) { return l.generation < r.generation; }); m != peer_status.end()) { min_generation = m->generation; } auto& logs = pbucket_info->layout.logs; auto log = std::find_if(logs.begin(), logs.end(), rgw::matches_gen(min_generation)); if (log == logs.end()) { ldpp_dout(dpp, 5) << __PRETTY_FUNCTION__ << ":" << __LINE__ << "ERROR: No log layout for min_generation=" << min_generation << dendl; return -ENOENT; } totrim = *log; return 0; } /// If there is a generation below the minimum, prepare to clean it up. int maybe_remove_generation() { if (clean_info) return 0; if (pbucket_info->layout.logs.front().gen < totrim.gen) { clean_info = {*pbucket_info, {}}; auto log = clean_info->first.layout.logs.cbegin(); clean_info->second = *log; if (clean_info->first.layout.logs.size() == 1) { ldpp_dout(dpp, -1) << "Critical error! Attempt to remove only log generation! " << "log.gen=" << log->gen << ", totrim.gen=" << totrim.gen << dendl; return -EIO; } clean_info->first.layout.logs.erase(log); } return 0; } public: BucketTrimInstanceCR(rgw::sal::RadosStore* store, RGWHTTPManager *http, BucketTrimObserver *observer, const std::string& bucket_instance, const DoutPrefixProvider *dpp) : RGWCoroutine(store->ctx()), store(store), http(http), observer(observer), bucket_instance(bucket_instance), zone_id(store->svc()->zone->get_zone().id), dpp(dpp) { rgw_bucket_parse_bucket_key(cct, bucket_instance, &bucket, nullptr); source_policy = make_shared<rgw_bucket_get_sync_policy_result>(); } int operate(const DoutPrefixProvider *dpp) override; }; namespace { /// populate the status with the minimum stable marker of each shard int take_min_status( CephContext *cct, const uint64_t min_generation, std::vector<BucketTrimInstanceCR::StatusShards>::const_iterator first, std::vector<BucketTrimInstanceCR::StatusShards>::const_iterator last, std::vector<std::string> *status) { for (auto peer = first; peer != last; ++peer) { // Peers on later generations don't get a say in the matter if (peer->generation > min_generation) { continue; } if (peer->shards.size() != status->size()) { // all peers must agree on the number of shards return -EINVAL; } auto m = status->begin(); for (auto& shard : peer->shards) { auto& marker = *m++; // always take the first marker, or any later marker that's smaller if (peer == first || marker > shard.inc_marker.position) { marker = std::move(shard.inc_marker.position); } } } return 0; } } template<> inline int parse_decode_json<BucketTrimInstanceCR::StatusShards>( BucketTrimInstanceCR::StatusShards& s, bufferlist& bl) { JSONParser p; if (!p.parse(bl.c_str(), bl.length())) { return -EINVAL; } try { bilog_status_v2 v; decode_json_obj(v, &p); s.generation = v.sync_status.incremental_gen; s.shards = std::move(v.inc_status); } catch (JSONDecoder::err& e) { try { // Fall back if we're talking to an old node that can't give v2 // output. s.generation = 0; decode_json_obj(s.shards, &p); } catch (JSONDecoder::err& e) { return -EINVAL; } } return 0; } int BucketTrimInstanceCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { ldpp_dout(dpp, 4) << "starting trim on bucket=" << bucket_instance << dendl; get_policy_params.zone = zone_id; get_policy_params.bucket = bucket; yield call(new RGWBucketGetSyncPolicyHandlerCR(store->svc()->rados->get_async_processor(), store, get_policy_params, source_policy, dpp)); if (retcode < 0) { if (retcode != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: failed to fetch policy handler for bucket=" << bucket << dendl; } return set_cr_error(retcode); } if (auto& opt_bucket_info = source_policy->policy_handler->get_bucket_info(); opt_bucket_info) { pbucket_info = &(*opt_bucket_info); } else { /* this shouldn't really happen */ return set_cr_error(-ENOENT); } if (pbucket_info->layout.logs.empty()) { return set_cr_done(); // no bilogs to trim } // query peers for sync status set_status("fetching sync status from relevant peers"); yield { const auto& all_dests = source_policy->policy_handler->get_all_dests(); vector<rgw_zone_id> zids; rgw_zone_id last_zid; for (auto& diter : all_dests) { const auto& zid = diter.first; if (zid == last_zid) { continue; } last_zid = zid; zids.push_back(zid); } peer_status.resize(zids.size()); auto& zone_conn_map = store->svc()->zone->get_zone_conn_map(); auto p = peer_status.begin(); for (auto& zid : zids) { // query data sync status from each sync peer rgw_http_param_pair params[] = { { "type", "bucket-index" }, { "status", nullptr }, { "options", "merge" }, { "bucket", bucket_instance.c_str() }, /* equal to source-bucket when `options==merge` and source-bucket param is not provided */ { "source-zone", zone_id.c_str() }, { "version", "2" }, { nullptr, nullptr } }; auto ziter = zone_conn_map.find(zid); if (ziter == zone_conn_map.end()) { ldpp_dout(dpp, 0) << "WARNING: no connection to zone " << zid << ", can't trim bucket: " << bucket << dendl; return set_cr_error(-ECANCELED); } using StatusCR = RGWReadRESTResourceCR<StatusShards>; spawn(new StatusCR(cct, ziter->second, http, "/admin/log/", params, &*p), false); ++p; } } // wait for a response from each peer. all must respond to attempt trim while (num_spawned()) { yield wait_for_child(); collect(&child_ret, nullptr); if (child_ret < 0) { drain_all(); return set_cr_error(child_ret); } } // Determine the minimum generation retcode = take_min_generation(); if (retcode < 0) { ldpp_dout(dpp, 4) << "failed to find minimum generation" << dendl; return set_cr_error(retcode); } retcode = maybe_remove_generation(); if (retcode < 0) { ldpp_dout(dpp, 4) << "error removing old generation from log: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } if (clean_info) { if (clean_info->second.layout.type != rgw::BucketLogType::InIndex) { ldpp_dout(dpp, 0) << "Unable to convert log of unknown type " << clean_info->second.layout.type << " to rgw::bucket_index_layout_generation " << dendl; return set_cr_error(-EINVAL); } yield call(new BucketCleanIndexCollectCR(dpp, store, clean_info->first, clean_info->second.layout.in_index)); if (retcode < 0) { ldpp_dout(dpp, 0) << "failed to remove previous generation: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } while (clean_info && retries < MAX_RETRIES) { yield call(new RGWPutBucketInstanceInfoCR( store->svc()->rados->get_async_processor(), store, clean_info->first, false, {}, no_change_attrs(), dpp)); // Raced, try again. if (retcode == -ECANCELED) { yield call(new RGWGetBucketInstanceInfoCR( store->svc()->rados->get_async_processor(), store, clean_info->first.bucket, &(clean_info->first), nullptr, dpp)); if (retcode < 0) { ldpp_dout(dpp, 0) << "failed to get bucket info: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } if (clean_info->first.layout.logs.front().gen == clean_info->second.gen) { clean_info->first.layout.logs.erase( clean_info->first.layout.logs.begin()); ++retries; continue; } // Raced, but someone else did what we needed to. retcode = 0; } if (retcode < 0) { ldpp_dout(dpp, 0) << "failed to put bucket info: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } clean_info = std::nullopt; } } else { if (totrim.layout.type != rgw::BucketLogType::InIndex) { ldpp_dout(dpp, 0) << "Unable to convert log of unknown type " << totrim.layout.type << " to rgw::bucket_index_layout_generation " << dendl; return set_cr_error(-EINVAL); } // To avoid hammering the OSD too hard, either trim old // generations OR trim the current one. // determine the minimum marker for each shard // initialize each shard with the maximum marker, which is only used when // there are no peers syncing from us min_markers.assign(std::max(1u, rgw::num_shards(totrim.layout.in_index)), RGWSyncLogTrimCR::max_marker); retcode = take_min_status(cct, totrim.gen, peer_status.cbegin(), peer_status.cend(), &min_markers); if (retcode < 0) { ldpp_dout(dpp, 4) << "failed to correlate bucket sync status from peers" << dendl; return set_cr_error(retcode); } // trim shards with a ShardCollectCR ldpp_dout(dpp, 10) << "trimming bilogs for bucket=" << pbucket_info->bucket << " markers=" << min_markers << ", shards=" << min_markers.size() << dendl; set_status("trimming bilog shards"); yield call(new BucketTrimShardCollectCR(dpp, store, *pbucket_info, totrim.layout.in_index, min_markers)); // ENODATA just means there were no keys to trim if (retcode == -ENODATA) { retcode = 0; } if (retcode < 0) { ldpp_dout(dpp, 4) << "failed to trim bilog shards: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } } observer->on_bucket_trimmed(std::move(bucket_instance)); return set_cr_done(); } return 0; } /// trim each bucket instance while limiting the number of concurrent operations class BucketTrimInstanceCollectCR : public RGWShardCollectCR { rgw::sal::RadosStore* const store; RGWHTTPManager *const http; BucketTrimObserver *const observer; std::vector<std::string>::const_iterator bucket; std::vector<std::string>::const_iterator end; const DoutPrefixProvider *dpp; int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "failed to trim bucket instance: " << cpp_strerror(r) << dendl; } return r; } public: BucketTrimInstanceCollectCR(rgw::sal::RadosStore* store, RGWHTTPManager *http, BucketTrimObserver *observer, const std::vector<std::string>& buckets, int max_concurrent, const DoutPrefixProvider *dpp) : RGWShardCollectCR(store->ctx(), max_concurrent), store(store), http(http), observer(observer), bucket(buckets.begin()), end(buckets.end()), dpp(dpp) {} bool spawn_next() override; }; bool BucketTrimInstanceCollectCR::spawn_next() { if (bucket == end) { return false; } spawn(new BucketTrimInstanceCR(store, http, observer, *bucket, dpp), false); ++bucket; return true; } /// correlate the replies from each peer gateway into the given counter int accumulate_peer_counters(bufferlist& bl, BucketChangeCounter& counter) { counter.clear(); try { // decode notify responses auto p = bl.cbegin(); std::map<std::pair<uint64_t, uint64_t>, bufferlist> replies; std::set<std::pair<uint64_t, uint64_t>> timeouts; decode(replies, p); decode(timeouts, p); for (auto& peer : replies) { auto q = peer.second.cbegin(); TrimCounters::Response response; decode(response, q); for (const auto& b : response.bucket_counters) { counter.insert(b.bucket, b.count); } } } catch (const buffer::error& e) { return -EIO; } return 0; } /// metadata callback has the signature bool(string&& key, string&& marker) using MetadataListCallback = std::function<bool(std::string&&, std::string&&)>; /// lists metadata keys, passing each to a callback until it returns false. /// on reaching the end, it will restart at the beginning and list up to the /// initial marker class AsyncMetadataList : public RGWAsyncRadosRequest { CephContext *const cct; RGWMetadataManager *const mgr; const std::string section; const std::string start_marker; MetadataListCallback callback; int _send_request(const DoutPrefixProvider *dpp) override; public: AsyncMetadataList(CephContext *cct, RGWCoroutine *caller, RGWAioCompletionNotifier *cn, RGWMetadataManager *mgr, const std::string& section, const std::string& start_marker, const MetadataListCallback& callback) : RGWAsyncRadosRequest(caller, cn), cct(cct), mgr(mgr), section(section), start_marker(start_marker), callback(callback) {} }; int AsyncMetadataList::_send_request(const DoutPrefixProvider *dpp) { void* handle = nullptr; std::list<std::string> keys; bool truncated{false}; std::string marker; // start a listing at the given marker int r = mgr->list_keys_init(dpp, section, start_marker, &handle); if (r == -EINVAL) { // restart with empty marker below } else if (r < 0) { ldpp_dout(dpp, 10) << "failed to init metadata listing: " << cpp_strerror(r) << dendl; return r; } else { ldpp_dout(dpp, 20) << "starting metadata listing at " << start_marker << dendl; // release the handle when scope exits auto g = make_scope_guard([=, this] { mgr->list_keys_complete(handle); }); do { // get the next key and marker r = mgr->list_keys_next(dpp, handle, 1, keys, &truncated); if (r < 0) { ldpp_dout(dpp, 10) << "failed to list metadata: " << cpp_strerror(r) << dendl; return r; } marker = mgr->get_marker(handle); if (!keys.empty()) { ceph_assert(keys.size() == 1); auto& key = keys.front(); if (!callback(std::move(key), std::move(marker))) { return 0; } } } while (truncated); if (start_marker.empty()) { // already listed all keys return 0; } } // restart the listing from the beginning (empty marker) handle = nullptr; r = mgr->list_keys_init(dpp, section, "", &handle); if (r < 0) { ldpp_dout(dpp, 10) << "failed to restart metadata listing: " << cpp_strerror(r) << dendl; return r; } ldpp_dout(dpp, 20) << "restarting metadata listing" << dendl; // release the handle when scope exits auto g = make_scope_guard([=, this] { mgr->list_keys_complete(handle); }); do { // get the next key and marker r = mgr->list_keys_next(dpp, handle, 1, keys, &truncated); if (r < 0) { ldpp_dout(dpp, 10) << "failed to list metadata: " << cpp_strerror(r) << dendl; return r; } marker = mgr->get_marker(handle); if (!keys.empty()) { ceph_assert(keys.size() == 1); auto& key = keys.front(); // stop at original marker if (marker > start_marker) { return 0; } if (!callback(std::move(key), std::move(marker))) { return 0; } } } while (truncated); return 0; } /// coroutine wrapper for AsyncMetadataList class MetadataListCR : public RGWSimpleCoroutine { RGWAsyncRadosProcessor *const async_rados; RGWMetadataManager *const mgr; const std::string& section; const std::string& start_marker; MetadataListCallback callback; RGWAsyncRadosRequest *req{nullptr}; public: MetadataListCR(CephContext *cct, RGWAsyncRadosProcessor *async_rados, RGWMetadataManager *mgr, const std::string& section, const std::string& start_marker, const MetadataListCallback& callback) : RGWSimpleCoroutine(cct), async_rados(async_rados), mgr(mgr), section(section), start_marker(start_marker), callback(callback) {} ~MetadataListCR() override { request_cleanup(); } int send_request(const DoutPrefixProvider *dpp) override { req = new AsyncMetadataList(cct, this, stack->create_completion_notifier(), mgr, section, start_marker, callback); async_rados->queue(req); return 0; } int request_complete() override { return req->get_ret_status(); } void request_cleanup() override { if (req) { req->finish(); req = nullptr; } } }; class BucketTrimCR : public RGWCoroutine { rgw::sal::RadosStore* const store; RGWHTTPManager *const http; const BucketTrimConfig& config; BucketTrimObserver *const observer; const rgw_raw_obj& obj; ceph::mono_time start_time; bufferlist notify_replies; BucketChangeCounter counter; std::vector<std::string> buckets; //< buckets selected for trim BucketTrimStatus status; RGWObjVersionTracker objv; //< version tracker for trim status object std::string last_cold_marker; //< position for next trim marker const DoutPrefixProvider *dpp; static const std::string section; //< metadata section for bucket instances public: BucketTrimCR(rgw::sal::RadosStore* store, RGWHTTPManager *http, const BucketTrimConfig& config, BucketTrimObserver *observer, const rgw_raw_obj& obj, const DoutPrefixProvider *dpp) : RGWCoroutine(store->ctx()), store(store), http(http), config(config), observer(observer), obj(obj), counter(config.counter_size), dpp(dpp) {} int operate(const DoutPrefixProvider *dpp) override; }; const std::string BucketTrimCR::section{"bucket.instance"}; int BucketTrimCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { start_time = ceph::mono_clock::now(); if (config.buckets_per_interval) { // query watch/notify for hot buckets ldpp_dout(dpp, 10) << "fetching active bucket counters" << dendl; set_status("fetching active bucket counters"); yield { // request the top bucket counters from each peer gateway const TrimNotifyType type = NotifyTrimCounters; TrimCounters::Request request{32}; bufferlist bl; encode(type, bl); encode(request, bl); call(new RGWRadosNotifyCR(store, obj, bl, config.notify_timeout_ms, &notify_replies)); } if (retcode < 0) { ldpp_dout(dpp, 10) << "failed to fetch peer bucket counters" << dendl; return set_cr_error(retcode); } // select the hottest buckets for trim retcode = accumulate_peer_counters(notify_replies, counter); if (retcode < 0) { ldout(cct, 4) << "failed to correlate peer bucket counters" << dendl; return set_cr_error(retcode); } buckets.reserve(config.buckets_per_interval); const int max_count = config.buckets_per_interval - config.min_cold_buckets_per_interval; counter.get_highest(max_count, [this] (const std::string& bucket, int count) { buckets.push_back(bucket); }); } if (buckets.size() < config.buckets_per_interval) { // read BucketTrimStatus for marker position set_status("reading trim status"); using ReadStatus = RGWSimpleRadosReadCR<BucketTrimStatus>; yield call(new ReadStatus(dpp, store, obj, &status, true, &objv)); if (retcode < 0) { ldpp_dout(dpp, 10) << "failed to read bilog trim status: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } if (status.marker == "MAX") { status.marker.clear(); // restart at the beginning } ldpp_dout(dpp, 10) << "listing cold buckets from marker=" << status.marker << dendl; set_status("listing cold buckets for trim"); yield { // capture a reference so 'this' remains valid in the callback auto ref = boost::intrusive_ptr<RGWCoroutine>{this}; // list cold buckets to consider for trim auto cb = [this, ref] (std::string&& bucket, std::string&& marker) { // filter out keys that we trimmed recently if (observer->trimmed_recently(bucket)) { return true; } // filter out active buckets that we've already selected auto i = std::find(buckets.begin(), buckets.end(), bucket); if (i != buckets.end()) { return true; } buckets.emplace_back(std::move(bucket)); // remember the last cold bucket spawned to update the status marker last_cold_marker = std::move(marker); // return true if there's room for more return buckets.size() < config.buckets_per_interval; }; call(new MetadataListCR(cct, store->svc()->rados->get_async_processor(), store->ctl()->meta.mgr, section, status.marker, cb)); } if (retcode < 0) { ldout(cct, 4) << "failed to list bucket instance metadata: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } } // trim bucket instances with limited concurrency set_status("trimming buckets"); ldpp_dout(dpp, 4) << "collected " << buckets.size() << " buckets for trim" << dendl; yield call(new BucketTrimInstanceCollectCR(store, http, observer, buckets, config.concurrent_buckets, dpp)); // ignore errors from individual buckets // write updated trim status if (!last_cold_marker.empty() && status.marker != last_cold_marker) { set_status("writing updated trim status"); status.marker = std::move(last_cold_marker); ldpp_dout(dpp, 20) << "writing bucket trim marker=" << status.marker << dendl; using WriteStatus = RGWSimpleRadosWriteCR<BucketTrimStatus>; yield call(new WriteStatus(dpp, store, obj, status, &objv)); if (retcode < 0) { ldpp_dout(dpp, 4) << "failed to write updated trim status: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } } // notify peers that trim completed set_status("trim completed"); yield { const TrimNotifyType type = NotifyTrimComplete; TrimComplete::Request request; bufferlist bl; encode(type, bl); encode(request, bl); call(new RGWRadosNotifyCR(store, obj, bl, config.notify_timeout_ms, nullptr)); } if (retcode < 0) { ldout(cct, 10) << "failed to notify peers of trim completion" << dendl; return set_cr_error(retcode); } ldpp_dout(dpp, 4) << "bucket index log processing completed in " << ceph::mono_clock::now() - start_time << dendl; return set_cr_done(); } return 0; } class BucketTrimPollCR : public RGWCoroutine { rgw::sal::RadosStore* const store; RGWHTTPManager *const http; const BucketTrimConfig& config; BucketTrimObserver *const observer; const rgw_raw_obj& obj; const std::string name{"trim"}; //< lock name const std::string cookie; const DoutPrefixProvider *dpp; public: BucketTrimPollCR(rgw::sal::RadosStore* store, RGWHTTPManager *http, const BucketTrimConfig& config, BucketTrimObserver *observer, const rgw_raw_obj& obj, const DoutPrefixProvider *dpp) : RGWCoroutine(store->ctx()), store(store), http(http), config(config), observer(observer), obj(obj), cookie(RGWSimpleRadosLockCR::gen_random_cookie(cct)), dpp(dpp) {} int operate(const DoutPrefixProvider *dpp) override; }; int BucketTrimPollCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { for (;;) { set_status("sleeping"); wait(utime_t{static_cast<time_t>(config.trim_interval_sec), 0}); // prevent others from trimming for our entire wait interval set_status("acquiring trim lock"); yield call(new RGWSimpleRadosLockCR(store->svc()->rados->get_async_processor(), store, obj, name, cookie, config.trim_interval_sec)); if (retcode < 0) { ldout(cct, 4) << "failed to lock: " << cpp_strerror(retcode) << dendl; continue; } set_status("trimming"); yield call(new BucketTrimCR(store, http, config, observer, obj, dpp)); if (retcode < 0) { // on errors, unlock so other gateways can try set_status("unlocking"); yield call(new RGWSimpleRadosUnlockCR(store->svc()->rados->get_async_processor(), store, obj, name, cookie)); } } } return 0; } /// tracks a bounded list of events with timestamps. old events can be expired, /// and recent events can be searched by key. expiration depends on events being /// inserted in temporal order template <typename T, typename Clock = ceph::coarse_mono_clock> class RecentEventList { public: using clock_type = Clock; using time_point = typename clock_type::time_point; RecentEventList(size_t max_size, const ceph::timespan& max_duration) : events(max_size), max_duration(max_duration) {} /// insert an event at the given point in time. this time must be at least as /// recent as the last inserted event void insert(T&& value, const time_point& now) { // ceph_assert(events.empty() || now >= events.back().time) events.push_back(Event{std::move(value), now}); } /// performs a linear search for an event matching the given key, whose type /// U can be any that provides operator==(U, T) template <typename U> bool lookup(const U& key) const { for (const auto& event : events) { if (key == event.value) { return true; } } return false; } /// remove events that are no longer recent compared to the given point in time void expire_old(const time_point& now) { const auto expired_before = now - max_duration; while (!events.empty() && events.front().time < expired_before) { events.pop_front(); } } private: struct Event { T value; time_point time; }; boost::circular_buffer<Event> events; const ceph::timespan max_duration; }; namespace rgw { // read bucket trim configuration from ceph context void configure_bucket_trim(CephContext *cct, BucketTrimConfig& config) { const auto& conf = cct->_conf; config.trim_interval_sec = conf.get_val<int64_t>("rgw_sync_log_trim_interval"); config.counter_size = 512; config.buckets_per_interval = conf.get_val<int64_t>("rgw_sync_log_trim_max_buckets"); config.min_cold_buckets_per_interval = conf.get_val<int64_t>("rgw_sync_log_trim_min_cold_buckets"); config.concurrent_buckets = conf.get_val<int64_t>("rgw_sync_log_trim_concurrent_buckets"); config.notify_timeout_ms = 10000; config.recent_size = 128; config.recent_duration = std::chrono::hours(2); } class BucketTrimManager::Impl : public TrimCounters::Server, public BucketTrimObserver { public: rgw::sal::RadosStore* const store; const BucketTrimConfig config; const rgw_raw_obj status_obj; /// count frequency of bucket instance entries in the data changes log BucketChangeCounter counter; using RecentlyTrimmedBucketList = RecentEventList<std::string>; using clock_type = RecentlyTrimmedBucketList::clock_type; /// track recently trimmed buckets to focus trim activity elsewhere RecentlyTrimmedBucketList trimmed; /// serve the bucket trim watch/notify api BucketTrimWatcher watcher; /// protect data shared between data sync, trim, and watch/notify threads std::mutex mutex; Impl(rgw::sal::RadosStore* store, const BucketTrimConfig& config) : store(store), config(config), status_obj(store->svc()->zone->get_zone_params().log_pool, BucketTrimStatus::oid), counter(config.counter_size), trimmed(config.recent_size, config.recent_duration), watcher(store, status_obj, this) {} /// TrimCounters::Server interface for watch/notify api void get_bucket_counters(int count, TrimCounters::Vector& buckets) { buckets.reserve(count); std::lock_guard<std::mutex> lock(mutex); counter.get_highest(count, [&buckets] (const std::string& key, int count) { buckets.emplace_back(key, count); }); ldout(store->ctx(), 20) << "get_bucket_counters: " << buckets << dendl; } void reset_bucket_counters() override { ldout(store->ctx(), 20) << "bucket trim completed" << dendl; std::lock_guard<std::mutex> lock(mutex); counter.clear(); trimmed.expire_old(clock_type::now()); } /// BucketTrimObserver interface to remember successfully-trimmed buckets void on_bucket_trimmed(std::string&& bucket_instance) override { ldout(store->ctx(), 20) << "trimmed bucket instance " << bucket_instance << dendl; std::lock_guard<std::mutex> lock(mutex); trimmed.insert(std::move(bucket_instance), clock_type::now()); } bool trimmed_recently(const std::string_view& bucket_instance) override { std::lock_guard<std::mutex> lock(mutex); return trimmed.lookup(bucket_instance); } }; BucketTrimManager::BucketTrimManager(rgw::sal::RadosStore* store, const BucketTrimConfig& config) : impl(new Impl(store, config)) { } BucketTrimManager::~BucketTrimManager() = default; int BucketTrimManager::init() { return impl->watcher.start(this); } void BucketTrimManager::on_bucket_changed(const std::string_view& bucket) { std::lock_guard<std::mutex> lock(impl->mutex); // filter recently trimmed bucket instances out of bucket change counter if (impl->trimmed.lookup(bucket)) { return; } impl->counter.insert(std::string(bucket)); } RGWCoroutine* BucketTrimManager::create_bucket_trim_cr(RGWHTTPManager *http) { return new BucketTrimPollCR(impl->store, http, impl->config, impl.get(), impl->status_obj, this); } RGWCoroutine* BucketTrimManager::create_admin_bucket_trim_cr(RGWHTTPManager *http) { // return the trim coroutine without any polling return new BucketTrimCR(impl->store, http, impl->config, impl.get(), impl->status_obj, this); } CephContext* BucketTrimManager::get_cct() const { return impl->store->ctx(); } unsigned BucketTrimManager::get_subsys() const { return dout_subsys; } std::ostream& BucketTrimManager::gen_prefix(std::ostream& out) const { return out << "rgw bucket trim manager: "; } } // namespace rgw int bilog_trim(const DoutPrefixProvider* p, rgw::sal::RadosStore* store, RGWBucketInfo& bucket_info, uint64_t gen, int shard_id, std::string_view start_marker, std::string_view end_marker) { auto& logs = bucket_info.layout.logs; auto log = std::find_if(logs.begin(), logs.end(), rgw::matches_gen(gen)); if (log == logs.end()) { ldpp_dout(p, 5) << __PRETTY_FUNCTION__ << ":" << __LINE__ << "ERROR: no log layout with gen=" << gen << dendl; return -ENOENT; } auto log_layout = *log; auto r = store->svc()->bilog_rados->log_trim(p, bucket_info, log_layout, shard_id, start_marker, end_marker); if (r < 0) { ldpp_dout(p, 5) << __PRETTY_FUNCTION__ << ":" << __LINE__ << "ERROR: bilog_rados->log_trim returned r=" << r << dendl; } return r; }
46,253
30.987552
118
cc
null
ceph-main/src/rgw/driver/rados/rgw_trim_bilog.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2017 Red Hat, Inc * * Author: Casey Bodley <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include <memory> #include <string_view> #include "include/common_fwd.h" #include "include/encoding.h" #include "common/ceph_time.h" #include "common/dout.h" #include "rgw_common.h" class RGWCoroutine; class RGWHTTPManager; namespace rgw { namespace sal { class RadosStore; } /// Interface to inform the trim process about which buckets are most active struct BucketChangeObserver { virtual ~BucketChangeObserver() = default; virtual void on_bucket_changed(const std::string_view& bucket_instance) = 0; }; /// Configuration for BucketTrimManager struct BucketTrimConfig { /// time interval in seconds between bucket trim attempts uint32_t trim_interval_sec{0}; /// maximum number of buckets to track with BucketChangeObserver size_t counter_size{0}; /// maximum number of buckets to process each trim interval uint32_t buckets_per_interval{0}; /// minimum number of buckets to choose from the global bucket instance list uint32_t min_cold_buckets_per_interval{0}; /// maximum number of buckets to process in parallel uint32_t concurrent_buckets{0}; /// timeout in ms for bucket trim notify replies uint64_t notify_timeout_ms{0}; /// maximum number of recently trimmed buckets to remember (should be small /// enough for a linear search) size_t recent_size{0}; /// maximum duration to consider a trim as 'recent' (should be some multiple /// of the trim interval, at least) ceph::timespan recent_duration{0}; }; /// fill out the BucketTrimConfig from the ceph context void configure_bucket_trim(CephContext *cct, BucketTrimConfig& config); /// Determines the buckets on which to focus trim activity, using two sources of /// input: the frequency of entries read from the data changes log, and a global /// listing of the bucket.instance metadata. This allows us to trim active /// buckets quickly, while also ensuring that all buckets will eventually trim class BucketTrimManager : public BucketChangeObserver, public DoutPrefixProvider { class Impl; std::unique_ptr<Impl> impl; public: BucketTrimManager(sal::RadosStore *store, const BucketTrimConfig& config); ~BucketTrimManager(); int init(); /// increment a counter for the given bucket instance void on_bucket_changed(const std::string_view& bucket_instance) override; /// create a coroutine to run the bucket trim process every trim interval RGWCoroutine* create_bucket_trim_cr(RGWHTTPManager *http); /// create a coroutine to trim buckets directly via radosgw-admin RGWCoroutine* create_admin_bucket_trim_cr(RGWHTTPManager *http); CephContext *get_cct() const override; unsigned get_subsys() const; std::ostream& gen_prefix(std::ostream& out) const; }; /// provides persistent storage for the trim manager's current position in the /// list of bucket instance metadata struct BucketTrimStatus { std::string marker; //< metadata key of current bucket instance void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(marker, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(marker, p); DECODE_FINISH(p); } static const std::string oid; }; } // namespace rgw WRITE_CLASS_ENCODER(rgw::BucketTrimStatus); int bilog_trim(const DoutPrefixProvider* p, rgw::sal::RadosStore* store, RGWBucketInfo& bucket_info, uint64_t gen, int shard_id, std::string_view start_marker, std::string_view end_marker);
3,920
31.139344
82
h
null
ceph-main/src/rgw/driver/rados/rgw_trim_datalog.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <vector> #include <string> #include "common/errno.h" #include "rgw_trim_datalog.h" #include "rgw_cr_rados.h" #include "rgw_cr_rest.h" #include "rgw_datalog.h" #include "rgw_data_sync.h" #include "rgw_zone.h" #include "rgw_bucket.h" #include "services/svc_zone.h" #include <boost/asio/yield.hpp> #define dout_subsys ceph_subsys_rgw #undef dout_prefix #define dout_prefix (*_dout << "data trim: ") namespace { class DatalogTrimImplCR : public RGWSimpleCoroutine { const DoutPrefixProvider *dpp; rgw::sal::RadosStore* store; boost::intrusive_ptr<RGWAioCompletionNotifier> cn; int shard; std::string marker; std::string* last_trim_marker; public: DatalogTrimImplCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, int shard, const std::string& marker, std::string* last_trim_marker) : RGWSimpleCoroutine(store->ctx()), dpp(dpp), store(store), shard(shard), marker(marker), last_trim_marker(last_trim_marker) { set_description() << "Datalog trim shard=" << shard << " marker=" << marker; } int send_request(const DoutPrefixProvider *dpp) override { set_status() << "sending request"; cn = stack->create_completion_notifier(); return store->svc()->datalog_rados->trim_entries(dpp, shard, marker, cn->completion()); } int request_complete() override { int r = cn->completion()->get_return_value(); ldpp_dout(dpp, 20) << __PRETTY_FUNCTION__ << "(): trim of shard=" << shard << " marker=" << marker << " returned r=" << r << dendl; set_status() << "request complete; ret=" << r; if (r != -ENODATA) { return r; } // nothing left to trim, update last_trim_marker if (*last_trim_marker < marker && marker != store->svc()->datalog_rados->max_marker()) { *last_trim_marker = marker; } return 0; } }; /// return the marker that it's safe to trim up to const std::string& get_stable_marker(const rgw_data_sync_marker& m) { return m.state == m.FullSync ? m.next_step_marker : m.marker; } /// populate the container starting with 'dest' with the minimum stable marker /// of each shard for all of the peers in [first, last) template <typename IterIn, typename IterOut> void take_min_markers(IterIn first, IterIn last, IterOut dest) { if (first == last) { return; } for (auto p = first; p != last; ++p) { auto m = dest; for (auto &shard : p->sync_markers) { const auto& stable = get_stable_marker(shard.second); if (*m > stable) { *m = stable; } ++m; } } } } // anonymous namespace class DataLogTrimCR : public RGWCoroutine { using TrimCR = DatalogTrimImplCR; const DoutPrefixProvider *dpp; rgw::sal::RadosStore* store; RGWHTTPManager *http; const int num_shards; const std::string& zone_id; //< my zone id std::vector<rgw_data_sync_status> peer_status; //< sync status for each peer std::vector<std::string> min_shard_markers; //< min marker per shard std::vector<std::string>& last_trim; //< last trimmed marker per shard int ret{0}; public: DataLogTrimCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, std::vector<std::string>& last_trim) : RGWCoroutine(store->ctx()), dpp(dpp), store(store), http(http), num_shards(num_shards), zone_id(store->svc()->zone->get_zone().id), peer_status(store->svc()->zone->get_zone_data_notify_to_map().size()), min_shard_markers(num_shards, std::string(store->svc()->datalog_rados->max_marker())), last_trim(last_trim) {} int operate(const DoutPrefixProvider *dpp) override; }; int DataLogTrimCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { ldpp_dout(dpp, 10) << "fetching sync status for zone " << zone_id << dendl; set_status("fetching sync status"); yield { // query data sync status from each sync peer rgw_http_param_pair params[] = { { "type", "data" }, { "status", nullptr }, { "source-zone", zone_id.c_str() }, { nullptr, nullptr } }; auto p = peer_status.begin(); for (auto& c : store->svc()->zone->get_zone_data_notify_to_map()) { ldpp_dout(dpp, 20) << "query sync status from " << c.first << dendl; using StatusCR = RGWReadRESTResourceCR<rgw_data_sync_status>; spawn(new StatusCR(cct, c.second, http, "/admin/log/", params, &*p), false); ++p; } } // must get a successful reply from all peers to consider trimming ret = 0; while (ret == 0 && num_spawned() > 0) { yield wait_for_child(); collect_next(&ret); } drain_all(); if (ret < 0) { ldpp_dout(dpp, 4) << "failed to fetch sync status from all peers" << dendl; return set_cr_error(ret); } ldpp_dout(dpp, 10) << "trimming log shards" << dendl; set_status("trimming log shards"); yield { // determine the minimum marker for each shard take_min_markers(peer_status.begin(), peer_status.end(), min_shard_markers.begin()); for (int i = 0; i < num_shards; i++) { const auto& m = min_shard_markers[i]; if (m <= last_trim[i]) { continue; } ldpp_dout(dpp, 10) << "trimming log shard " << i << " at marker=" << m << " last_trim=" << last_trim[i] << dendl; spawn(new TrimCR(dpp, store, i, m, &last_trim[i]), true); } } return set_cr_done(); } return 0; } RGWCoroutine* create_admin_data_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, std::vector<std::string>& markers) { return new DataLogTrimCR(dpp, store, http, num_shards, markers); } class DataLogTrimPollCR : public RGWCoroutine { const DoutPrefixProvider *dpp; rgw::sal::RadosStore* store; RGWHTTPManager *http; const int num_shards; const utime_t interval; //< polling interval const std::string lock_oid; //< use first data log shard for lock const std::string lock_cookie; std::vector<std::string> last_trim; //< last trimmed marker per shard public: DataLogTrimPollCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval) : RGWCoroutine(store->ctx()), dpp(dpp), store(store), http(http), num_shards(num_shards), interval(interval), lock_oid(store->svc()->datalog_rados->get_oid(0, 0)), lock_cookie(RGWSimpleRadosLockCR::gen_random_cookie(cct)), last_trim(num_shards) {} int operate(const DoutPrefixProvider *dpp) override; }; int DataLogTrimPollCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { for (;;) { set_status("sleeping"); wait(interval); // request a 'data_trim' lock that covers the entire wait interval to // prevent other gateways from attempting to trim for the duration set_status("acquiring trim lock"); // interval is a small number and unlikely to overflow // coverity[store_truncates_time_t:SUPPRESS] yield call(new RGWSimpleRadosLockCR(store->svc()->rados->get_async_processor(), store, rgw_raw_obj(store->svc()->zone->get_zone_params().log_pool, lock_oid), "data_trim", lock_cookie, interval.sec())); if (retcode < 0) { // if the lock is already held, go back to sleep and try again later ldpp_dout(dpp, 4) << "failed to lock " << lock_oid << ", trying again in " << interval.sec() << "s" << dendl; continue; } set_status("trimming"); yield call(new DataLogTrimCR(dpp, store, http, num_shards, last_trim)); // note that the lock is not released. this is intentional, as it avoids // duplicating this work in other gateways } } return 0; } RGWCoroutine* create_data_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval) { return new DataLogTrimPollCR(dpp, store, http, num_shards, interval); }
8,526
32.308594
112
cc
null
ceph-main/src/rgw/driver/rados/rgw_trim_datalog.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string> #include <vector> #include "common/dout.h" class RGWCoroutine; class RGWRados; class RGWHTTPManager; class utime_t; namespace rgw { namespace sal { class RadosStore; } } // DataLogTrimCR factory function extern RGWCoroutine* create_data_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval); // factory function for datalog trim via radosgw-admin RGWCoroutine* create_admin_data_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, std::vector<std::string>& markers);
965
32.310345
104
h
null
ceph-main/src/rgw/driver/rados/rgw_trim_mdlog.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "common/errno.h" #include "rgw_trim_mdlog.h" #include "rgw_sync.h" #include "rgw_cr_rados.h" #include "rgw_cr_rest.h" #include "rgw_zone.h" #include "services/svc_zone.h" #include "services/svc_meta.h" #include "services/svc_mdlog.h" #include "services/svc_cls.h" #include <boost/asio/yield.hpp> #define dout_subsys ceph_subsys_rgw #undef dout_prefix #define dout_prefix (*_dout << "meta trim: ") /// purge all log shards for the given mdlog class PurgeLogShardsCR : public RGWShardCollectCR { rgw::sal::RadosStore* const store; const RGWMetadataLog* mdlog; const int num_shards; rgw_raw_obj obj; int i{0}; static constexpr int max_concurrent = 16; int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "failed to remove mdlog shard: " << cpp_strerror(r) << dendl; } return r; } public: PurgeLogShardsCR(rgw::sal::RadosStore* store, const RGWMetadataLog* mdlog, const rgw_pool& pool, int num_shards) : RGWShardCollectCR(store->ctx(), max_concurrent), store(store), mdlog(mdlog), num_shards(num_shards), obj(pool, "") {} bool spawn_next() override { if (i == num_shards) { return false; } mdlog->get_shard_oid(i++, obj.oid); spawn(new RGWRadosRemoveCR(store, obj), false); return true; } }; using Cursor = RGWPeriodHistory::Cursor; /// purge mdlogs from the oldest up to (but not including) the given realm_epoch class PurgePeriodLogsCR : public RGWCoroutine { struct Svc { RGWSI_Zone *zone; RGWSI_MDLog *mdlog; } svc; const DoutPrefixProvider *dpp; rgw::sal::RadosStore* const store; RGWMetadataManager *const metadata; RGWObjVersionTracker objv; Cursor cursor; epoch_t realm_epoch; epoch_t *last_trim_epoch; //< update last trim on success public: PurgePeriodLogsCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, epoch_t realm_epoch, epoch_t *last_trim) : RGWCoroutine(store->ctx()), dpp(dpp), store(store), metadata(store->ctl()->meta.mgr), realm_epoch(realm_epoch), last_trim_epoch(last_trim) { svc.zone = store->svc()->zone; svc.mdlog = store->svc()->mdlog; } int operate(const DoutPrefixProvider *dpp) override; }; int PurgePeriodLogsCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { // read our current oldest log period yield call(svc.mdlog->read_oldest_log_period_cr(dpp, &cursor, &objv)); if (retcode < 0) { return set_cr_error(retcode); } ceph_assert(cursor); ldpp_dout(dpp, 20) << "oldest log realm_epoch=" << cursor.get_epoch() << " period=" << cursor.get_period().get_id() << dendl; // trim -up to- the given realm_epoch while (cursor.get_epoch() < realm_epoch) { ldpp_dout(dpp, 4) << "purging log shards for realm_epoch=" << cursor.get_epoch() << " period=" << cursor.get_period().get_id() << dendl; yield { const auto mdlog = svc.mdlog->get_log(cursor.get_period().get_id()); const auto& pool = svc.zone->get_zone_params().log_pool; auto num_shards = cct->_conf->rgw_md_log_max_shards; call(new PurgeLogShardsCR(store, mdlog, pool, num_shards)); } if (retcode < 0) { ldpp_dout(dpp, 1) << "failed to remove log shards: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } ldpp_dout(dpp, 10) << "removed log shards for realm_epoch=" << cursor.get_epoch() << " period=" << cursor.get_period().get_id() << dendl; // update our mdlog history yield call(svc.mdlog->trim_log_period_cr(dpp, cursor, &objv)); if (retcode == -ENOENT) { // must have raced to update mdlog history. return success and allow the // winner to continue purging ldpp_dout(dpp, 10) << "already removed log shards for realm_epoch=" << cursor.get_epoch() << " period=" << cursor.get_period().get_id() << dendl; return set_cr_done(); } else if (retcode < 0) { ldpp_dout(dpp, 1) << "failed to remove log shards for realm_epoch=" << cursor.get_epoch() << " period=" << cursor.get_period().get_id() << " with: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } if (*last_trim_epoch < cursor.get_epoch()) { *last_trim_epoch = cursor.get_epoch(); } ceph_assert(cursor.has_next()); // get_current() should always come after cursor.next(); } return set_cr_done(); } return 0; } namespace { using connection_map = std::map<std::string, std::unique_ptr<RGWRESTConn>>; /// construct a RGWRESTConn for each zone in the realm template <typename Zonegroups> connection_map make_peer_connections(rgw::sal::RadosStore* store, const Zonegroups& zonegroups) { connection_map connections; for (auto& g : zonegroups) { for (auto& z : g.second.zones) { std::unique_ptr<RGWRESTConn> conn{ new RGWRESTConn(store->ctx(), store, z.first.id, z.second.endpoints, g.second.api_name)}; connections.emplace(z.first.id, std::move(conn)); } } return connections; } /// return the marker that it's safe to trim up to const std::string& get_stable_marker(const rgw_meta_sync_marker& m) { return m.state == m.FullSync ? m.next_step_marker : m.marker; } /// comparison operator for take_min_status() bool operator<(const rgw_meta_sync_marker& lhs, const rgw_meta_sync_marker& rhs) { // sort by stable marker return get_stable_marker(lhs) < get_stable_marker(rhs); } /// populate the status with the minimum stable marker of each shard for any /// peer whose realm_epoch matches the minimum realm_epoch in the input template <typename Iter> int take_min_status(CephContext *cct, Iter first, Iter last, rgw_meta_sync_status *status) { if (first == last) { return -EINVAL; } const size_t num_shards = cct->_conf->rgw_md_log_max_shards; status->sync_info.realm_epoch = std::numeric_limits<epoch_t>::max(); for (auto p = first; p != last; ++p) { // validate peer's shard count if (p->sync_markers.size() != num_shards) { ldout(cct, 1) << "take_min_status got peer status with " << p->sync_markers.size() << " shards, expected " << num_shards << dendl; return -EINVAL; } if (p->sync_info.realm_epoch < status->sync_info.realm_epoch) { // earlier epoch, take its entire status *status = std::move(*p); } else if (p->sync_info.realm_epoch == status->sync_info.realm_epoch) { // same epoch, take any earlier markers auto m = status->sync_markers.begin(); for (auto& shard : p->sync_markers) { if (shard.second < m->second) { m->second = std::move(shard.second); } ++m; } } } return 0; } struct TrimEnv { const DoutPrefixProvider *dpp; rgw::sal::RadosStore* const store; RGWHTTPManager *const http; int num_shards; const rgw_zone_id& zone; Cursor current; //< cursor to current period epoch_t last_trim_epoch{0}; //< epoch of last mdlog that was purged TrimEnv(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards) : dpp(dpp), store(store), http(http), num_shards(num_shards), zone(store->svc()->zone->zone_id()), current(store->svc()->mdlog->get_period_history()->get_current()) {} }; struct MasterTrimEnv : public TrimEnv { connection_map connections; //< peer connections std::vector<rgw_meta_sync_status> peer_status; //< sync status for each peer /// last trim marker for each shard, only applies to current period's mdlog std::vector<std::string> last_trim_markers; MasterTrimEnv(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards) : TrimEnv(dpp, store, http, num_shards), last_trim_markers(num_shards) { auto& period = current.get_period(); connections = make_peer_connections(store, period.get_map().zonegroups); connections.erase(zone.id); peer_status.resize(connections.size()); } }; struct PeerTrimEnv : public TrimEnv { /// last trim timestamp for each shard, only applies to current period's mdlog std::vector<ceph::real_time> last_trim_timestamps; PeerTrimEnv(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards) : TrimEnv(dpp, store, http, num_shards), last_trim_timestamps(num_shards) {} void set_num_shards(int num_shards) { this->num_shards = num_shards; last_trim_timestamps.resize(num_shards); } }; } // anonymous namespace /// spawn a trim cr for each shard that needs it, while limiting the number /// of concurrent shards class MetaMasterTrimShardCollectCR : public RGWShardCollectCR { private: static constexpr int MAX_CONCURRENT_SHARDS = 16; MasterTrimEnv& env; RGWMetadataLog *mdlog; int shard_id{0}; std::string oid; const rgw_meta_sync_status& sync_status; int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "failed to trim mdlog shard: " << cpp_strerror(r) << dendl; } return r; } public: MetaMasterTrimShardCollectCR(MasterTrimEnv& env, RGWMetadataLog *mdlog, const rgw_meta_sync_status& sync_status) : RGWShardCollectCR(env.store->ctx(), MAX_CONCURRENT_SHARDS), env(env), mdlog(mdlog), sync_status(sync_status) {} bool spawn_next() override; }; bool MetaMasterTrimShardCollectCR::spawn_next() { while (shard_id < env.num_shards) { auto m = sync_status.sync_markers.find(shard_id); if (m == sync_status.sync_markers.end()) { shard_id++; continue; } auto& stable = get_stable_marker(m->second); auto& last_trim = env.last_trim_markers[shard_id]; if (stable <= last_trim) { // already trimmed ldpp_dout(env.dpp, 20) << "skipping log shard " << shard_id << " at marker=" << stable << " last_trim=" << last_trim << " realm_epoch=" << sync_status.sync_info.realm_epoch << dendl; shard_id++; continue; } mdlog->get_shard_oid(shard_id, oid); ldpp_dout(env.dpp, 10) << "trimming log shard " << shard_id << " at marker=" << stable << " last_trim=" << last_trim << " realm_epoch=" << sync_status.sync_info.realm_epoch << dendl; spawn(new RGWSyncLogTrimCR(env.dpp, env.store, oid, stable, &last_trim), false); shard_id++; return true; } return false; } /// spawn rest requests to read each peer's sync status class MetaMasterStatusCollectCR : public RGWShardCollectCR { static constexpr int MAX_CONCURRENT_SHARDS = 16; MasterTrimEnv& env; connection_map::iterator c; std::vector<rgw_meta_sync_status>::iterator s; int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "failed to fetch metadata sync status: " << cpp_strerror(r) << dendl; } return r; } public: explicit MetaMasterStatusCollectCR(MasterTrimEnv& env) : RGWShardCollectCR(env.store->ctx(), MAX_CONCURRENT_SHARDS), env(env), c(env.connections.begin()), s(env.peer_status.begin()) {} bool spawn_next() override { if (c == env.connections.end()) { return false; } static rgw_http_param_pair params[] = { { "type", "metadata" }, { "status", nullptr }, { nullptr, nullptr } }; ldout(cct, 20) << "query sync status from " << c->first << dendl; auto conn = c->second.get(); using StatusCR = RGWReadRESTResourceCR<rgw_meta_sync_status>; spawn(new StatusCR(cct, conn, env.http, "/admin/log/", params, &*s), false); ++c; ++s; return true; } }; class MetaMasterTrimCR : public RGWCoroutine { MasterTrimEnv& env; rgw_meta_sync_status min_status; //< minimum sync status of all peers int ret{0}; public: explicit MetaMasterTrimCR(MasterTrimEnv& env) : RGWCoroutine(env.store->ctx()), env(env) {} int operate(const DoutPrefixProvider *dpp) override; }; int MetaMasterTrimCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { // TODO: detect this and fail before we spawn the trim thread? if (env.connections.empty()) { ldpp_dout(dpp, 4) << "no peers, exiting" << dendl; return set_cr_done(); } ldpp_dout(dpp, 10) << "fetching sync status for zone " << env.zone << dendl; // query mdlog sync status from peers yield call(new MetaMasterStatusCollectCR(env)); // must get a successful reply from all peers to consider trimming if (ret < 0) { ldpp_dout(dpp, 4) << "failed to fetch sync status from all peers" << dendl; return set_cr_error(ret); } // determine the minimum epoch and markers ret = take_min_status(env.store->ctx(), env.peer_status.begin(), env.peer_status.end(), &min_status); if (ret < 0) { ldpp_dout(dpp, 4) << "failed to calculate min sync status from peers" << dendl; return set_cr_error(ret); } yield { auto store = env.store; auto epoch = min_status.sync_info.realm_epoch; ldpp_dout(dpp, 4) << "realm epoch min=" << epoch << " current=" << env.current.get_epoch()<< dendl; if (epoch > env.last_trim_epoch + 1) { // delete any prior mdlog periods spawn(new PurgePeriodLogsCR(dpp, store, epoch, &env.last_trim_epoch), true); } else { ldpp_dout(dpp, 10) << "mdlogs already purged up to realm_epoch " << env.last_trim_epoch << dendl; } // if realm_epoch == current, trim mdlog based on markers if (epoch == env.current.get_epoch()) { auto mdlog = store->svc()->mdlog->get_log(env.current.get_period().get_id()); spawn(new MetaMasterTrimShardCollectCR(env, mdlog, min_status), true); } } // ignore any errors during purge/trim because we want to hold the lock open return set_cr_done(); } return 0; } /// read the first entry of the master's mdlog shard and trim to that position class MetaPeerTrimShardCR : public RGWCoroutine { RGWMetaSyncEnv& env; RGWMetadataLog *mdlog; const std::string& period_id; const int shard_id; RGWMetadataLogInfo info; ceph::real_time stable; //< safe timestamp to trim, according to master ceph::real_time *last_trim; //< last trimmed timestamp, updated on trim rgw_mdlog_shard_data result; //< result from master's mdlog listing public: MetaPeerTrimShardCR(RGWMetaSyncEnv& env, RGWMetadataLog *mdlog, const std::string& period_id, int shard_id, ceph::real_time *last_trim) : RGWCoroutine(env.store->ctx()), env(env), mdlog(mdlog), period_id(period_id), shard_id(shard_id), last_trim(last_trim) {} int operate(const DoutPrefixProvider *dpp) override; }; int MetaPeerTrimShardCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { // query master's first mdlog entry for this shard yield call(create_list_remote_mdlog_shard_cr(&env, period_id, shard_id, "", 1, &result)); if (retcode < 0) { ldpp_dout(dpp, 5) << "failed to read first entry from master's mdlog shard " << shard_id << " for period " << period_id << ": " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } if (result.entries.empty()) { // if there are no mdlog entries, we don't have a timestamp to compare. we // can't just trim everything, because there could be racing updates since // this empty reply. query the mdlog shard info to read its max timestamp, // then retry the listing to make sure it's still empty before trimming to // that ldpp_dout(dpp, 10) << "empty master mdlog shard " << shard_id << ", reading last timestamp from shard info" << dendl; // read the mdlog shard info for the last timestamp yield call(create_read_remote_mdlog_shard_info_cr(&env, period_id, shard_id, &info)); if (retcode < 0) { ldpp_dout(dpp, 5) << "failed to read info from master's mdlog shard " << shard_id << " for period " << period_id << ": " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } if (ceph::real_clock::is_zero(info.last_update)) { return set_cr_done(); // nothing to trim } ldpp_dout(dpp, 10) << "got mdlog shard info with last update=" << info.last_update << dendl; // re-read the master's first mdlog entry to make sure it hasn't changed yield call(create_list_remote_mdlog_shard_cr(&env, period_id, shard_id, "", 1, &result)); if (retcode < 0) { ldpp_dout(dpp, 5) << "failed to read first entry from master's mdlog shard " << shard_id << " for period " << period_id << ": " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } // if the mdlog is still empty, trim to max marker if (result.entries.empty()) { stable = info.last_update; } else { stable = result.entries.front().timestamp; // can only trim -up to- master's first timestamp, so subtract a second. // (this is why we use timestamps instead of markers for the peers) stable -= std::chrono::seconds(1); } } else { stable = result.entries.front().timestamp; stable -= std::chrono::seconds(1); } if (stable <= *last_trim) { ldpp_dout(dpp, 10) << "skipping log shard " << shard_id << " at timestamp=" << stable << " last_trim=" << *last_trim << dendl; return set_cr_done(); } ldpp_dout(dpp, 10) << "trimming log shard " << shard_id << " at timestamp=" << stable << " last_trim=" << *last_trim << dendl; yield { std::string oid; mdlog->get_shard_oid(shard_id, oid); call(new RGWRadosTimelogTrimCR(dpp, env.store, oid, real_time{}, stable, "", "")); } if (retcode < 0 && retcode != -ENODATA) { ldpp_dout(dpp, 1) << "failed to trim mdlog shard " << shard_id << ": " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } *last_trim = stable; return set_cr_done(); } return 0; } class MetaPeerTrimShardCollectCR : public RGWShardCollectCR { static constexpr int MAX_CONCURRENT_SHARDS = 16; PeerTrimEnv& env; RGWMetadataLog *mdlog; const std::string& period_id; RGWMetaSyncEnv meta_env; //< for RGWListRemoteMDLogShardCR int shard_id{0}; int handle_result(int r) override { if (r == -ENOENT) { // ENOENT is not a fatal error return 0; } if (r < 0) { ldout(cct, 4) << "failed to trim mdlog shard: " << cpp_strerror(r) << dendl; } return r; } public: MetaPeerTrimShardCollectCR(PeerTrimEnv& env, RGWMetadataLog *mdlog) : RGWShardCollectCR(env.store->ctx(), MAX_CONCURRENT_SHARDS), env(env), mdlog(mdlog), period_id(env.current.get_period().get_id()) { meta_env.init(env.dpp, cct, env.store, env.store->svc()->zone->get_master_conn(), env.store->svc()->rados->get_async_processor(), env.http, nullptr, env.store->getRados()->get_sync_tracer()); } bool spawn_next() override; }; bool MetaPeerTrimShardCollectCR::spawn_next() { if (shard_id >= env.num_shards) { return false; } auto& last_trim = env.last_trim_timestamps[shard_id]; spawn(new MetaPeerTrimShardCR(meta_env, mdlog, period_id, shard_id, &last_trim), false); shard_id++; return true; } class MetaPeerTrimCR : public RGWCoroutine { PeerTrimEnv& env; rgw_mdlog_info mdlog_info; //< master's mdlog info public: explicit MetaPeerTrimCR(PeerTrimEnv& env) : RGWCoroutine(env.store->ctx()), env(env) {} int operate(const DoutPrefixProvider *dpp) override; }; int MetaPeerTrimCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { ldpp_dout(dpp, 10) << "fetching master mdlog info" << dendl; yield { // query mdlog_info from master for oldest_log_period rgw_http_param_pair params[] = { { "type", "metadata" }, { nullptr, nullptr } }; using LogInfoCR = RGWReadRESTResourceCR<rgw_mdlog_info>; call(new LogInfoCR(cct, env.store->svc()->zone->get_master_conn(), env.http, "/admin/log/", params, &mdlog_info)); } if (retcode < 0) { ldpp_dout(dpp, 4) << "failed to read mdlog info from master" << dendl; return set_cr_error(retcode); } // use master's shard count instead env.set_num_shards(mdlog_info.num_shards); if (mdlog_info.realm_epoch > env.last_trim_epoch + 1) { // delete any prior mdlog periods yield call(new PurgePeriodLogsCR(dpp, env.store, mdlog_info.realm_epoch, &env.last_trim_epoch)); } else { ldpp_dout(dpp, 10) << "mdlogs already purged through realm_epoch " << env.last_trim_epoch << dendl; } // if realm_epoch == current, trim mdlog based on master's markers if (mdlog_info.realm_epoch == env.current.get_epoch()) { yield { auto mdlog = env.store->svc()->mdlog->get_log(env.current.get_period().get_id()); call(new MetaPeerTrimShardCollectCR(env, mdlog)); // ignore any errors during purge/trim because we want to hold the lock open } } return set_cr_done(); } return 0; } class MetaTrimPollCR : public RGWCoroutine { rgw::sal::RadosStore* const store; const utime_t interval; //< polling interval const rgw_raw_obj obj; const std::string name{"meta_trim"}; //< lock name const std::string cookie; protected: /// allocate the coroutine to run within the lease virtual RGWCoroutine* alloc_cr() = 0; public: MetaTrimPollCR(rgw::sal::RadosStore* store, utime_t interval) : RGWCoroutine(store->ctx()), store(store), interval(interval), obj(store->svc()->zone->get_zone_params().log_pool, RGWMetadataLogHistory::oid), cookie(RGWSimpleRadosLockCR::gen_random_cookie(cct)) {} int operate(const DoutPrefixProvider *dpp) override; }; int MetaTrimPollCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { for (;;) { set_status("sleeping"); wait(interval); // prevent others from trimming for our entire wait interval set_status("acquiring trim lock"); // interval is a small number and unlikely to overflow // coverity[store_truncates_time_t:SUPPRESS] yield call(new RGWSimpleRadosLockCR(store->svc()->rados->get_async_processor(), store, obj, name, cookie, interval.sec())); if (retcode < 0) { ldout(cct, 4) << "failed to lock: " << cpp_strerror(retcode) << dendl; continue; } set_status("trimming"); yield call(alloc_cr()); if (retcode < 0) { // on errors, unlock so other gateways can try set_status("unlocking"); yield call(new RGWSimpleRadosUnlockCR(store->svc()->rados->get_async_processor(), store, obj, name, cookie)); } } } return 0; } class MetaMasterTrimPollCR : public MetaTrimPollCR { MasterTrimEnv env; //< trim state to share between calls RGWCoroutine* alloc_cr() override { return new MetaMasterTrimCR(env); } public: MetaMasterTrimPollCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval) : MetaTrimPollCR(store, interval), env(dpp, store, http, num_shards) {} }; class MetaPeerTrimPollCR : public MetaTrimPollCR { PeerTrimEnv env; //< trim state to share between calls RGWCoroutine* alloc_cr() override { return new MetaPeerTrimCR(env); } public: MetaPeerTrimPollCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval) : MetaTrimPollCR(store, interval), env(dpp, store, http, num_shards) {} }; namespace { bool sanity_check_endpoints(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store) { bool retval = true; auto current = store->svc()->mdlog->get_period_history()->get_current(); const auto& period = current.get_period(); for (const auto& [_, zonegroup] : period.get_map().zonegroups) { if (zonegroup.endpoints.empty()) { ldpp_dout(dpp, -1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " WARNING: Cluster is is misconfigured! " << " Zonegroup " << zonegroup.get_name() << " (" << zonegroup.get_id() << ") in Realm " << period.get_realm_name() << " ( " << period.get_realm() << ") " << " has no endpoints!" << dendl; } for (const auto& [_, zone] : zonegroup.zones) { if (zone.endpoints.empty()) { ldpp_dout(dpp, -1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " ERROR: Cluster is is misconfigured! " << " Zone " << zone.name << " (" << zone.id << ") in Zonegroup " << zonegroup.get_name() << " ( " << zonegroup.get_id() << ") in Realm " << period.get_realm_name() << " ( " << period.get_realm() << ") " << " has no endpoints! Trimming is impossible." << dendl; retval = false; } } } return retval; } } RGWCoroutine* create_meta_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval) { if (!sanity_check_endpoints(dpp, store)) { ldpp_dout(dpp, -1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " ERROR: Cluster is is misconfigured! Refusing to trim." << dendl; return nullptr; } if (store->svc()->zone->is_meta_master()) { return new MetaMasterTrimPollCR(dpp, store, http, num_shards, interval); } return new MetaPeerTrimPollCR(dpp, store, http, num_shards, interval); } struct MetaMasterAdminTrimCR : private MasterTrimEnv, public MetaMasterTrimCR { MetaMasterAdminTrimCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards) : MasterTrimEnv(dpp, store, http, num_shards), MetaMasterTrimCR(*static_cast<MasterTrimEnv*>(this)) {} }; struct MetaPeerAdminTrimCR : private PeerTrimEnv, public MetaPeerTrimCR { MetaPeerAdminTrimCR(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards) : PeerTrimEnv(dpp, store, http, num_shards), MetaPeerTrimCR(*static_cast<PeerTrimEnv*>(this)) {} }; RGWCoroutine* create_admin_meta_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards) { if (!sanity_check_endpoints(dpp, store)) { ldpp_dout(dpp, -1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " ERROR: Cluster is is misconfigured! Refusing to trim." << dendl; return nullptr; } if (store->svc()->zone->is_meta_master()) { return new MetaMasterAdminTrimCR(dpp, store, http, num_shards); } return new MetaPeerAdminTrimCR(dpp, store, http, num_shards); }
27,534
33.461827
121
cc
null
ceph-main/src/rgw/driver/rados/rgw_trim_mdlog.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once class RGWCoroutine; class DoutPrefixProvider; class RGWRados; class RGWHTTPManager; class utime_t; namespace rgw { namespace sal { class RadosStore; } } // MetaLogTrimCR factory function RGWCoroutine* create_meta_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval); // factory function for mdlog trim via radosgw-admin RGWCoroutine* create_admin_meta_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards);
908
33.961538
74
h
null
ceph-main/src/rgw/driver/rados/rgw_user.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "common/errno.h" #include "rgw_user.h" #include "rgw_bucket.h" #include "rgw_quota.h" #include "services/svc_user.h" #include "services/svc_meta.h" #define dout_subsys ceph_subsys_rgw using namespace std; extern void op_type_to_str(uint32_t mask, char *buf, int len); static string key_type_to_str(int key_type) { switch (key_type) { case KEY_TYPE_SWIFT: return "swift"; break; default: return "s3"; break; } } static bool char_is_unreserved_url(char c) { if (isalnum(c)) return true; switch (c) { case '-': case '.': case '_': case '~': return true; default: return false; } } static bool validate_access_key(string& key) { const char *p = key.c_str(); while (*p) { if (!char_is_unreserved_url(*p)) return false; p++; } return true; } static void set_err_msg(std::string *sink, std::string msg) { if (sink && !msg.empty()) *sink = msg; } /* * Dump either the full user info or a subset to a formatter. * * NOTE: It is the caller's responsibility to ensure that the * formatter is flushed at the correct time. */ static void dump_subusers_info(Formatter *f, RGWUserInfo &info) { map<string, RGWSubUser>::iterator uiter; f->open_array_section("subusers"); for (uiter = info.subusers.begin(); uiter != info.subusers.end(); ++uiter) { RGWSubUser& u = uiter->second; f->open_object_section("user"); string s; info.user_id.to_str(s); f->dump_format("id", "%s:%s", s.c_str(), u.name.c_str()); char buf[256]; rgw_perm_to_str(u.perm_mask, buf, sizeof(buf)); f->dump_string("permissions", buf); f->close_section(); } f->close_section(); } static void dump_access_keys_info(Formatter *f, RGWUserInfo &info) { map<string, RGWAccessKey>::iterator kiter; f->open_array_section("keys"); for (kiter = info.access_keys.begin(); kiter != info.access_keys.end(); ++kiter) { RGWAccessKey& k = kiter->second; const char *sep = (k.subuser.empty() ? "" : ":"); const char *subuser = (k.subuser.empty() ? "" : k.subuser.c_str()); f->open_object_section("key"); string s; info.user_id.to_str(s); f->dump_format("user", "%s%s%s", s.c_str(), sep, subuser); f->dump_string("access_key", k.id); f->dump_string("secret_key", k.key); f->close_section(); } f->close_section(); } static void dump_swift_keys_info(Formatter *f, RGWUserInfo &info) { map<string, RGWAccessKey>::iterator kiter; f->open_array_section("swift_keys"); for (kiter = info.swift_keys.begin(); kiter != info.swift_keys.end(); ++kiter) { RGWAccessKey& k = kiter->second; const char *sep = (k.subuser.empty() ? "" : ":"); const char *subuser = (k.subuser.empty() ? "" : k.subuser.c_str()); f->open_object_section("key"); string s; info.user_id.to_str(s); f->dump_format("user", "%s%s%s", s.c_str(), sep, subuser); f->dump_string("secret_key", k.key); f->close_section(); } f->close_section(); } static void dump_user_info(Formatter *f, RGWUserInfo &info, RGWStorageStats *stats = NULL) { f->open_object_section("user_info"); encode_json("tenant", info.user_id.tenant, f); encode_json("user_id", info.user_id.id, f); encode_json("display_name", info.display_name, f); encode_json("email", info.user_email, f); encode_json("suspended", (int)info.suspended, f); encode_json("max_buckets", (int)info.max_buckets, f); dump_subusers_info(f, info); dump_access_keys_info(f, info); dump_swift_keys_info(f, info); encode_json("caps", info.caps, f); char buf[256]; op_type_to_str(info.op_mask, buf, sizeof(buf)); encode_json("op_mask", (const char *)buf, f); encode_json("system", (bool)info.system, f); encode_json("admin", (bool)info.admin, f); encode_json("default_placement", info.default_placement.name, f); encode_json("default_storage_class", info.default_placement.storage_class, f); encode_json("placement_tags", info.placement_tags, f); encode_json("bucket_quota", info.quota.bucket_quota, f); encode_json("user_quota", info.quota.user_quota, f); encode_json("temp_url_keys", info.temp_url_keys, f); string user_source_type; switch ((RGWIdentityType)info.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", info.mfa_ids, f); if (stats) { encode_json("stats", *stats, f); } f->close_section(); } static int user_add_helper(RGWUserAdminOpState& op_state, std::string *err_msg) { int ret = 0; const rgw_user& uid = op_state.get_user_id(); std::string user_email = op_state.get_user_email(); std::string display_name = op_state.get_display_name(); // fail if the user exists already if (op_state.has_existing_user()) { if (op_state.found_by_email) { set_err_msg(err_msg, "email: " + user_email + " is the email address of an existing user"); ret = -ERR_EMAIL_EXIST; } else if (op_state.found_by_key) { set_err_msg(err_msg, "duplicate key provided"); ret = -ERR_KEY_EXIST; } else { set_err_msg(err_msg, "user: " + uid.to_str() + " exists"); ret = -EEXIST; } return ret; } // fail if the user_info has already been populated if (op_state.is_populated()) { set_err_msg(err_msg, "cannot overwrite already populated user"); return -EEXIST; } // fail if the display name was not included if (display_name.empty()) { set_err_msg(err_msg, "no display name specified"); return -EINVAL; } return ret; } RGWAccessKeyPool::RGWAccessKeyPool(RGWUser* usr) { if (!usr) { return; } user = usr; driver = user->get_driver(); } int RGWAccessKeyPool::init(RGWUserAdminOpState& op_state) { if (!op_state.is_initialized()) { keys_allowed = false; return -EINVAL; } const rgw_user& uid = op_state.get_user_id(); if (uid.compare(RGW_USER_ANON_ID) == 0) { keys_allowed = false; return -EINVAL; } swift_keys = op_state.get_swift_keys(); access_keys = op_state.get_access_keys(); keys_allowed = true; return 0; } RGWUserAdminOpState::RGWUserAdminOpState(rgw::sal::Driver* driver) { user = driver->get_user(rgw_user(RGW_USER_ANON_ID)); } void RGWUserAdminOpState::set_user_id(const rgw_user& id) { if (id.empty()) return; user->get_info().user_id = id; } void RGWUserAdminOpState::set_subuser(std::string& _subuser) { if (_subuser.empty()) return; size_t pos = _subuser.find(":"); if (pos != string::npos) { rgw_user tmp_id; tmp_id.from_str(_subuser.substr(0, pos)); if (tmp_id.tenant.empty()) { user->get_info().user_id.id = tmp_id.id; } else { user->get_info().user_id = tmp_id; } subuser = _subuser.substr(pos+1); } else { subuser = _subuser; } subuser_specified = true; } void RGWUserAdminOpState::set_user_info(RGWUserInfo& user_info) { user->get_info() = user_info; } void RGWUserAdminOpState::set_user_version_tracker(RGWObjVersionTracker& objv_tracker) { user->get_version_tracker() = objv_tracker; } const rgw_user& RGWUserAdminOpState::get_user_id() { return user->get_id(); } RGWUserInfo& RGWUserAdminOpState::get_user_info() { return user->get_info(); } map<std::string, RGWAccessKey>* RGWUserAdminOpState::get_swift_keys() { return &user->get_info().swift_keys; } map<std::string, RGWAccessKey>* RGWUserAdminOpState::get_access_keys() { return &user->get_info().access_keys; } map<std::string, RGWSubUser>* RGWUserAdminOpState::get_subusers() { return &user->get_info().subusers; } RGWUserCaps *RGWUserAdminOpState::get_caps_obj() { return &user->get_info().caps; } std::string RGWUserAdminOpState::build_default_swift_kid() { if (user->get_id().empty() || subuser.empty()) return ""; std::string kid; user->get_id().to_str(kid); kid.append(":"); kid.append(subuser); return kid; } std::string RGWUserAdminOpState::generate_subuser() { if (user->get_id().empty()) return ""; std::string generated_subuser; user->get_id().to_str(generated_subuser); std::string rand_suffix; int sub_buf_size = RAND_SUBUSER_LEN + 1; char sub_buf[RAND_SUBUSER_LEN + 1]; gen_rand_alphanumeric_upper(g_ceph_context, sub_buf, sub_buf_size); rand_suffix = sub_buf; if (rand_suffix.empty()) return ""; generated_subuser.append(rand_suffix); subuser = generated_subuser; return generated_subuser; } /* * Do a fairly exhaustive search for an existing key matching the parameters * given. Also handles the case where no key type was specified and updates * the operation state if needed. */ bool RGWAccessKeyPool::check_existing_key(RGWUserAdminOpState& op_state) { bool existing_key = false; int key_type = op_state.get_key_type(); std::string kid = op_state.get_access_key(); std::map<std::string, RGWAccessKey>::iterator kiter; std::string swift_kid = op_state.build_default_swift_kid(); RGWUserInfo dup_info; if (kid.empty() && swift_kid.empty()) return false; switch (key_type) { case KEY_TYPE_SWIFT: kiter = swift_keys->find(swift_kid); existing_key = (kiter != swift_keys->end()); if (existing_key) op_state.set_access_key(swift_kid); break; case KEY_TYPE_S3: kiter = access_keys->find(kid); existing_key = (kiter != access_keys->end()); break; default: kiter = access_keys->find(kid); existing_key = (kiter != access_keys->end()); if (existing_key) { op_state.set_key_type(KEY_TYPE_S3); break; } kiter = swift_keys->find(kid); existing_key = (kiter != swift_keys->end()); if (existing_key) { op_state.set_key_type(KEY_TYPE_SWIFT); break; } // handle the case where the access key was not provided in user:key format if (swift_kid.empty()) return false; kiter = swift_keys->find(swift_kid); existing_key = (kiter != swift_keys->end()); if (existing_key) { op_state.set_access_key(swift_kid); op_state.set_key_type(KEY_TYPE_SWIFT); } } op_state.set_existing_key(existing_key); return existing_key; } int RGWAccessKeyPool::check_op(RGWUserAdminOpState& op_state, std::string *err_msg) { RGWUserInfo dup_info; if (!op_state.is_populated()) { set_err_msg(err_msg, "user info was not populated"); return -EINVAL; } if (!keys_allowed) { set_err_msg(err_msg, "keys not allowed for this user"); return -EACCES; } int32_t key_type = op_state.get_key_type(); // if a key type wasn't specified if (key_type < 0) { if (op_state.has_subuser()) { key_type = KEY_TYPE_SWIFT; } else { key_type = KEY_TYPE_S3; } } op_state.set_key_type(key_type); /* see if the access key was specified */ if (key_type == KEY_TYPE_S3 && !op_state.will_gen_access() && op_state.get_access_key().empty()) { set_err_msg(err_msg, "empty access key"); return -ERR_INVALID_ACCESS_KEY; } // don't check for secret key because we may be doing a removal if (check_existing_key(op_state)) { op_state.set_access_key_exist(); } return 0; } // Generate a new random key int RGWAccessKeyPool::generate_key(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { std::string id; std::string key; std::pair<std::string, RGWAccessKey> key_pair; RGWAccessKey new_key; std::unique_ptr<rgw::sal::User> duplicate_check; int key_type = op_state.get_key_type(); bool gen_access = op_state.will_gen_access(); bool gen_secret = op_state.will_gen_secret(); if (!keys_allowed) { set_err_msg(err_msg, "access keys not allowed for this user"); return -EACCES; } if (op_state.has_existing_key()) { set_err_msg(err_msg, "cannot create existing key"); return -ERR_KEY_EXIST; } if (!gen_access) { id = op_state.get_access_key(); } if (!id.empty()) { switch (key_type) { case KEY_TYPE_SWIFT: if (driver->get_user_by_swift(dpp, id, y, &duplicate_check) >= 0) { set_err_msg(err_msg, "existing swift key in RGW system:" + id); return -ERR_KEY_EXIST; } break; case KEY_TYPE_S3: if (driver->get_user_by_access_key(dpp, id, y, &duplicate_check) >= 0) { set_err_msg(err_msg, "existing S3 key in RGW system:" + id); return -ERR_KEY_EXIST; } } } //key's subuser if (op_state.has_subuser()) { //create user and subuser at the same time, user's s3 key should not be set this if (!op_state.key_type_setbycontext || (key_type == KEY_TYPE_SWIFT)) { new_key.subuser = op_state.get_subuser(); } } //Secret key if (!gen_secret) { if (op_state.get_secret_key().empty()) { set_err_msg(err_msg, "empty secret key"); return -ERR_INVALID_SECRET_KEY; } key = op_state.get_secret_key(); } else { char secret_key_buf[SECRET_KEY_LEN + 1]; gen_rand_alphanumeric_plain(g_ceph_context, secret_key_buf, sizeof(secret_key_buf)); key = secret_key_buf; } // Generate the access key if (key_type == KEY_TYPE_S3 && gen_access) { char public_id_buf[PUBLIC_ID_LEN + 1]; do { int id_buf_size = sizeof(public_id_buf); gen_rand_alphanumeric_upper(g_ceph_context, public_id_buf, id_buf_size); id = public_id_buf; if (!validate_access_key(id)) continue; } while (!driver->get_user_by_access_key(dpp, id, y, &duplicate_check)); } if (key_type == KEY_TYPE_SWIFT) { id = op_state.build_default_swift_kid(); if (id.empty()) { set_err_msg(err_msg, "empty swift access key"); return -ERR_INVALID_ACCESS_KEY; } // check that the access key doesn't exist if (driver->get_user_by_swift(dpp, id, y, &duplicate_check) >= 0) { set_err_msg(err_msg, "cannot create existing swift key"); return -ERR_KEY_EXIST; } } // finally create the new key new_key.id = id; new_key.key = key; key_pair.first = id; key_pair.second = new_key; if (key_type == KEY_TYPE_S3) { access_keys->insert(key_pair); } else if (key_type == KEY_TYPE_SWIFT) { swift_keys->insert(key_pair); } return 0; } // modify an existing key int RGWAccessKeyPool::modify_key(RGWUserAdminOpState& op_state, std::string *err_msg) { std::string id; std::string key = op_state.get_secret_key(); int key_type = op_state.get_key_type(); RGWAccessKey modify_key; pair<string, RGWAccessKey> key_pair; map<std::string, RGWAccessKey>::iterator kiter; switch (key_type) { case KEY_TYPE_S3: id = op_state.get_access_key(); if (id.empty()) { set_err_msg(err_msg, "no access key specified"); return -ERR_INVALID_ACCESS_KEY; } break; case KEY_TYPE_SWIFT: id = op_state.build_default_swift_kid(); if (id.empty()) { set_err_msg(err_msg, "no subuser specified"); return -EINVAL; } break; default: set_err_msg(err_msg, "invalid key type"); return -ERR_INVALID_KEY_TYPE; } if (!op_state.has_existing_key()) { set_err_msg(err_msg, "key does not exist"); return -ERR_INVALID_ACCESS_KEY; } key_pair.first = id; if (key_type == KEY_TYPE_SWIFT) { modify_key.id = id; modify_key.subuser = op_state.get_subuser(); } else if (key_type == KEY_TYPE_S3) { kiter = access_keys->find(id); if (kiter != access_keys->end()) { modify_key = kiter->second; } } if (op_state.will_gen_secret()) { char secret_key_buf[SECRET_KEY_LEN + 1]; int key_buf_size = sizeof(secret_key_buf); gen_rand_alphanumeric_plain(g_ceph_context, secret_key_buf, key_buf_size); key = secret_key_buf; } if (key.empty()) { set_err_msg(err_msg, "empty secret key"); return -ERR_INVALID_SECRET_KEY; } // update the access key with the new secret key modify_key.key = key; key_pair.second = modify_key; if (key_type == KEY_TYPE_S3) { (*access_keys)[id] = modify_key; } else if (key_type == KEY_TYPE_SWIFT) { (*swift_keys)[id] = modify_key; } return 0; } int RGWAccessKeyPool::execute_add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret = 0; std::string subprocess_msg; int key_op = GENERATE_KEY; // set the op if (op_state.has_existing_key()) key_op = MODIFY_KEY; switch (key_op) { case GENERATE_KEY: ret = generate_key(dpp, op_state, y, &subprocess_msg); break; case MODIFY_KEY: ret = modify_key(op_state, &subprocess_msg); break; } if (ret < 0) { set_err_msg(err_msg, subprocess_msg); return ret; } // store the updated info if (!defer_user_update) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWAccessKeyPool::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return add(dpp, op_state, err_msg, false, y); } int RGWAccessKeyPool::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret; std::string subprocess_msg; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse request, " + subprocess_msg); return ret; } ret = execute_add(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to add access key, " + subprocess_msg); return ret; } return 0; } int RGWAccessKeyPool::execute_remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret = 0; int key_type = op_state.get_key_type(); std::string id = op_state.get_access_key(); map<std::string, RGWAccessKey>::iterator kiter; map<std::string, RGWAccessKey> *keys_map; if (!op_state.has_existing_key()) { set_err_msg(err_msg, "unable to find access key, with key type: " + key_type_to_str(key_type)); return -ERR_INVALID_ACCESS_KEY; } if (key_type == KEY_TYPE_S3) { keys_map = access_keys; } else if (key_type == KEY_TYPE_SWIFT) { keys_map = swift_keys; } else { keys_map = NULL; set_err_msg(err_msg, "invalid access key"); return -ERR_INVALID_ACCESS_KEY; } kiter = keys_map->find(id); if (kiter == keys_map->end()) { set_err_msg(err_msg, "key not found"); return -ERR_INVALID_ACCESS_KEY; } keys_map->erase(kiter); if (!defer_user_update) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWAccessKeyPool::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return remove(dpp, op_state, err_msg, false, y); } int RGWAccessKeyPool::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret; std::string subprocess_msg; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse request, " + subprocess_msg); return ret; } ret = execute_remove(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to remove access key, " + subprocess_msg); return ret; } return 0; } // remove all keys associated with a subuser int RGWAccessKeyPool::remove_subuser_keys(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret = 0; if (!op_state.is_populated()) { set_err_msg(err_msg, "user info was not populated"); return -EINVAL; } if (!op_state.has_subuser()) { set_err_msg(err_msg, "no subuser specified"); return -EINVAL; } std::string swift_kid = op_state.build_default_swift_kid(); if (swift_kid.empty()) { set_err_msg(err_msg, "empty swift access key"); return -EINVAL; } map<std::string, RGWAccessKey>::iterator kiter; map<std::string, RGWAccessKey> *keys_map; // a subuser can have at most one swift key keys_map = swift_keys; kiter = keys_map->find(swift_kid); if (kiter != keys_map->end()) { keys_map->erase(kiter); } // a subuser may have multiple s3 key pairs std::string subuser_str = op_state.get_subuser(); keys_map = access_keys; RGWUserInfo user_info = op_state.get_user_info(); auto user_kiter = user_info.access_keys.begin(); for (; user_kiter != user_info.access_keys.end(); ++user_kiter) { if (user_kiter->second.subuser == subuser_str) { kiter = keys_map->find(user_kiter->first); if (kiter != keys_map->end()) { keys_map->erase(kiter); } } } if (!defer_user_update) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } RGWSubUserPool::RGWSubUserPool(RGWUser *usr) { if (!usr) { return; } user = usr; subusers_allowed = true; driver = user->get_driver(); } int RGWSubUserPool::init(RGWUserAdminOpState& op_state) { if (!op_state.is_initialized()) { subusers_allowed = false; return -EINVAL; } const rgw_user& uid = op_state.get_user_id(); if (uid.compare(RGW_USER_ANON_ID) == 0) { subusers_allowed = false; return -EACCES; } subuser_map = op_state.get_subusers(); if (subuser_map == NULL) { subusers_allowed = false; return -EINVAL; } subusers_allowed = true; return 0; } bool RGWSubUserPool::exists(std::string subuser) { if (subuser.empty()) return false; if (!subuser_map) return false; if (subuser_map->count(subuser)) return true; return false; } int RGWSubUserPool::check_op(RGWUserAdminOpState& op_state, std::string *err_msg) { bool existing = false; std::string subuser = op_state.get_subuser(); if (!op_state.is_populated()) { set_err_msg(err_msg, "user info was not populated"); return -EINVAL; } if (!subusers_allowed) { set_err_msg(err_msg, "subusers not allowed for this user"); return -EACCES; } if (subuser.empty() && !op_state.will_gen_subuser()) { set_err_msg(err_msg, "empty subuser name"); return -EINVAL; } if (op_state.get_subuser_perm() == RGW_PERM_INVALID) { set_err_msg(err_msg, "invalid subuser access"); return -EINVAL; } //set key type when it not set or set by context if ((op_state.get_key_type() < 0) || op_state.key_type_setbycontext) { op_state.set_key_type(KEY_TYPE_SWIFT); op_state.key_type_setbycontext = true; } // check if the subuser exists if (!subuser.empty()) existing = exists(subuser); op_state.set_existing_subuser(existing); return 0; } int RGWSubUserPool::execute_add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret = 0; std::string subprocess_msg; RGWSubUser subuser; std::pair<std::string, RGWSubUser> subuser_pair; std::string subuser_str = op_state.get_subuser(); subuser_pair.first = subuser_str; // assumes key should be created if (op_state.has_key_op()) { ret = user->keys.add(dpp, op_state, &subprocess_msg, true, y); if (ret < 0) { set_err_msg(err_msg, "unable to create subuser key, " + subprocess_msg); return ret; } } // create the subuser subuser.name = subuser_str; if (op_state.has_subuser_perm()) subuser.perm_mask = op_state.get_subuser_perm(); // insert the subuser into user info subuser_pair.second = subuser; subuser_map->insert(subuser_pair); // attempt to save the subuser if (!defer_user_update) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWSubUserPool::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return add(dpp, op_state, err_msg, false, y); } int RGWSubUserPool::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { std::string subprocess_msg; int ret; int32_t key_type = op_state.get_key_type(); ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse request, " + subprocess_msg); return ret; } if (op_state.get_access_key_exist()) { set_err_msg(err_msg, "cannot create existing key"); return -ERR_KEY_EXIST; } if (key_type == KEY_TYPE_S3 && op_state.get_access_key().empty()) { op_state.set_gen_access(); } if (op_state.get_secret_key().empty()) { op_state.set_gen_secret(); } ret = execute_add(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to create subuser, " + subprocess_msg); return ret; } return 0; } int RGWSubUserPool::execute_remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret = 0; std::string subprocess_msg; std::string subuser_str = op_state.get_subuser(); map<std::string, RGWSubUser>::iterator siter; siter = subuser_map->find(subuser_str); if (siter == subuser_map->end()){ set_err_msg(err_msg, "subuser not found: " + subuser_str); return -ERR_NO_SUCH_SUBUSER; } if (!op_state.has_existing_subuser()) { set_err_msg(err_msg, "subuser not found: " + subuser_str); return -ERR_NO_SUCH_SUBUSER; } // always purge all associate keys user->keys.remove_subuser_keys(dpp, op_state, &subprocess_msg, true, y); // remove the subuser from the user info subuser_map->erase(siter); // attempt to save the subuser if (!defer_user_update) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWSubUserPool::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return remove(dpp, op_state, err_msg, false, y); } int RGWSubUserPool::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { std::string subprocess_msg; int ret; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse request, " + subprocess_msg); return ret; } ret = execute_remove(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to remove subuser, " + subprocess_msg); return ret; } return 0; } int RGWSubUserPool::execute_modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_user_update, optional_yield y) { int ret = 0; std::string subprocess_msg; std::map<std::string, RGWSubUser>::iterator siter; std::pair<std::string, RGWSubUser> subuser_pair; std::string subuser_str = op_state.get_subuser(); RGWSubUser subuser; if (!op_state.has_existing_subuser()) { set_err_msg(err_msg, "subuser does not exist"); return -ERR_NO_SUCH_SUBUSER; } subuser_pair.first = subuser_str; siter = subuser_map->find(subuser_str); subuser = siter->second; if (op_state.has_key_op()) { ret = user->keys.add(dpp, op_state, &subprocess_msg, true, y); if (ret < 0) { set_err_msg(err_msg, "unable to create subuser keys, " + subprocess_msg); return ret; } } if (op_state.has_subuser_perm()) subuser.perm_mask = op_state.get_subuser_perm(); subuser_pair.second = subuser; subuser_map->erase(siter); subuser_map->insert(subuser_pair); // attempt to save the subuser if (!defer_user_update) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWSubUserPool::modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return RGWSubUserPool::modify(dpp, op_state, y, err_msg, false); } int RGWSubUserPool::modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg, bool defer_user_update) { std::string subprocess_msg; int ret; RGWSubUser subuser; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse request, " + subprocess_msg); return ret; } ret = execute_modify(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to modify subuser, " + subprocess_msg); return ret; } return 0; } RGWUserCapPool::RGWUserCapPool(RGWUser *usr) { if (!usr) { return; } user = usr; caps_allowed = true; } int RGWUserCapPool::init(RGWUserAdminOpState& op_state) { if (!op_state.is_initialized()) { caps_allowed = false; return -EINVAL; } const rgw_user& uid = op_state.get_user_id(); if (uid.compare(RGW_USER_ANON_ID) == 0) { caps_allowed = false; return -EACCES; } caps = op_state.get_caps_obj(); if (!caps) { caps_allowed = false; return -ERR_INVALID_CAP; } caps_allowed = true; return 0; } int RGWUserCapPool::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return add(dpp, op_state, err_msg, false, y); } int RGWUserCapPool::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y) { int ret = 0; std::string caps_str = op_state.get_caps(); if (!op_state.is_populated()) { set_err_msg(err_msg, "user info was not populated"); return -EINVAL; } if (!caps_allowed) { set_err_msg(err_msg, "caps not allowed for this user"); return -EACCES; } if (caps_str.empty()) { set_err_msg(err_msg, "empty user caps"); return -ERR_INVALID_CAP; } int r = caps->add_from_string(caps_str); if (r < 0) { set_err_msg(err_msg, "unable to add caps: " + caps_str); return r; } if (!defer_save) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWUserCapPool::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { return remove(dpp, op_state, err_msg, false, y); } int RGWUserCapPool::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y) { int ret = 0; std::string caps_str = op_state.get_caps(); if (!op_state.is_populated()) { set_err_msg(err_msg, "user info was not populated"); return -EINVAL; } if (!caps_allowed) { set_err_msg(err_msg, "caps not allowed for this user"); return -EACCES; } if (caps_str.empty()) { set_err_msg(err_msg, "empty user caps"); return -ERR_INVALID_CAP; } int r = caps->remove_from_string(caps_str); if (r < 0) { set_err_msg(err_msg, "unable to remove caps: " + caps_str); return r; } if (!defer_save) ret = user->update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } RGWUser::RGWUser() : caps(this), keys(this), subusers(this) { init_default(); } int RGWUser::init(const DoutPrefixProvider *dpp, rgw::sal::Driver* _driver, RGWUserAdminOpState& op_state, optional_yield y) { init_default(); int ret = init_storage(_driver); if (ret < 0) return ret; ret = init(dpp, op_state, y); if (ret < 0) return ret; return 0; } void RGWUser::init_default() { // use anonymous user info as a placeholder rgw_get_anon_user(old_info); user_id = RGW_USER_ANON_ID; clear_populated(); } int RGWUser::init_storage(rgw::sal::Driver* _driver) { if (!_driver) { return -EINVAL; } driver = _driver; clear_populated(); /* API wrappers */ keys = RGWAccessKeyPool(this); caps = RGWUserCapPool(this); subusers = RGWSubUserPool(this); return 0; } int RGWUser::init(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y) { bool found = false; std::string swift_user; user_id = op_state.get_user_id(); std::string user_email = op_state.get_user_email(); std::string access_key = op_state.get_access_key(); std::string subuser = op_state.get_subuser(); int key_type = op_state.get_key_type(); if (key_type == KEY_TYPE_SWIFT) { swift_user = op_state.get_access_key(); access_key.clear(); } std::unique_ptr<rgw::sal::User> user; clear_populated(); if (user_id.empty() && !subuser.empty()) { size_t pos = subuser.find(':'); if (pos != string::npos) { user_id = subuser.substr(0, pos); op_state.set_user_id(user_id); } } if (!user_id.empty() && (user_id.compare(RGW_USER_ANON_ID) != 0)) { user = driver->get_user(user_id); found = (user->load_user(dpp, y) >= 0); op_state.found_by_uid = found; } if (driver->ctx()->_conf.get_val<bool>("rgw_user_unique_email")) { if (!user_email.empty() && !found) { found = (driver->get_user_by_email(dpp, user_email, y, &user) >= 0); op_state.found_by_email = found; } } if (!swift_user.empty() && !found) { found = (driver->get_user_by_swift(dpp, swift_user, y, &user) >= 0); op_state.found_by_key = found; } if (!access_key.empty() && !found) { found = (driver->get_user_by_access_key(dpp, access_key, y, &user) >= 0); op_state.found_by_key = found; } op_state.set_existing_user(found); if (found) { op_state.set_user_info(user->get_info()); op_state.set_populated(); op_state.objv = user->get_version_tracker(); op_state.set_user_version_tracker(user->get_version_tracker()); old_info = user->get_info(); set_populated(); } if (user_id.empty()) { user_id = user->get_id(); } op_state.set_initialized(); // this may have been called by a helper object int ret = init_members(op_state); if (ret < 0) return ret; return 0; } int RGWUser::init_members(RGWUserAdminOpState& op_state) { int ret = 0; ret = keys.init(op_state); if (ret < 0) return ret; ret = subusers.init(op_state); if (ret < 0) return ret; ret = caps.init(op_state); if (ret < 0) return ret; return 0; } int RGWUser::update(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y) { int ret; std::string subprocess_msg; rgw::sal::User* user = op_state.get_user(); if (!driver) { set_err_msg(err_msg, "couldn't initialize storage"); return -EINVAL; } // if op_state.op_access_keys is not empty most recent keys have been fetched from master zone if(!op_state.op_access_keys.empty()) { auto user_access_keys = op_state.get_access_keys(); *(user_access_keys) = op_state.op_access_keys; } RGWUserInfo *pold_info = (is_populated() ? &old_info : nullptr); ret = user->store_user(dpp, y, false, pold_info); op_state.objv = user->get_version_tracker(); op_state.set_user_version_tracker(user->get_version_tracker()); if (ret < 0) { set_err_msg(err_msg, "unable to store user info"); return ret; } old_info = user->get_info(); set_populated(); return 0; } int RGWUser::check_op(RGWUserAdminOpState& op_state, std::string *err_msg) { int ret = 0; const rgw_user& uid = op_state.get_user_id(); if (uid.compare(RGW_USER_ANON_ID) == 0) { set_err_msg(err_msg, "unable to perform operations on the anonymous user"); return -EINVAL; } if (is_populated() && user_id.compare(uid) != 0) { set_err_msg(err_msg, "user id mismatch, operation id: " + uid.to_str() + " does not match: " + user_id.to_str()); return -EINVAL; } ret = rgw_validate_tenant_name(uid.tenant); if (ret) { set_err_msg(err_msg, "invalid tenant only alphanumeric and _ characters are allowed"); return ret; } //set key type when it not set or set by context if ((op_state.get_key_type() < 0) || op_state.key_type_setbycontext) { op_state.set_key_type(KEY_TYPE_S3); op_state.key_type_setbycontext = true; } return 0; } // update swift_keys with new user id static void rename_swift_keys(const rgw_user& user, std::map<std::string, RGWAccessKey>& keys) { std::string user_id; user.to_str(user_id); auto modify_keys = std::move(keys); for ([[maybe_unused]] auto& [k, key] : modify_keys) { std::string id = user_id + ":" + key.subuser; key.id = id; keys[id] = std::move(key); } } int RGWUser::execute_rename(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y) { int ret; bool populated = op_state.is_populated(); if (!op_state.has_existing_user() && !populated) { set_err_msg(err_msg, "user not found"); return -ENOENT; } if (!populated) { ret = init(dpp, op_state, y); if (ret < 0) { set_err_msg(err_msg, "unable to retrieve user info"); return ret; } } std::unique_ptr<rgw::sal::User> old_user = driver->get_user(op_state.get_user_info().user_id); std::unique_ptr<rgw::sal::User> new_user = driver->get_user(op_state.get_new_uid()); if (old_user->get_tenant() != new_user->get_tenant()) { set_err_msg(err_msg, "users have to be under the same tenant namespace " + old_user->get_tenant() + " != " + new_user->get_tenant()); return -EINVAL; } // create a stub user and write only the uid index and buckets object std::unique_ptr<rgw::sal::User> user; user = driver->get_user(new_user->get_id()); const bool exclusive = !op_state.get_overwrite_new_user(); // overwrite if requested ret = user->store_user(dpp, y, exclusive); if (ret == -EEXIST) { set_err_msg(err_msg, "user name given by --new-uid already exists"); return ret; } if (ret < 0) { set_err_msg(err_msg, "unable to store new user info"); return ret; } RGWAccessControlPolicy policy_instance; policy_instance.create_default(new_user->get_id(), old_user->get_display_name()); //unlink and link buckets to new user string marker; CephContext *cct = driver->ctx(); size_t max_buckets = cct->_conf->rgw_list_buckets_max_chunk; rgw::sal::BucketList buckets; do { ret = old_user->list_buckets(dpp, marker, "", max_buckets, false, buckets, y); if (ret < 0) { set_err_msg(err_msg, "unable to list user buckets"); return ret; } auto& m = buckets.get_buckets(); for (auto it = m.begin(); it != m.end(); ++it) { auto& bucket = it->second; marker = it->first; ret = bucket->load_bucket(dpp, y); if (ret < 0) { set_err_msg(err_msg, "failed to fetch bucket info for bucket=" + bucket->get_name()); return ret; } ret = bucket->set_acl(dpp, policy_instance, y); if (ret < 0) { set_err_msg(err_msg, "failed to set acl on bucket " + bucket->get_name()); return ret; } ret = rgw_chown_bucket_and_objects(driver, bucket.get(), new_user.get(), std::string(), nullptr, dpp, y); if (ret < 0) { set_err_msg(err_msg, "failed to run bucket chown" + cpp_strerror(-ret)); return ret; } } } while (buckets.is_truncated()); // update the 'stub user' with all of the other fields and rewrite all of the // associated index objects RGWUserInfo& user_info = op_state.get_user_info(); user_info.user_id = new_user->get_id(); op_state.objv = user->get_version_tracker(); op_state.set_user_version_tracker(user->get_version_tracker()); rename_swift_keys(new_user->get_id(), user_info.swift_keys); return update(dpp, op_state, err_msg, y); } int RGWUser::execute_add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y) { const rgw_user& uid = op_state.get_user_id(); std::string user_email = op_state.get_user_email(); std::string display_name = op_state.get_display_name(); // set the user info RGWUserInfo user_info; user_id = uid; user_info.user_id = user_id; user_info.display_name = display_name; user_info.type = TYPE_RGW; if (!user_email.empty()) user_info.user_email = user_email; CephContext *cct = driver->ctx(); if (op_state.max_buckets_specified) { user_info.max_buckets = op_state.get_max_buckets(); } else { user_info.max_buckets = cct->_conf.get_val<int64_t>("rgw_user_max_buckets"); } user_info.suspended = op_state.get_suspension_status(); user_info.admin = op_state.admin; user_info.system = op_state.system; if (op_state.op_mask_specified) user_info.op_mask = op_state.get_op_mask(); if (op_state.has_bucket_quota()) { user_info.quota.bucket_quota = op_state.get_bucket_quota(); } else { rgw_apply_default_bucket_quota(user_info.quota.bucket_quota, cct->_conf); } if (op_state.temp_url_key_specified) { map<int, string>::iterator iter; for (iter = op_state.temp_url_keys.begin(); iter != op_state.temp_url_keys.end(); ++iter) { user_info.temp_url_keys[iter->first] = iter->second; } } if (op_state.has_user_quota()) { user_info.quota.user_quota = op_state.get_user_quota(); } else { rgw_apply_default_user_quota(user_info.quota.user_quota, cct->_conf); } if (op_state.default_placement_specified) { user_info.default_placement = op_state.default_placement; } if (op_state.placement_tags_specified) { user_info.placement_tags = op_state.placement_tags; } // update the request op_state.set_user_info(user_info); op_state.set_populated(); // update the helper objects int ret = init_members(op_state); if (ret < 0) { set_err_msg(err_msg, "unable to initialize user"); return ret; } // see if we need to add an access key std::string subprocess_msg; bool defer_user_update = true; if (op_state.has_key_op()) { ret = keys.add(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to create access key, " + subprocess_msg); return ret; } } // see if we need to add some caps if (op_state.has_caps_op()) { ret = caps.add(dpp, op_state, &subprocess_msg, defer_user_update, y); if (ret < 0) { set_err_msg(err_msg, "unable to add user capabilities, " + subprocess_msg); return ret; } } ret = update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWUser::add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { std::string subprocess_msg; int ret = user_add_helper(op_state, &subprocess_msg); if (ret != 0) { set_err_msg(err_msg, "unable to parse parameters, " + subprocess_msg); return ret; } ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse parameters, " + subprocess_msg); return ret; } ret = execute_add(dpp, op_state, &subprocess_msg, y); if (ret < 0) { set_err_msg(err_msg, "unable to create user, " + subprocess_msg); return ret; } return 0; } int RGWUser::rename(RGWUserAdminOpState& op_state, optional_yield y, const DoutPrefixProvider *dpp, std::string *err_msg) { std::string subprocess_msg; int ret; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse parameters, " + subprocess_msg); return ret; } ret = execute_rename(dpp, op_state, &subprocess_msg, y); if (ret < 0) { set_err_msg(err_msg, "unable to rename user, " + subprocess_msg); return ret; } return 0; } int RGWUser::execute_remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y) { int ret; bool purge_data = op_state.will_purge_data(); rgw::sal::User* user = op_state.get_user(); if (!op_state.has_existing_user()) { set_err_msg(err_msg, "user does not exist"); return -ENOENT; } rgw::sal::BucketList buckets; string marker; CephContext *cct = driver->ctx(); size_t max_buckets = cct->_conf->rgw_list_buckets_max_chunk; do { ret = user->list_buckets(dpp, marker, string(), max_buckets, false, buckets, y); if (ret < 0) { set_err_msg(err_msg, "unable to read user bucket info"); return ret; } auto& m = buckets.get_buckets(); if (!m.empty() && !purge_data) { set_err_msg(err_msg, "must specify purge data to remove user with buckets"); return -EEXIST; // change to code that maps to 409: conflict } for (auto it = m.begin(); it != m.end(); ++it) { ret = it->second->remove_bucket(dpp, true, false, nullptr, y); if (ret < 0) { set_err_msg(err_msg, "unable to delete user data"); return ret; } marker = it->first; } } while (buckets.is_truncated()); ret = user->remove_user(dpp, y); if (ret < 0) { set_err_msg(err_msg, "unable to remove user from RADOS"); return ret; } op_state.clear_populated(); clear_populated(); return 0; } int RGWUser::remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { std::string subprocess_msg; int ret; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse parameters, " + subprocess_msg); return ret; } ret = execute_remove(dpp, op_state, &subprocess_msg, y); if (ret < 0) { set_err_msg(err_msg, "unable to remove user, " + subprocess_msg); return ret; } return 0; } int RGWUser::execute_modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y) { bool populated = op_state.is_populated(); int ret = 0; std::string subprocess_msg; std::string op_email = op_state.get_user_email(); std::string display_name = op_state.get_display_name(); RGWUserInfo user_info; std::unique_ptr<rgw::sal::User> duplicate_check; // ensure that the user info has been populated or is populate-able if (!op_state.has_existing_user() && !populated) { set_err_msg(err_msg, "user not found"); return -ENOENT; } // if the user hasn't already been populated...attempt to if (!populated) { ret = init(dpp, op_state, y); if (ret < 0) { set_err_msg(err_msg, "unable to retrieve user info"); return ret; } } // ensure that we can modify the user's attributes if (user_id.compare(RGW_USER_ANON_ID) == 0) { set_err_msg(err_msg, "unable to modify anonymous user's info"); return -EACCES; } user_info = old_info; std::string old_email = old_info.user_email; if (!op_email.empty()) { // make sure we are not adding a duplicate email if (old_email != op_email) { ret = driver->get_user_by_email(dpp, op_email, y, &duplicate_check); if (ret >= 0 && duplicate_check->get_id().compare(user_id) != 0) { set_err_msg(err_msg, "cannot add duplicate email"); return -ERR_EMAIL_EXIST; } } user_info.user_email = op_email; } else if (op_email.empty() && op_state.user_email_specified) { ldpp_dout(dpp, 10) << "removing email index: " << user_info.user_email << dendl; /* will be physically removed later when calling update() */ user_info.user_email.clear(); } // update the remaining user info if (!display_name.empty()) user_info.display_name = display_name; if (op_state.max_buckets_specified) user_info.max_buckets = op_state.get_max_buckets(); if (op_state.admin_specified) user_info.admin = op_state.admin; if (op_state.system_specified) user_info.system = op_state.system; if (op_state.temp_url_key_specified) { map<int, string>::iterator iter; for (iter = op_state.temp_url_keys.begin(); iter != op_state.temp_url_keys.end(); ++iter) { user_info.temp_url_keys[iter->first] = iter->second; } } if (op_state.op_mask_specified) user_info.op_mask = op_state.get_op_mask(); if (op_state.has_bucket_quota()) user_info.quota.bucket_quota = op_state.get_bucket_quota(); if (op_state.has_user_quota()) user_info.quota.user_quota = op_state.get_user_quota(); if (op_state.has_suspension_op()) { __u8 suspended = op_state.get_suspension_status(); user_info.suspended = suspended; rgw::sal::BucketList buckets; if (user_id.empty()) { set_err_msg(err_msg, "empty user id passed...aborting"); return -EINVAL; } string marker; CephContext *cct = driver->ctx(); size_t max_buckets = cct->_conf->rgw_list_buckets_max_chunk; std::unique_ptr<rgw::sal::User> user = driver->get_user(user_id); do { ret = user->list_buckets(dpp, marker, string(), max_buckets, false, buckets, y); if (ret < 0) { set_err_msg(err_msg, "could not get buckets for uid: " + user_id.to_str()); return ret; } auto& m = buckets.get_buckets(); vector<rgw_bucket> bucket_names; for (auto iter = m.begin(); iter != m.end(); ++iter) { auto& bucket = iter->second; bucket_names.push_back(bucket->get_key()); marker = iter->first; } ret = driver->set_buckets_enabled(dpp, bucket_names, !suspended, y); if (ret < 0) { set_err_msg(err_msg, "failed to modify bucket"); return ret; } } while (buckets.is_truncated()); } if (op_state.mfa_ids_specified) { user_info.mfa_ids = op_state.mfa_ids; } if (op_state.default_placement_specified) { user_info.default_placement = op_state.default_placement; } if (op_state.placement_tags_specified) { user_info.placement_tags = op_state.placement_tags; } op_state.set_user_info(user_info); // if we're supposed to modify keys, do so if (op_state.has_key_op()) { ret = keys.add(dpp, op_state, &subprocess_msg, true, y); if (ret < 0) { set_err_msg(err_msg, "unable to create or modify keys, " + subprocess_msg); return ret; } } ret = update(dpp, op_state, err_msg, y); if (ret < 0) return ret; return 0; } int RGWUser::modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg) { std::string subprocess_msg; int ret; ret = check_op(op_state, &subprocess_msg); if (ret < 0) { set_err_msg(err_msg, "unable to parse parameters, " + subprocess_msg); return ret; } ret = execute_modify(dpp, op_state, &subprocess_msg, y); if (ret < 0) { set_err_msg(err_msg, "unable to modify user, " + subprocess_msg); return ret; } return 0; } int RGWUser::info(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, RGWUserInfo& fetched_info, optional_yield y, std::string *err_msg) { int ret = init(dpp, op_state, y); if (ret < 0) { set_err_msg(err_msg, "unable to fetch user info"); return ret; } fetched_info = op_state.get_user_info(); return 0; } int RGWUser::info(RGWUserInfo& fetched_info, std::string *err_msg) { if (!is_populated()) { set_err_msg(err_msg, "no user info saved"); return -EINVAL; } fetched_info = old_info; return 0; } int RGWUser::list(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher) { Formatter *formatter = flusher.get_formatter(); void *handle = nullptr; std::string metadata_key = "user"; if (op_state.max_entries > 1000) { op_state.max_entries = 1000; } int ret = driver->meta_list_keys_init(dpp, metadata_key, op_state.marker, &handle); if (ret < 0) { return ret; } bool truncated = false; uint64_t count = 0; uint64_t left = 0; flusher.start(0); // open the result object section formatter->open_object_section("result"); // open the user id list array section formatter->open_array_section("keys"); do { std::list<std::string> keys; left = op_state.max_entries - count; ret = driver->meta_list_keys_next(dpp, handle, left, keys, &truncated); if (ret < 0 && ret != -ENOENT) { return ret; } if (ret != -ENOENT) { for (std::list<std::string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { formatter->dump_string("key", *iter); ++count; } } } while (truncated && left > 0); // close user id list section formatter->close_section(); formatter->dump_bool("truncated", truncated); formatter->dump_int("count", count); if (truncated) { formatter->dump_string("marker", driver->meta_get_marker(handle)); } // close result object section formatter->close_section(); driver->meta_list_keys_complete(handle); flusher.flush(); return 0; } int RGWUserAdminOp_User::list(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher) { RGWUser user; int ret = user.init_storage(driver); if (ret < 0) return ret; ret = user.list(dpp, op_state, flusher); if (ret < 0) return ret; return 0; } int RGWUserAdminOp_User::info(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; std::unique_ptr<rgw::sal::User> ruser; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; Formatter *formatter = flusher.get_formatter(); ret = user.info(info, NULL); if (ret < 0) return ret; ruser = driver->get_user(info.user_id); if (op_state.sync_stats) { ret = rgw_user_sync_all_stats(dpp, driver, ruser.get(), y); if (ret < 0) { return ret; } } RGWStorageStats stats; RGWStorageStats *arg_stats = NULL; if (op_state.fetch_stats) { int ret = ruser->read_stats(dpp, y, &stats); if (ret < 0 && ret != -ENOENT) { return ret; } arg_stats = &stats; } if (formatter) { flusher.start(0); dump_user_info(formatter, info, arg_stats); flusher.flush(); } return 0; } int RGWUserAdminOp_User::create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; Formatter *formatter = flusher.get_formatter(); ret = user.add(dpp, op_state, y, NULL); if (ret < 0) { if (ret == -EEXIST) ret = -ERR_USER_EXIST; return ret; } ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); dump_user_info(formatter, info); flusher.flush(); } return 0; } int RGWUserAdminOp_User::modify(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; Formatter *formatter = flusher.get_formatter(); ret = user.modify(dpp, op_state, y, NULL); if (ret < 0) { if (ret == -ENOENT) ret = -ERR_NO_SUCH_USER; return ret; } ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); dump_user_info(formatter, info); flusher.flush(); } return 0; } int RGWUserAdminOp_User::remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; ret = user.remove(dpp, op_state, y, NULL); if (ret == -ENOENT) ret = -ERR_NO_SUCH_USER; return ret; } int RGWUserAdminOp_Subuser::create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; Formatter *formatter = flusher.get_formatter(); ret = user.subusers.add(dpp, op_state, y, NULL); if (ret < 0) return ret; ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); dump_subusers_info(formatter, info); flusher.flush(); } return 0; } int RGWUserAdminOp_Subuser::modify(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; Formatter *formatter = flusher.get_formatter(); ret = user.subusers.modify(dpp, op_state, y, NULL); if (ret < 0) return ret; ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); dump_subusers_info(formatter, info); flusher.flush(); } return 0; } int RGWUserAdminOp_Subuser::remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; ret = user.subusers.remove(dpp, op_state, y, NULL); if (ret < 0) return ret; return 0; } int RGWUserAdminOp_Key::create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; Formatter *formatter = flusher.get_formatter(); ret = user.keys.add(dpp, op_state, y, NULL); if (ret < 0) return ret; ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); int key_type = op_state.get_key_type(); if (key_type == KEY_TYPE_SWIFT) dump_swift_keys_info(formatter, info); else if (key_type == KEY_TYPE_S3) dump_access_keys_info(formatter, info); flusher.flush(); } return 0; } int RGWUserAdminOp_Key::remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; ret = user.keys.remove(dpp, op_state, y, NULL); if (ret < 0) return ret; return 0; } int RGWUserAdminOp_Caps::add(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; Formatter *formatter = flusher.get_formatter(); ret = user.caps.add(dpp, op_state, y, NULL); if (ret < 0) return ret; ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); info.caps.dump(formatter); flusher.flush(); } return 0; } int RGWUserAdminOp_Caps::remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y) { RGWUserInfo info; RGWUser user; int ret = user.init(dpp, driver, op_state, y); if (ret < 0) return ret; if (!op_state.has_existing_user()) return -ERR_NO_SUCH_USER; Formatter *formatter = flusher.get_formatter(); ret = user.caps.remove(dpp, op_state, y, NULL); if (ret < 0) return ret; ret = user.info(info, NULL); if (ret < 0) return ret; if (formatter) { flusher.start(0); info.caps.dump(formatter); flusher.flush(); } return 0; } class RGWUserMetadataHandler : public RGWMetadataHandler_GenericMetaBE { public: struct Svc { RGWSI_User *user{nullptr}; } svc; RGWUserMetadataHandler(RGWSI_User *user_svc) { base_init(user_svc->ctx(), user_svc->get_be_handler()); svc.user = user_svc; } ~RGWUserMetadataHandler() {} string get_type() override { return "user"; } int do_get(RGWSI_MetaBackend_Handler::Op *op, string& entry, RGWMetadataObject **obj, optional_yield y, const DoutPrefixProvider *dpp) override { RGWUserCompleteInfo uci; RGWObjVersionTracker objv_tracker; real_time mtime; rgw_user user = RGWSI_User::user_from_meta_key(entry); int ret = svc.user->read_user_info(op->ctx(), user, &uci.info, &objv_tracker, &mtime, nullptr, &uci.attrs, y, dpp); if (ret < 0) { return ret; } RGWUserMetadataObject *mdo = new RGWUserMetadataObject(uci, objv_tracker.read_version, mtime); *obj = mdo; return 0; } RGWMetadataObject *get_meta_obj(JSONObj *jo, const obj_version& objv, const ceph::real_time& mtime) override { RGWUserCompleteInfo uci; try { decode_json_obj(uci, jo); } catch (JSONDecoder::err& e) { return nullptr; } return new RGWUserMetadataObject(uci, objv, mtime); } int do_put(RGWSI_MetaBackend_Handler::Op *op, string& entry, RGWMetadataObject *obj, RGWObjVersionTracker& objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, RGWMDLogSyncType type, bool from_remote_zone) override; int do_remove(RGWSI_MetaBackend_Handler::Op *op, string& entry, RGWObjVersionTracker& objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) override { RGWUserInfo info; rgw_user user = RGWSI_User::user_from_meta_key(entry); int ret = svc.user->read_user_info(op->ctx(), user, &info, nullptr, nullptr, nullptr, nullptr, y, dpp); if (ret < 0) { return ret; } return svc.user->remove_user_info(op->ctx(), info, &objv_tracker, y, dpp); } }; class RGWMetadataHandlerPut_User : public RGWMetadataHandlerPut_SObj { RGWUserMetadataHandler *uhandler; RGWUserMetadataObject *uobj; public: RGWMetadataHandlerPut_User(RGWUserMetadataHandler *_handler, RGWSI_MetaBackend_Handler::Op *op, string& entry, RGWMetadataObject *obj, RGWObjVersionTracker& objv_tracker, optional_yield y, RGWMDLogSyncType type, bool from_remote_zone) : RGWMetadataHandlerPut_SObj(_handler, op, entry, obj, objv_tracker, y, type, from_remote_zone), uhandler(_handler) { uobj = static_cast<RGWUserMetadataObject *>(obj); } int put_checked(const DoutPrefixProvider *dpp) override; }; int RGWUserMetadataHandler::do_put(RGWSI_MetaBackend_Handler::Op *op, string& entry, RGWMetadataObject *obj, RGWObjVersionTracker& objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, RGWMDLogSyncType type, bool from_remote_zone) { RGWMetadataHandlerPut_User put_op(this, op, entry, obj, objv_tracker, y, type, from_remote_zone); return do_put_operate(&put_op, dpp); } int RGWMetadataHandlerPut_User::put_checked(const DoutPrefixProvider *dpp) { RGWUserMetadataObject *orig_obj = static_cast<RGWUserMetadataObject *>(old_obj); RGWUserCompleteInfo& uci = uobj->get_uci(); map<string, bufferlist> *pattrs{nullptr}; if (uci.has_attrs) { pattrs = &uci.attrs; } RGWUserInfo *pold_info = (orig_obj ? &orig_obj->get_uci().info : nullptr); auto mtime = obj->get_mtime(); int ret = uhandler->svc.user->store_user_info(op->ctx(), uci.info, pold_info, &objv_tracker, mtime, false, pattrs, y, dpp); if (ret < 0) { return ret; } return STATUS_APPLIED; } RGWUserCtl::RGWUserCtl(RGWSI_Zone *zone_svc, RGWSI_User *user_svc, RGWUserMetadataHandler *_umhandler) : umhandler(_umhandler) { svc.zone = zone_svc; svc.user = user_svc; be_handler = umhandler->get_be_handler(); } template <class T> class optional_default { const std::optional<T>& opt; std::optional<T> def; const T *p; public: optional_default(const std::optional<T>& _o) : opt(_o) { if (opt) { p = &(*opt); } else { def = T(); p = &(*def); } } const T *operator->() { return p; } const T& operator*() { return *p; } }; int RGWUserCtl::get_info_by_uid(const DoutPrefixProvider *dpp, const rgw_user& uid, RGWUserInfo *info, optional_yield y, const GetParams& params) { return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->read_user_info(op->ctx(), uid, info, params.objv_tracker, params.mtime, params.cache_info, params.attrs, y, dpp); }); } int RGWUserCtl::get_info_by_email(const DoutPrefixProvider *dpp, const string& email, RGWUserInfo *info, optional_yield y, const GetParams& params) { return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->get_user_info_by_email(op->ctx(), email, info, params.objv_tracker, params.mtime, y, dpp); }); } int RGWUserCtl::get_info_by_swift(const DoutPrefixProvider *dpp, const string& swift_name, RGWUserInfo *info, optional_yield y, const GetParams& params) { return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->get_user_info_by_swift(op->ctx(), swift_name, info, params.objv_tracker, params.mtime, y, dpp); }); } int RGWUserCtl::get_info_by_access_key(const DoutPrefixProvider *dpp, const string& access_key, RGWUserInfo *info, optional_yield y, const GetParams& params) { return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->get_user_info_by_access_key(op->ctx(), access_key, info, params.objv_tracker, params.mtime, y, dpp); }); } int RGWUserCtl::get_attrs_by_uid(const DoutPrefixProvider *dpp, const rgw_user& user_id, map<string, bufferlist> *pattrs, optional_yield y, RGWObjVersionTracker *objv_tracker) { RGWUserInfo user_info; return get_info_by_uid(dpp, user_id, &user_info, y, RGWUserCtl::GetParams() .set_attrs(pattrs) .set_objv_tracker(objv_tracker)); } int RGWUserCtl::store_info(const DoutPrefixProvider *dpp, const RGWUserInfo& info, optional_yield y, const PutParams& params) { string key = RGWSI_User::get_meta_key(info.user_id); return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->store_user_info(op->ctx(), info, params.old_info, params.objv_tracker, params.mtime, params.exclusive, params.attrs, y, dpp); }); } int RGWUserCtl::remove_info(const DoutPrefixProvider *dpp, const RGWUserInfo& info, optional_yield y, const RemoveParams& params) { string key = RGWSI_User::get_meta_key(info.user_id); return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->remove_user_info(op->ctx(), info, params.objv_tracker, y, dpp); }); } int RGWUserCtl::list_buckets(const DoutPrefixProvider *dpp, const rgw_user& user, const string& marker, const string& end_marker, uint64_t max, bool need_stats, RGWUserBuckets *buckets, bool *is_truncated, optional_yield y, uint64_t default_max) { if (!max) { max = default_max; } int ret = svc.user->list_buckets(dpp, user, marker, end_marker, max, buckets, is_truncated, y); if (ret < 0) { return ret; } if (need_stats) { map<string, RGWBucketEnt>& m = buckets->get_buckets(); ret = ctl.bucket->read_buckets_stats(m, y, dpp); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: could not get stats for buckets" << dendl; return ret; } } return 0; } int RGWUserCtl::read_stats(const DoutPrefixProvider *dpp, const rgw_user& user, RGWStorageStats *stats, optional_yield y, ceph::real_time *last_stats_sync, ceph::real_time *last_stats_update) { return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) { return svc.user->read_stats(dpp, op->ctx(), user, stats, last_stats_sync, last_stats_update, y); }); } RGWMetadataHandler *RGWUserMetaHandlerAllocator::alloc(RGWSI_User *user_svc) { return new RGWUserMetadataHandler(user_svc); } void rgw_user::dump(Formatter *f) const { ::encode_json("user", *this, f); }
72,377
25.063378
171
cc
null
ceph-main/src/rgw/driver/rados/rgw_user.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string> #include <boost/algorithm/string.hpp> #include "include/ceph_assert.h" #include "include/types.h" #include "rgw_common.h" #include "rgw_tools.h" #include "rgw_string.h" #include "common/Formatter.h" #include "rgw_formats.h" #include "rgw_metadata.h" #include "rgw_sal_fwd.h" #define RGW_USER_ANON_ID "anonymous" #define SECRET_KEY_LEN 40 #define PUBLIC_ID_LEN 20 #define RAND_SUBUSER_LEN 5 #define XMLNS_AWS_S3 "http://s3.amazonaws.com/doc/2006-03-01/" class RGWUserCtl; class RGWBucketCtl; class RGWUserBuckets; class RGWGetUserStats_CB; /** * A string wrapper that includes encode/decode functions * for easily accessing a UID in all forms */ struct RGWUID { rgw_user user_id; void encode(bufferlist& bl) const { std::string s; user_id.to_str(s); using ceph::encode; encode(s, bl); } void decode(bufferlist::const_iterator& bl) { std::string s; using ceph::decode; decode(s, bl); user_id.from_str(s); } }; WRITE_CLASS_ENCODER(RGWUID) /** Entry for bucket metadata collection */ struct bucket_meta_entry { size_t size; size_t size_rounded; ceph::real_time creation_time; uint64_t count; }; extern int rgw_user_sync_all_stats(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, rgw::sal::User* user, optional_yield y); extern int rgw_user_get_all_buckets_stats(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, rgw::sal::User* user, std::map<std::string, bucket_meta_entry>& buckets_usage_map, optional_yield y); /** * Get the anonymous (ie, unauthenticated) user info. */ extern void rgw_get_anon_user(RGWUserInfo& info); extern void rgw_perm_to_str(uint32_t mask, char *buf, int len); extern uint32_t rgw_str_to_perm(const char *str); extern int rgw_validate_tenant_name(const std::string& t); enum ObjectKeyType { KEY_TYPE_SWIFT, KEY_TYPE_S3, KEY_TYPE_UNDEFINED }; enum RGWKeyPoolOp { GENERATE_KEY, MODIFY_KEY }; enum RGWUserId { RGW_USER_ID, RGW_SWIFT_USERNAME, RGW_USER_EMAIL, RGW_ACCESS_KEY, }; /* * An RGWUser class along with supporting classes created * to support the creation of an RESTful administrative API */ struct RGWUserAdminOpState { // user attributes std::unique_ptr<rgw::sal::User> user; std::string user_email; std::string display_name; rgw_user new_user_id; bool overwrite_new_user = false; int32_t max_buckets{RGW_DEFAULT_MAX_BUCKETS}; __u8 suspended{0}; __u8 admin{0}; __u8 system{0}; __u8 exclusive{0}; __u8 fetch_stats{0}; __u8 sync_stats{0}; std::string caps; RGWObjVersionTracker objv; uint32_t op_mask{0}; std::map<int, std::string> temp_url_keys; // subuser attributes std::string subuser; uint32_t perm_mask{RGW_PERM_NONE}; // key_attributes std::string id; // access key std::string key; // secret key // access keys fetched for a user in the middle of an op std::map<std::string, RGWAccessKey> op_access_keys; int32_t key_type{-1}; bool access_key_exist = false; std::set<std::string> mfa_ids; // operation attributes bool existing_user{false}; bool existing_key{false}; bool existing_subuser{false}; bool existing_email{false}; bool subuser_specified{false}; bool gen_secret{false}; bool gen_access{false}; bool gen_subuser{false}; bool id_specified{false}; bool key_specified{false}; bool type_specified{false}; bool key_type_setbycontext{false}; // key type set by user or subuser context bool purge_data{false}; bool purge_keys{false}; bool display_name_specified{false}; bool user_email_specified{false}; bool max_buckets_specified{false}; bool perm_specified{false}; bool op_mask_specified{false}; bool caps_specified{false}; bool suspension_op{false}; bool admin_specified{false}; bool system_specified{false}; bool key_op{false}; bool temp_url_key_specified{false}; bool found_by_uid{false}; bool found_by_email{false}; bool found_by_key{false}; bool mfa_ids_specified{false}; // req parameters bool populated{false}; bool initialized{false}; bool key_params_checked{false}; bool subuser_params_checked{false}; bool user_params_checked{false}; bool bucket_quota_specified{false}; bool user_quota_specified{false}; bool bucket_ratelimit_specified{false}; bool user_ratelimit_specified{false}; RGWQuota quota; RGWRateLimitInfo user_ratelimit; RGWRateLimitInfo bucket_ratelimit; // req parameters for listing user std::string marker{""}; uint32_t max_entries{1000}; rgw_placement_rule default_placement; // user default placement bool default_placement_specified{false}; std::list<std::string> placement_tags; // user default placement_tags bool placement_tags_specified{false}; void set_access_key(const std::string& access_key) { if (access_key.empty()) return; id = access_key; id_specified = true; gen_access = false; key_op = true; } void set_secret_key(const std::string& secret_key) { if (secret_key.empty()) return; key = secret_key; key_specified = true; gen_secret = false; key_op = true; } void set_user_id(const rgw_user& id); void set_new_user_id(const rgw_user& id) { if (id.empty()) return; new_user_id = id; } void set_overwrite_new_user(bool b) { overwrite_new_user = b; } void set_user_email(std::string& email) { /* always lowercase email address */ boost::algorithm::to_lower(email); user_email = email; user_email_specified = true; } void set_display_name(const std::string& name) { if (name.empty()) return; display_name = name; display_name_specified = true; } void set_subuser(std::string& _subuser); void set_caps(const std::string& _caps) { if (_caps.empty()) return; caps = _caps; caps_specified = true; } void set_perm(uint32_t perm) { perm_mask = perm; perm_specified = true; } void set_op_mask(uint32_t mask) { op_mask = mask; op_mask_specified = true; } void set_temp_url_key(const std::string& key, int index) { temp_url_keys[index] = key; temp_url_key_specified = true; } void set_key_type(int32_t type) { key_type = type; type_specified = true; } void set_access_key_exist() { access_key_exist = true; } void set_suspension(__u8 is_suspended) { suspended = is_suspended; suspension_op = true; } void set_admin(__u8 is_admin) { admin = is_admin; admin_specified = true; } void set_system(__u8 is_system) { system = is_system; system_specified = true; } void set_exclusive(__u8 is_exclusive) { exclusive = is_exclusive; } void set_fetch_stats(__u8 is_fetch_stats) { fetch_stats = is_fetch_stats; } void set_sync_stats(__u8 is_sync_stats) { sync_stats = is_sync_stats; } void set_user_info(RGWUserInfo& user_info); void set_user_version_tracker(RGWObjVersionTracker& objv_tracker); void set_max_buckets(int32_t mb) { max_buckets = mb; max_buckets_specified = true; } void set_gen_access() { gen_access = true; key_op = true; } void set_gen_secret() { gen_secret = true; key_op = true; } void set_generate_key() { if (id.empty()) gen_access = true; if (key.empty()) gen_secret = true; key_op = true; } void clear_generate_key() { gen_access = false; gen_secret = false; } void set_purge_keys() { purge_keys = true; key_op = true; } void set_bucket_quota(RGWQuotaInfo& quotas) { quota.bucket_quota = quotas; bucket_quota_specified = true; } void set_user_quota(RGWQuotaInfo& quotas) { quota.user_quota = quotas; user_quota_specified = true; } void set_bucket_ratelimit(RGWRateLimitInfo& ratelimit) { bucket_ratelimit = ratelimit; bucket_ratelimit_specified = true; } void set_user_ratelimit(RGWRateLimitInfo& ratelimit) { user_ratelimit = ratelimit; user_ratelimit_specified = true; } void set_mfa_ids(const std::set<std::string>& ids) { mfa_ids = ids; mfa_ids_specified = true; } void set_default_placement(const rgw_placement_rule& _placement) { default_placement = _placement; default_placement_specified = true; } void set_placement_tags(const std::list<std::string>& _tags) { placement_tags = _tags; placement_tags_specified = true; } bool is_populated() { return populated; } bool is_initialized() { return initialized; } bool has_existing_user() { return existing_user; } bool has_existing_key() { return existing_key; } bool has_existing_subuser() { return existing_subuser; } bool has_existing_email() { return existing_email; } bool has_subuser() { return subuser_specified; } bool has_key_op() { return key_op; } bool has_caps_op() { return caps_specified; } bool has_suspension_op() { return suspension_op; } bool has_subuser_perm() { return perm_specified; } bool has_op_mask() { return op_mask_specified; } bool will_gen_access() { return gen_access; } bool will_gen_secret() { return gen_secret; } bool will_gen_subuser() { return gen_subuser; } bool will_purge_keys() { return purge_keys; } bool will_purge_data() { return purge_data; } bool will_generate_subuser() { return gen_subuser; } bool has_bucket_quota() { return bucket_quota_specified; } bool has_user_quota() { return user_quota_specified; } void set_populated() { populated = true; } void clear_populated() { populated = false; } void set_initialized() { initialized = true; } void set_existing_user(bool flag) { existing_user = flag; } void set_existing_key(bool flag) { existing_key = flag; } void set_existing_subuser(bool flag) { existing_subuser = flag; } void set_existing_email(bool flag) { existing_email = flag; } void set_purge_data(bool flag) { purge_data = flag; } void set_generate_subuser(bool flag) { gen_subuser = flag; } __u8 get_suspension_status() { return suspended; } int32_t get_key_type() {return key_type; } bool get_access_key_exist() {return access_key_exist; } uint32_t get_subuser_perm() { return perm_mask; } int32_t get_max_buckets() { return max_buckets; } uint32_t get_op_mask() { return op_mask; } RGWQuotaInfo& get_bucket_quota() { return quota.bucket_quota; } RGWQuotaInfo& get_user_quota() { return quota.user_quota; } std::set<std::string>& get_mfa_ids() { return mfa_ids; } rgw::sal::User* get_user() { return user.get(); } const rgw_user& get_user_id(); std::string get_subuser() { return subuser; } std::string get_access_key() { return id; } std::string get_secret_key() { return key; } std::string get_caps() { return caps; } std::string get_user_email() { return user_email; } std::string get_display_name() { return display_name; } rgw_user& get_new_uid() { return new_user_id; } bool get_overwrite_new_user() const { return overwrite_new_user; } std::map<int, std::string>& get_temp_url_keys() { return temp_url_keys; } RGWUserInfo& get_user_info(); std::map<std::string, RGWAccessKey>* get_swift_keys(); std::map<std::string, RGWAccessKey>* get_access_keys(); std::map<std::string, RGWSubUser>* get_subusers(); RGWUserCaps* get_caps_obj(); std::string build_default_swift_kid(); std::string generate_subuser(); RGWUserAdminOpState(rgw::sal::Driver* driver); }; class RGWUser; class RGWAccessKeyPool { RGWUser *user{nullptr}; std::map<std::string, int, ltstr_nocase> key_type_map; rgw_user user_id; rgw::sal::Driver* driver{nullptr}; std::map<std::string, RGWAccessKey> *swift_keys{nullptr}; std::map<std::string, RGWAccessKey> *access_keys{nullptr}; // we don't want to allow keys for the anonymous user or a null user bool keys_allowed{false}; private: int create_key(RGWUserAdminOpState& op_state, std::string *err_msg = NULL); int generate_key(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int modify_key(RGWUserAdminOpState& op_state, std::string *err_msg = NULL); int check_key_owner(RGWUserAdminOpState& op_state); bool check_existing_key(RGWUserAdminOpState& op_state); int check_op(RGWUserAdminOpState& op_state, std::string *err_msg = NULL); /* API Contract Fulfilment */ int execute_add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int execute_remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int remove_subuser_keys(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); public: explicit RGWAccessKeyPool(RGWUser* usr); int init(RGWUserAdminOpState& op_state); /* API Contracted Methods */ int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); friend class RGWUser; friend class RGWSubUserPool; }; class RGWSubUserPool { RGWUser *user{nullptr}; rgw_user user_id; rgw::sal::Driver* driver{nullptr}; bool subusers_allowed{false}; std::map<std::string, RGWSubUser> *subuser_map{nullptr}; private: int check_op(RGWUserAdminOpState& op_state, std::string *err_msg = NULL); /* API Contract Fulfillment */ int execute_add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int execute_remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int execute_modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg, bool defer_save); public: explicit RGWSubUserPool(RGWUser *user); bool exists(std::string subuser); int init(RGWUserAdminOpState& op_state); /* API contracted methods */ int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); friend class RGWUser; }; class RGWUserCapPool { RGWUserCaps *caps{nullptr}; bool caps_allowed{false}; RGWUser *user{nullptr}; private: int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, bool defer_save, optional_yield y); public: explicit RGWUserCapPool(RGWUser *user); int init(RGWUserAdminOpState& op_state); /* API contracted methods */ int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); friend class RGWUser; }; class RGWUser { private: RGWUserInfo old_info; rgw::sal::Driver* driver{nullptr}; rgw_user user_id; bool info_stored{false}; void set_populated() { info_stored = true; } void clear_populated() { info_stored = false; } bool is_populated() { return info_stored; } int check_op(RGWUserAdminOpState& req, std::string *err_msg); int update(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y); void clear_members(); void init_default(); /* API Contract Fulfillment */ int execute_add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y); int execute_remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y); int execute_modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y); int execute_rename(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, std::string *err_msg, optional_yield y); public: RGWUser(); int init(const DoutPrefixProvider *dpp, rgw::sal::Driver* storage, RGWUserAdminOpState& op_state, optional_yield y); int init_storage(rgw::sal::Driver* storage); int init(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y); int init_members(RGWUserAdminOpState& op_state); rgw::sal::Driver* get_driver() { return driver; } /* API Contracted Members */ RGWUserCapPool caps; RGWAccessKeyPool keys; RGWSubUserPool subusers; /* API Contracted Methods */ int add(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int remove(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); int rename(RGWUserAdminOpState& op_state, optional_yield y, const DoutPrefixProvider *dpp, std::string *err_msg = NULL); /* remove an already populated RGWUser */ int remove(std::string *err_msg = NULL); int modify(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, optional_yield y, std::string *err_msg = NULL); /* retrieve info from an existing user in the RGW system */ int info(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, RGWUserInfo& fetched_info, optional_yield y, std::string *err_msg = NULL); /* info from an already populated RGWUser */ int info (RGWUserInfo& fetched_info, std::string *err_msg = NULL); /* list the existing users */ int list(const DoutPrefixProvider *dpp, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher); friend class RGWAccessKeyPool; friend class RGWSubUserPool; friend class RGWUserCapPool; }; /* Wrappers for admin API functionality */ class RGWUserAdminOp_User { public: static int list(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher); static int info(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int modify(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); }; class RGWUserAdminOp_Subuser { public: static int create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int modify(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); }; class RGWUserAdminOp_Key { public: static int create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); }; class RGWUserAdminOp_Caps { public: static int add(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); static int remove(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWUserAdminOpState& op_state, RGWFormatterFlusher& flusher, optional_yield y); }; struct RGWUserCompleteInfo { RGWUserInfo info; std::map<std::string, bufferlist> attrs; bool has_attrs{false}; void dump(Formatter * const f) const { info.dump(f); encode_json("attrs", attrs, f); } void decode_json(JSONObj *obj) { decode_json_obj(info, obj); has_attrs = JSONDecoder::decode_json("attrs", attrs, obj); } }; class RGWUserMetadataObject : public RGWMetadataObject { RGWUserCompleteInfo uci; public: RGWUserMetadataObject() {} RGWUserMetadataObject(const RGWUserCompleteInfo& _uci, const obj_version& v, real_time m) : uci(_uci) { objv = v; mtime = m; } void dump(Formatter *f) const override { uci.dump(f); } RGWUserCompleteInfo& get_uci() { return uci; } }; class RGWUserMetadataHandler; class RGWUserCtl { struct Svc { RGWSI_Zone *zone{nullptr}; RGWSI_User *user{nullptr}; } svc; struct Ctl { RGWBucketCtl *bucket{nullptr}; } ctl; RGWUserMetadataHandler *umhandler; RGWSI_MetaBackend_Handler *be_handler{nullptr}; public: RGWUserCtl(RGWSI_Zone *zone_svc, RGWSI_User *user_svc, RGWUserMetadataHandler *_umhandler); void init(RGWBucketCtl *bucket_ctl) { ctl.bucket = bucket_ctl; } RGWBucketCtl *get_bucket_ctl() { return ctl.bucket; } struct GetParams { RGWObjVersionTracker *objv_tracker{nullptr}; ceph::real_time *mtime{nullptr}; rgw_cache_entry_info *cache_info{nullptr}; std::map<std::string, bufferlist> *attrs{nullptr}; GetParams() {} GetParams& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } GetParams& set_mtime(ceph::real_time *_mtime) { mtime = _mtime; return *this; } GetParams& set_cache_info(rgw_cache_entry_info *_cache_info) { cache_info = _cache_info; return *this; } GetParams& set_attrs(std::map<std::string, bufferlist> *_attrs) { attrs = _attrs; return *this; } }; struct PutParams { RGWUserInfo *old_info{nullptr}; RGWObjVersionTracker *objv_tracker{nullptr}; ceph::real_time mtime; bool exclusive{false}; std::map<std::string, bufferlist> *attrs{nullptr}; PutParams() {} PutParams& set_old_info(RGWUserInfo *_info) { old_info = _info; return *this; } PutParams& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } PutParams& set_mtime(const ceph::real_time& _mtime) { mtime = _mtime; return *this; } PutParams& set_exclusive(bool _exclusive) { exclusive = _exclusive; return *this; } PutParams& set_attrs(std::map<std::string, bufferlist> *_attrs) { attrs = _attrs; return *this; } }; struct RemoveParams { RGWObjVersionTracker *objv_tracker{nullptr}; RemoveParams() {} RemoveParams& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } }; int get_info_by_uid(const DoutPrefixProvider *dpp, const rgw_user& uid, RGWUserInfo *info, optional_yield y, const GetParams& params = {}); int get_info_by_email(const DoutPrefixProvider *dpp, const std::string& email, RGWUserInfo *info, optional_yield y, const GetParams& params = {}); int get_info_by_swift(const DoutPrefixProvider *dpp, const std::string& swift_name, RGWUserInfo *info, optional_yield y, const GetParams& params = {}); int get_info_by_access_key(const DoutPrefixProvider *dpp, const std::string& access_key, RGWUserInfo *info, optional_yield y, const GetParams& params = {}); int get_attrs_by_uid(const DoutPrefixProvider *dpp, const rgw_user& user_id, std::map<std::string, bufferlist> *attrs, optional_yield y, RGWObjVersionTracker *objv_tracker = nullptr); int store_info(const DoutPrefixProvider *dpp, const RGWUserInfo& info, optional_yield y, const PutParams& params = {}); int remove_info(const DoutPrefixProvider *dpp, const RGWUserInfo& info, optional_yield y, const RemoveParams& params = {}); int list_buckets(const DoutPrefixProvider *dpp, const rgw_user& user, const std::string& marker, const std::string& end_marker, uint64_t max, bool need_stats, RGWUserBuckets *buckets, bool *is_truncated, optional_yield y, uint64_t default_max = 1000); int read_stats(const DoutPrefixProvider *dpp, const rgw_user& user, RGWStorageStats *stats, optional_yield y, ceph::real_time *last_stats_sync = nullptr, /* last time a full stats sync completed */ ceph::real_time *last_stats_update = nullptr); /* last time a stats update was done */ }; class RGWUserMetaHandlerAllocator { public: static RGWMetadataHandler *alloc(RGWSI_User *user_svc); };
26,434
28.836343
140
h
null
ceph-main/src/rgw/driver/rados/rgw_zone.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_zone.h" #include "rgw_realm_watcher.h" #include "rgw_sal_config.h" #include "rgw_sync.h" #include "services/svc_zone.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; using namespace rgw_zone_defaults; RGWMetaSyncStatusManager::~RGWMetaSyncStatusManager(){} #define FIRST_EPOCH 1 struct RGWAccessKey; /// Generate a random uuid for realm/period/zonegroup/zone ids static std::string gen_random_uuid() { uuid_d uuid; uuid.generate_random(); return uuid.to_string(); } void RGWDefaultZoneGroupInfo::dump(Formatter *f) const { encode_json("default_zonegroup", default_zonegroup, f); } void RGWDefaultZoneGroupInfo::decode_json(JSONObj *obj) { JSONDecoder::decode_json("default_zonegroup", default_zonegroup, obj); /* backward compatability with region */ if (default_zonegroup.empty()) { JSONDecoder::decode_json("default_region", default_zonegroup, obj); } } int RGWZoneGroup::create_default(const DoutPrefixProvider *dpp, optional_yield y, bool old_format) { name = default_zonegroup_name; api_name = default_zonegroup_name; is_master = true; RGWZoneGroupPlacementTarget placement_target; placement_target.name = "default-placement"; placement_targets[placement_target.name] = placement_target; default_placement.name = "default-placement"; RGWZoneParams zone_params(default_zone_name); int r = zone_params.init(dpp, cct, sysobj_svc, y, false); if (r < 0) { ldpp_dout(dpp, 0) << "create_default: error initializing zone params: " << cpp_strerror(-r) << dendl; return r; } r = zone_params.create_default(dpp, y); if (r < 0 && r != -EEXIST) { ldpp_dout(dpp, 0) << "create_default: error in create_default zone params: " << cpp_strerror(-r) << dendl; return r; } else if (r == -EEXIST) { ldpp_dout(dpp, 10) << "zone_params::create_default() returned -EEXIST, we raced with another default zone_params creation" << dendl; zone_params.clear_id(); r = zone_params.init(dpp, cct, sysobj_svc, y); if (r < 0) { ldpp_dout(dpp, 0) << "create_default: error in init existing zone params: " << cpp_strerror(-r) << dendl; return r; } ldpp_dout(dpp, 20) << "zone_params::create_default() " << zone_params.get_name() << " id " << zone_params.get_id() << dendl; } RGWZone& default_zone = zones[zone_params.get_id()]; default_zone.name = zone_params.get_name(); default_zone.id = zone_params.get_id(); master_zone = default_zone.id; // initialize supported zone features default_zone.supported_features.insert(rgw::zone_features::supported.begin(), rgw::zone_features::supported.end()); // enable default zonegroup features enabled_features.insert(rgw::zone_features::enabled.begin(), rgw::zone_features::enabled.end()); r = create(dpp, y); if (r < 0 && r != -EEXIST) { ldpp_dout(dpp, 0) << "error storing zone group info: " << cpp_strerror(-r) << dendl; return r; } if (r == -EEXIST) { ldpp_dout(dpp, 10) << "create_default() returned -EEXIST, we raced with another zonegroup creation" << dendl; id.clear(); r = init(dpp, cct, sysobj_svc, y); if (r < 0) { return r; } } if (old_format) { name = id; } post_process_params(dpp, y); return 0; } int RGWZoneGroup::equals(const string& other_zonegroup) const { if (is_master && other_zonegroup.empty()) return true; return (id == other_zonegroup); } int RGWZoneGroup::add_zone(const DoutPrefixProvider *dpp, const RGWZoneParams& zone_params, bool *is_master, bool *read_only, const list<string>& endpoints, const string *ptier_type, bool *psync_from_all, list<string>& sync_from, list<string>& sync_from_rm, string *predirect_zone, std::optional<int> bucket_index_max_shards, RGWSyncModulesManager *sync_mgr, const rgw::zone_features::set& enable_features, const rgw::zone_features::set& disable_features, optional_yield y) { auto& zone_id = zone_params.get_id(); auto& zone_name = zone_params.get_name(); // check for duplicate zone name on insert if (!zones.count(zone_id)) { for (const auto& zone : zones) { if (zone.second.name == zone_name) { ldpp_dout(dpp, 0) << "ERROR: found existing zone name " << zone_name << " (" << zone.first << ") in zonegroup " << get_name() << dendl; return -EEXIST; } } } if (is_master) { if (*is_master) { if (!master_zone.empty() && master_zone != zone_id) { ldpp_dout(dpp, 0) << "NOTICE: overriding master zone: " << master_zone << dendl; } master_zone = zone_id; } else if (master_zone == zone_id) { master_zone.clear(); } } RGWZone& zone = zones[zone_id]; zone.name = zone_name; zone.id = zone_id; if (!endpoints.empty()) { zone.endpoints = endpoints; } if (read_only) { zone.read_only = *read_only; } if (ptier_type) { zone.tier_type = *ptier_type; if (!sync_mgr->get_module(*ptier_type, nullptr)) { ldpp_dout(dpp, 0) << "ERROR: could not found sync module: " << *ptier_type << ", valid sync modules: " << sync_mgr->get_registered_module_names() << dendl; return -ENOENT; } } if (psync_from_all) { zone.sync_from_all = *psync_from_all; } if (predirect_zone) { zone.redirect_zone = *predirect_zone; } if (bucket_index_max_shards) { zone.bucket_index_max_shards = *bucket_index_max_shards; } for (auto add : sync_from) { zone.sync_from.insert(add); } for (auto rm : sync_from_rm) { zone.sync_from.erase(rm); } zone.supported_features.insert(enable_features.begin(), enable_features.end()); for (const auto& feature : disable_features) { if (enabled_features.contains(feature)) { lderr(cct) << "ERROR: Cannot disable zone feature \"" << feature << "\" until it's been disabled in zonegroup " << name << dendl; return -EINVAL; } auto i = zone.supported_features.find(feature); if (i == zone.supported_features.end()) { ldout(cct, 1) << "WARNING: zone feature \"" << feature << "\" was not enabled in zone " << zone.name << dendl; continue; } zone.supported_features.erase(i); } post_process_params(dpp, y); return update(dpp,y); } int RGWZoneGroup::rename_zone(const DoutPrefixProvider *dpp, const RGWZoneParams& zone_params, optional_yield y) { RGWZone& zone = zones[zone_params.get_id()]; zone.name = zone_params.get_name(); return update(dpp, y); } void RGWZoneGroup::post_process_params(const DoutPrefixProvider *dpp, optional_yield y) { bool log_data = zones.size() > 1; if (master_zone.empty()) { auto iter = zones.begin(); if (iter != zones.end()) { master_zone = iter->first; } } for (auto& item : zones) { RGWZone& zone = item.second; zone.log_data = log_data; RGWZoneParams zone_params(zone.id, zone.name); int ret = zone_params.init(dpp, cct, sysobj_svc, y); if (ret < 0) { ldpp_dout(dpp, 0) << "WARNING: could not read zone params for zone id=" << zone.id << " name=" << zone.name << dendl; continue; } for (auto& pitem : zone_params.placement_pools) { const string& placement_name = pitem.first; if (placement_targets.find(placement_name) == placement_targets.end()) { RGWZoneGroupPlacementTarget placement_target; placement_target.name = placement_name; placement_targets[placement_name] = placement_target; } } } if (default_placement.empty() && !placement_targets.empty()) { default_placement.init(placement_targets.begin()->first, RGW_STORAGE_CLASS_STANDARD); } } int RGWZoneGroup::remove_zone(const DoutPrefixProvider *dpp, const std::string& zone_id, optional_yield y) { auto iter = zones.find(zone_id); if (iter == zones.end()) { ldpp_dout(dpp, 0) << "zone id " << zone_id << " is not a part of zonegroup " << name << dendl; return -ENOENT; } zones.erase(iter); post_process_params(dpp, y); return update(dpp, y); } void RGWDefaultSystemMetaObjInfo::dump(Formatter *f) const { encode_json("default_id", default_id, f); } void RGWDefaultSystemMetaObjInfo::decode_json(JSONObj *obj) { JSONDecoder::decode_json("default_id", default_id, obj); } int RGWSystemMetaObj::rename(const DoutPrefixProvider *dpp, const string& new_name, optional_yield y) { string new_id; int ret = read_id(dpp, new_name, new_id, y); if (!ret) { return -EEXIST; } if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "Error read_id " << new_name << ": " << cpp_strerror(-ret) << dendl; return ret; } string old_name = name; name = new_name; ret = update(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "Error storing new obj info " << new_name << ": " << cpp_strerror(-ret) << dendl; return ret; } ret = store_name(dpp, true, y); if (ret < 0) { ldpp_dout(dpp, 0) << "Error storing new name " << new_name << ": " << cpp_strerror(-ret) << dendl; return ret; } /* delete old name */ rgw_pool pool(get_pool(cct)); string oid = get_names_oid_prefix() + old_name; rgw_raw_obj old_name_obj(pool, oid); auto sysobj = sysobj_svc->get_obj(old_name_obj); ret = sysobj.wop().remove(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "Error delete old obj name " << old_name << ": " << cpp_strerror(-ret) << dendl; return ret; } return ret; } int RGWSystemMetaObj::read(const DoutPrefixProvider *dpp, optional_yield y) { int ret = read_id(dpp, name, id, y); if (ret < 0) { return ret; } return read_info(dpp, id, y); } int RGWZoneParams::create_default(const DoutPrefixProvider *dpp, optional_yield y, bool old_format) { name = default_zone_name; int r = create(dpp, y); if (r < 0) { return r; } if (old_format) { name = id; } return r; } const string& RGWZoneParams::get_compression_type(const rgw_placement_rule& placement_rule) const { static const std::string NONE{"none"}; auto p = placement_pools.find(placement_rule.name); if (p == placement_pools.end()) { return NONE; } const auto& type = p->second.get_compression_type(placement_rule.get_storage_class()); return !type.empty() ? type : NONE; } // run an MD5 hash on the zone_id and return the first 32 bits static uint32_t gen_short_zone_id(const std::string zone_id) { unsigned char md5[CEPH_CRYPTO_MD5_DIGESTSIZE]; MD5 hash; // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); hash.Update((const unsigned char *)zone_id.c_str(), zone_id.size()); hash.Final(md5); uint32_t short_id; memcpy((char *)&short_id, md5, sizeof(short_id)); return std::max(short_id, 1u); } int RGWPeriodMap::update(const RGWZoneGroup& zonegroup, CephContext *cct) { if (zonegroup.is_master_zonegroup() && (!master_zonegroup.empty() && zonegroup.get_id() != master_zonegroup)) { ldout(cct,0) << "Error updating periodmap, multiple master zonegroups configured "<< dendl; ldout(cct,0) << "master zonegroup: " << master_zonegroup << " and " << zonegroup.get_id() <<dendl; return -EINVAL; } map<string, RGWZoneGroup>::iterator iter = zonegroups.find(zonegroup.get_id()); if (iter != zonegroups.end()) { RGWZoneGroup& old_zonegroup = iter->second; if (!old_zonegroup.api_name.empty()) { zonegroups_by_api.erase(old_zonegroup.api_name); } } zonegroups[zonegroup.get_id()] = zonegroup; if (!zonegroup.api_name.empty()) { zonegroups_by_api[zonegroup.api_name] = zonegroup; } if (zonegroup.is_master_zonegroup()) { master_zonegroup = zonegroup.get_id(); } else if (master_zonegroup == zonegroup.get_id()) { master_zonegroup = ""; } for (auto& i : zonegroup.zones) { auto& zone = i.second; if (short_zone_ids.find(zone.id) != short_zone_ids.end()) { continue; } // calculate the zone's short id uint32_t short_id = gen_short_zone_id(zone.id); // search for an existing zone with the same short id for (auto& s : short_zone_ids) { if (s.second == short_id) { ldout(cct, 0) << "New zone '" << zone.name << "' (" << zone.id << ") generates the same short_zone_id " << short_id << " as existing zone id " << s.first << dendl; return -EEXIST; } } short_zone_ids[zone.id] = short_id; } return 0; } uint32_t RGWPeriodMap::get_zone_short_id(const string& zone_id) const { auto i = short_zone_ids.find(zone_id); if (i == short_zone_ids.end()) { return 0; } return i->second; } bool RGWPeriodMap::find_zone_by_name(const string& zone_name, RGWZoneGroup *zonegroup, RGWZone *zone) const { for (auto& iter : zonegroups) { auto& zg = iter.second; for (auto& ziter : zg.zones) { auto& z = ziter.second; if (z.name == zone_name) { *zonegroup = zg; *zone = z; return true; } } } return false; } namespace rgw { int read_realm(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, std::string_view realm_id, std::string_view realm_name, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) { if (!realm_id.empty()) { return cfgstore->read_realm_by_id(dpp, y, realm_id, info, writer); } if (!realm_name.empty()) { return cfgstore->read_realm_by_name(dpp, y, realm_name, info, writer); } return cfgstore->read_default_realm(dpp, y, info, writer); } int create_realm(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer_out) { if (info.name.empty()) { ldpp_dout(dpp, -1) << __func__ << " requires a realm name" << dendl; return -EINVAL; } if (info.id.empty()) { info.id = gen_random_uuid(); } // if the realm already has a current_period, just make sure it exists std::optional<RGWPeriod> period; if (!info.current_period.empty()) { period.emplace(); int r = cfgstore->read_period(dpp, y, info.current_period, std::nullopt, *period); if (r < 0) { ldpp_dout(dpp, -1) << __func__ << " failed to read realm's current_period=" << info.current_period << " with " << cpp_strerror(r) << dendl; return r; } } // create the realm std::unique_ptr<sal::RealmWriter> writer; int r = cfgstore->create_realm(dpp, y, exclusive, info, &writer); if (r < 0) { return r; } if (!period) { // initialize and exclusive-create the initial period period.emplace(); period->id = gen_random_uuid(); period->period_map.id = period->id; period->epoch = FIRST_EPOCH; period->realm_id = info.id; period->realm_name = info.name; r = cfgstore->create_period(dpp, y, true, *period); if (r < 0) { ldpp_dout(dpp, -1) << __func__ << " failed to create the initial period id=" << period->id << " for realm " << info.name << " with " << cpp_strerror(r) << dendl; return r; } } // update the realm's current_period r = realm_set_current_period(dpp, y, cfgstore, *writer, info, *period); if (r < 0) { return r; } // try to set as default. may race with another create, so pass exclusive=true // so we don't override an existing default r = set_default_realm(dpp, y, cfgstore, info, true); if (r < 0 && r != -EEXIST) { ldpp_dout(dpp, 0) << "WARNING: failed to set realm as default: " << cpp_strerror(r) << dendl; } if (writer_out) { *writer_out = std::move(writer); } return 0; } int set_default_realm(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWRealm& info, bool exclusive) { return cfgstore->write_default_realm_id(dpp, y, exclusive, info.id); } int realm_set_current_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, sal::RealmWriter& writer, RGWRealm& realm, const RGWPeriod& period) { // update realm epoch to match the period's if (realm.epoch > period.realm_epoch) { ldpp_dout(dpp, -1) << __func__ << " with old realm epoch " << period.realm_epoch << ", current epoch=" << realm.epoch << dendl; return -EINVAL; } if (realm.epoch == period.realm_epoch && realm.current_period != period.id) { ldpp_dout(dpp, -1) << __func__ << " with same realm epoch " << period.realm_epoch << ", but different period id " << period.id << " != " << realm.current_period << dendl; return -EINVAL; } realm.epoch = period.realm_epoch; realm.current_period = period.id; // update the realm object int r = writer.write(dpp, y, realm); if (r < 0) { ldpp_dout(dpp, -1) << __func__ << " failed to overwrite realm " << realm.name << " with " << cpp_strerror(r) << dendl; return r; } // reflect the zonegroup and period config (void) reflect_period(dpp, y, cfgstore, period); return 0; } int reflect_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWPeriod& info) { // overwrite the local period config and zonegroup objects constexpr bool exclusive = false; int r = cfgstore->write_period_config(dpp, y, exclusive, info.realm_id, info.period_config); if (r < 0) { ldpp_dout(dpp, -1) << __func__ << " failed to store period config for realm id=" << info.realm_id << " with " << cpp_strerror(r) << dendl; return r; } for (auto& [zonegroup_id, zonegroup] : info.period_map.zonegroups) { r = cfgstore->create_zonegroup(dpp, y, exclusive, zonegroup, nullptr); if (r < 0) { ldpp_dout(dpp, -1) << __func__ << " failed to store zonegroup id=" << zonegroup_id << " with " << cpp_strerror(r) << dendl; return r; } if (zonegroup.is_master) { // set master as default if no default exists constexpr bool exclusive = true; r = set_default_zonegroup(dpp, y, cfgstore, zonegroup, exclusive); if (r == 0) { ldpp_dout(dpp, 1) << "Set the period's master zonegroup " << zonegroup.name << " as the default" << dendl; } } } return 0; } std::string get_staging_period_id(std::string_view realm_id) { return string_cat_reserve(realm_id, ":staging"); } void fork_period(const DoutPrefixProvider* dpp, RGWPeriod& info) { ldpp_dout(dpp, 20) << __func__ << " realm id=" << info.realm_id << " period id=" << info.id << dendl; info.predecessor_uuid = std::move(info.id); info.id = get_staging_period_id(info.realm_id); info.period_map.reset(); info.realm_epoch++; } int update_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, RGWPeriod& info) { // clear zone short ids of removed zones. period_map.update() will add the // remaining zones back info.period_map.short_zone_ids.clear(); // list all zonegroups in the realm rgw::sal::ListResult<std::string> listing; std::array<std::string, 1000> zonegroup_names; // list in pages of 1000 do { int ret = cfgstore->list_zonegroup_names(dpp, y, listing.next, zonegroup_names, listing); if (ret < 0) { std::cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl; return -ret; } for (const auto& name : listing.entries) { RGWZoneGroup zg; ret = cfgstore->read_zonegroup_by_name(dpp, y, name, zg, nullptr); if (ret < 0) { ldpp_dout(dpp, 0) << "WARNING: failed to read zonegroup " << name << ": " << cpp_strerror(-ret) << dendl; continue; } if (zg.realm_id != info.realm_id) { ldpp_dout(dpp, 20) << "skipping zonegroup " << zg.get_name() << " with realm id " << zg.realm_id << ", not on our realm " << info.realm_id << dendl; continue; } if (zg.master_zone.empty()) { ldpp_dout(dpp, 0) << "ERROR: zonegroup " << zg.get_name() << " should have a master zone " << dendl; return -EINVAL; } if (zg.zones.find(zg.master_zone) == zg.zones.end()) { ldpp_dout(dpp, 0) << "ERROR: zonegroup " << zg.get_name() << " has a non existent master zone "<< dendl; return -EINVAL; } if (zg.is_master_zonegroup()) { info.master_zonegroup = zg.get_id(); info.master_zone = zg.master_zone; } ret = info.period_map.update(zg, dpp->get_cct()); if (ret < 0) { return ret; } } // foreach name in listing.entries } while (!listing.next.empty()); // read the realm's current period config int ret = cfgstore->read_period_config(dpp, y, info.realm_id, info.period_config); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: failed to read period config: " << cpp_strerror(ret) << dendl; return ret; } return 0; } int commit_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, sal::Driver* driver, RGWRealm& realm, sal::RealmWriter& realm_writer, const RGWPeriod& current_period, RGWPeriod& info, std::ostream& error_stream, bool force_if_stale) { auto zone_svc = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone; // XXX ldpp_dout(dpp, 20) << __func__ << " realm " << realm.id << " period " << current_period.id << dendl; // gateway must be in the master zone to commit if (info.master_zone != zone_svc->get_zone_params().id) { error_stream << "Cannot commit period on zone " << zone_svc->get_zone_params().id << ", it must be sent to " "the period's master zone " << info.master_zone << '.' << std::endl; return -EINVAL; } // period predecessor must match current period if (info.predecessor_uuid != current_period.id) { error_stream << "Period predecessor " << info.predecessor_uuid << " does not match current period " << current_period.id << ". Use 'period pull' to get the latest period from the master, " "reapply your changes, and try again." << std::endl; return -EINVAL; } // realm epoch must be 1 greater than current period if (info.realm_epoch != current_period.realm_epoch + 1) { error_stream << "Period's realm epoch " << info.realm_epoch << " does not come directly after current realm epoch " << current_period.realm_epoch << ". Use 'realm pull' to get the " "latest realm and period from the master zone, reapply your changes, " "and try again." << std::endl; return -EINVAL; } // did the master zone change? if (info.master_zone != current_period.master_zone) { // store the current metadata sync status in the period int r = info.update_sync_status(dpp, driver, current_period, error_stream, force_if_stale); if (r < 0) { ldpp_dout(dpp, 0) << "failed to update metadata sync status: " << cpp_strerror(-r) << dendl; return r; } // create an object with a new period id info.period_map.id = info.id = gen_random_uuid(); info.epoch = FIRST_EPOCH; constexpr bool exclusive = true; r = cfgstore->create_period(dpp, y, exclusive, info); if (r < 0) { ldpp_dout(dpp, 0) << "failed to create new period: " << cpp_strerror(-r) << dendl; return r; } // set as current period r = realm_set_current_period(dpp, y, cfgstore, realm_writer, realm, info); if (r < 0) { ldpp_dout(dpp, 0) << "failed to update realm's current period: " << cpp_strerror(-r) << dendl; return r; } ldpp_dout(dpp, 4) << "Promoted to master zone and committed new period " << info.id << dendl; (void) cfgstore->realm_notify_new_period(dpp, y, info); return 0; } // period must be based on current epoch if (info.epoch != current_period.epoch) { error_stream << "Period epoch " << info.epoch << " does not match " "predecessor epoch " << current_period.epoch << ". Use " "'period pull' to get the latest epoch from the master zone, " "reapply your changes, and try again." << std::endl; return -EINVAL; } // set period as next epoch info.id = current_period.id; info.epoch = current_period.epoch + 1; info.predecessor_uuid = current_period.predecessor_uuid; info.realm_epoch = current_period.realm_epoch; // write the period constexpr bool exclusive = true; int r = cfgstore->create_period(dpp, y, exclusive, info); if (r == -EEXIST) { // already have this epoch (or a more recent one) return 0; } if (r < 0) { ldpp_dout(dpp, 0) << "failed to store period: " << cpp_strerror(r) << dendl; return r; } r = reflect_period(dpp, y, cfgstore, info); if (r < 0) { ldpp_dout(dpp, 0) << "failed to update local objects: " << cpp_strerror(r) << dendl; return r; } ldpp_dout(dpp, 4) << "Committed new epoch " << info.epoch << " for period " << info.id << dendl; (void) cfgstore->realm_notify_new_period(dpp, y, info); return 0; } int read_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, std::string_view zonegroup_id, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) { if (!zonegroup_id.empty()) { return cfgstore->read_zonegroup_by_id(dpp, y, zonegroup_id, info, writer); } if (!zonegroup_name.empty()) { return cfgstore->read_zonegroup_by_name(dpp, y, zonegroup_name, info, writer); } std::string realm_id; int r = cfgstore->read_default_realm_id(dpp, y, realm_id); if (r == -ENOENT) { return cfgstore->read_zonegroup_by_name(dpp, y, default_zonegroup_name, info, writer); } if (r < 0) { return r; } return cfgstore->read_default_zonegroup(dpp, y, realm_id, info, writer); } int create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, RGWZoneGroup& info) { if (info.name.empty()) { ldpp_dout(dpp, -1) << __func__ << " requires a zonegroup name" << dendl; return -EINVAL; } if (info.id.empty()) { info.id = gen_random_uuid(); } // insert the default placement target if it doesn't exist constexpr std::string_view default_placement_name = "default-placement"; RGWZoneGroupPlacementTarget placement_target; placement_target.name = default_placement_name; info.placement_targets.emplace(default_placement_name, placement_target); if (info.default_placement.name.empty()) { info.default_placement.name = default_placement_name; } int r = cfgstore->create_zonegroup(dpp, y, exclusive, info, nullptr); if (r < 0) { ldpp_dout(dpp, 0) << "failed to create zonegroup with " << cpp_strerror(r) << dendl; return r; } // try to set as default. may race with another create, so pass exclusive=true // so we don't override an existing default r = set_default_zonegroup(dpp, y, cfgstore, info, true); if (r < 0 && r != -EEXIST) { ldpp_dout(dpp, 0) << "WARNING: failed to set zonegroup as default: " << cpp_strerror(r) << dendl; } return 0; } static int create_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, const RGWZoneParams& default_zone, RGWZoneGroup& info) { info.name = default_zonegroup_name; info.api_name = default_zonegroup_name; info.is_master = true; // enable all supported features info.enabled_features.insert(rgw::zone_features::enabled.begin(), rgw::zone_features::enabled.end()); // add the zone to the zonegroup bool is_master = true; std::list<std::string> empty_list; rgw::zone_features::set disable_features; // empty int r = add_zone_to_group(dpp, info, default_zone, &is_master, nullptr, empty_list, nullptr, nullptr, empty_list, empty_list, nullptr, std::nullopt, info.enabled_features, disable_features); if (r < 0) { return r; } // write the zone return create_zonegroup(dpp, y, cfgstore, exclusive, info); } int set_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneGroup& info, bool exclusive) { return cfgstore->write_default_zonegroup_id( dpp, y, exclusive, info.realm_id, info.id); } int remove_zone_from_group(const DoutPrefixProvider* dpp, RGWZoneGroup& zonegroup, const rgw_zone_id& zone_id) { auto z = zonegroup.zones.find(zone_id); if (z == zonegroup.zones.end()) { return -ENOENT; } zonegroup.zones.erase(z); if (zonegroup.master_zone == zone_id) { // choose a new master zone auto m = zonegroup.zones.begin(); if (m != zonegroup.zones.end()) { zonegroup.master_zone = m->first; ldpp_dout(dpp, 0) << "NOTICE: promoted " << m->second.name << " as new master_zone of zonegroup " << zonegroup.name << dendl; } else { ldpp_dout(dpp, 0) << "NOTICE: removed master_zone of zonegroup " << zonegroup.name << dendl; } } const bool log_data = zonegroup.zones.size() > 1; for (auto& [id, zone] : zonegroup.zones) { zone.log_data = log_data; } return 0; } // try to remove the given zone id from every zonegroup in the cluster static int remove_zone_from_groups(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const rgw_zone_id& zone_id) { std::array<std::string, 128> zonegroup_names; sal::ListResult<std::string> listing; do { int r = cfgstore->list_zonegroup_names(dpp, y, listing.next, zonegroup_names, listing); if (r < 0) { ldpp_dout(dpp, 0) << "failed to list zonegroups with " << cpp_strerror(r) << dendl; return r; } for (const auto& name : listing.entries) { RGWZoneGroup zonegroup; std::unique_ptr<sal::ZoneGroupWriter> writer; r = cfgstore->read_zonegroup_by_name(dpp, y, name, zonegroup, &writer); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: failed to load zonegroup " << name << " with " << cpp_strerror(r) << dendl; continue; } r = remove_zone_from_group(dpp, zonegroup, zone_id); if (r < 0) { continue; } // write the updated zonegroup r = writer->write(dpp, y, zonegroup); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: failed to write zonegroup " << name << " with " << cpp_strerror(r) << dendl; continue; } ldpp_dout(dpp, 0) << "Removed zone from zonegroup " << name << dendl; } } while (!listing.next.empty()); return 0; } int read_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, std::string_view zone_id, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) { if (!zone_id.empty()) { return cfgstore->read_zone_by_id(dpp, y, zone_id, info, writer); } if (!zone_name.empty()) { return cfgstore->read_zone_by_name(dpp, y, zone_name, info, writer); } std::string realm_id; int r = cfgstore->read_default_realm_id(dpp, y, realm_id); if (r == -ENOENT) { return cfgstore->read_zone_by_name(dpp, y, default_zone_name, info, writer); } if (r < 0) { return r; } return cfgstore->read_default_zone(dpp, y, realm_id, info, writer); } extern int get_zones_pool_set(const DoutPrefixProvider *dpp, optional_yield y, rgw::sal::ConfigStore* cfgstore, std::string_view my_zone_id, std::set<rgw_pool>& pools); int create_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) { if (info.name.empty()) { ldpp_dout(dpp, -1) << __func__ << " requires a zone name" << dendl; return -EINVAL; } if (info.id.empty()) { info.id = gen_random_uuid(); } // add default placement with empty pool name rgw_pool pool; auto& placement = info.placement_pools["default-placement"]; placement.storage_classes.set_storage_class( RGW_STORAGE_CLASS_STANDARD, &pool, nullptr); // build a set of all pool names used by other zones std::set<rgw_pool> pools; int r = get_zones_pool_set(dpp, y, cfgstore, info.id, pools); if (r < 0) { return r; } // initialize pool names with the zone name prefix r = init_zone_pool_names(dpp, y, pools, info); if (r < 0) { return r; } r = cfgstore->create_zone(dpp, y, exclusive, info, nullptr); if (r < 0) { ldpp_dout(dpp, 0) << "failed to create zone with " << cpp_strerror(r) << dendl; return r; } // try to set as default. may race with another create, so pass exclusive=true // so we don't override an existing default r = set_default_zone(dpp, y, cfgstore, info, true); if (r < 0 && r != -EEXIST) { ldpp_dout(dpp, 0) << "WARNING: failed to set zone as default: " << cpp_strerror(r) << dendl; } return 0; } int set_default_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneParams& info, bool exclusive) { return cfgstore->write_default_zone_id( dpp, y, exclusive, info.realm_id, info.id); } int delete_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneParams& info, sal::ZoneWriter& writer) { // remove this zone from any zonegroups that contain it int r = remove_zone_from_groups(dpp, y, cfgstore, info.id); if (r < 0) { return r; } return writer.remove(dpp, y); } static int read_or_create_default_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, RGWZoneParams& info) { int r = cfgstore->read_zone_by_name(dpp, y, default_zone_name, info, nullptr); if (r == -ENOENT) { info.name = default_zone_name; constexpr bool exclusive = true; r = create_zone(dpp, y, cfgstore, exclusive, info, nullptr); if (r == -EEXIST) { r = cfgstore->read_zone_by_name(dpp, y, default_zone_name, info, nullptr); } if (r < 0) { ldpp_dout(dpp, 0) << "failed to create default zone: " << cpp_strerror(r) << dendl; return r; } } return r; } static int read_or_create_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneParams& zone_params, RGWZoneGroup& info) { int r = cfgstore->read_zonegroup_by_name(dpp, y, default_zonegroup_name, info, nullptr); if (r == -ENOENT) { constexpr bool exclusive = true; r = create_default_zonegroup(dpp, y, cfgstore, exclusive, zone_params, info); if (r == -EEXIST) { r = cfgstore->read_zonegroup_by_name(dpp, y, default_zonegroup_name, info, nullptr); } if (r < 0) { ldpp_dout(dpp, 0) << "failed to create default zonegroup: " << cpp_strerror(r) << dendl; return r; } } return r; } int SiteConfig::load(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore) { // clear existing configuration zone = nullptr; zonegroup = nullptr; local_zonegroup = std::nullopt; period = std::nullopt; zone_params = RGWZoneParams{}; int r = 0; // try to load a realm realm.emplace(); std::string realm_name = dpp->get_cct()->_conf->rgw_realm; if (!realm_name.empty()) { r = cfgstore->read_realm_by_name(dpp, y, realm_name, *realm, nullptr); } else { r = cfgstore->read_default_realm(dpp, y, *realm, nullptr); if (r == -ENOENT) { // no realm r = 0; realm = std::nullopt; } } if (r < 0) { ldpp_dout(dpp, 0) << "failed to load realm: " << cpp_strerror(r) << dendl; return r; } // try to load the local zone params std::string zone_name = dpp->get_cct()->_conf->rgw_zone; if (!zone_name.empty()) { r = cfgstore->read_zone_by_name(dpp, y, zone_name, zone_params, nullptr); } else if (realm) { // load the realm's default zone r = cfgstore->read_default_zone(dpp, y, realm->id, zone_params, nullptr); } else { // load or create the "default" zone r = read_or_create_default_zone(dpp, y, cfgstore, zone_params); } if (r < 0) { ldpp_dout(dpp, 0) << "failed to load zone: " << cpp_strerror(r) << dendl; return r; } if (!realm && !zone_params.realm_id.empty()) { realm.emplace(); r = cfgstore->read_realm_by_id(dpp, y, zone_params.realm_id, *realm, nullptr); if (r < 0) { ldpp_dout(dpp, 0) << "failed to load realm: " << cpp_strerror(r) << dendl; return r; } } if (realm) { // try to load the realm's period r = load_period_zonegroup(dpp, y, cfgstore, *realm, zone_params.id); } else { // fall back to a local zonegroup r = load_local_zonegroup(dpp, y, cfgstore, zone_params.id); } return r; } int SiteConfig::load_period_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWRealm& realm, const rgw_zone_id& zone_id) { // load the realm's current period period.emplace(); int r = cfgstore->read_period(dpp, y, realm.current_period, std::nullopt, *period); if (r < 0) { ldpp_dout(dpp, 0) << "failed to load current period: " << cpp_strerror(r) << dendl; return r; } // find our zone and zonegroup in the period for (const auto& zg : period->period_map.zonegroups) { auto z = zg.second.zones.find(zone_id); if (z != zg.second.zones.end()) { zone = &z->second; zonegroup = &zg.second; return 0; } } ldpp_dout(dpp, 0) << "ERROR: current period " << period->id << " does not contain zone id " << zone_id << dendl; period = std::nullopt; return -ENOENT; } int SiteConfig::load_local_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const rgw_zone_id& zone_id) { int r = 0; // load the zonegroup local_zonegroup.emplace(); std::string zonegroup_name = dpp->get_cct()->_conf->rgw_zonegroup; if (!zonegroup_name.empty()) { r = cfgstore->read_zonegroup_by_name(dpp, y, zonegroup_name, *local_zonegroup, nullptr); } else { r = read_or_create_default_zonegroup(dpp, y, cfgstore, zone_params, *local_zonegroup); } if (r < 0) { ldpp_dout(dpp, 0) << "failed to load zonegroup: " << cpp_strerror(r) << dendl; } else { // find our zone in the zonegroup auto z = local_zonegroup->zones.find(zone_id); if (z != local_zonegroup->zones.end()) { zone = &z->second; zonegroup = &*local_zonegroup; return 0; } ldpp_dout(dpp, 0) << "ERROR: zonegroup " << local_zonegroup->id << " does not contain zone id " << zone_id << dendl; r = -ENOENT; } local_zonegroup = std::nullopt; return r; } } // namespace rgw static inline int conf_to_uint64(const JSONFormattable& config, const string& key, uint64_t *pval) { string sval; if (config.find(key, &sval)) { string err; uint64_t val = strict_strtoll(sval.c_str(), 10, &err); if (!err.empty()) { return -EINVAL; } *pval = val; } return 0; } int RGWZoneGroupPlacementTier::update_params(const JSONFormattable& config) { int r = -1; if (config.exists("retain_head_object")) { string s = config["retain_head_object"]; if (s == "true") { retain_head_object = true; } else { retain_head_object = false; } } if (tier_type == "cloud-s3") { r = t.s3.update_params(config); } return r; } int RGWZoneGroupPlacementTier::clear_params(const JSONFormattable& config) { if (config.exists("retain_head_object")) { retain_head_object = false; } if (tier_type == "cloud-s3") { t.s3.clear_params(config); } return 0; } int RGWZoneGroupPlacementTierS3::update_params(const JSONFormattable& config) { int r = -1; if (config.exists("endpoint")) { endpoint = config["endpoint"]; } if (config.exists("target_path")) { target_path = config["target_path"]; } if (config.exists("region")) { region = config["region"]; } if (config.exists("host_style")) { string s; s = config["host_style"]; if (s != "virtual") { host_style = PathStyle; } else { host_style = VirtualStyle; } } if (config.exists("target_storage_class")) { target_storage_class = config["target_storage_class"]; } if (config.exists("access_key")) { key.id = config["access_key"]; } if (config.exists("secret")) { key.key = config["secret"]; } if (config.exists("multipart_sync_threshold")) { r = conf_to_uint64(config, "multipart_sync_threshold", &multipart_sync_threshold); if (r < 0) { multipart_sync_threshold = DEFAULT_MULTIPART_SYNC_PART_SIZE; } } if (config.exists("multipart_min_part_size")) { r = conf_to_uint64(config, "multipart_min_part_size", &multipart_min_part_size); if (r < 0) { multipart_min_part_size = DEFAULT_MULTIPART_SYNC_PART_SIZE; } } if (config.exists("acls")) { const JSONFormattable& cc = config["acls"]; if (cc.is_array()) { for (auto& c : cc.array()) { RGWTierACLMapping m; m.init(c); if (!m.source_id.empty()) { acl_mappings[m.source_id] = m; } } } else { RGWTierACLMapping m; m.init(cc); if (!m.source_id.empty()) { acl_mappings[m.source_id] = m; } } } return 0; } int RGWZoneGroupPlacementTierS3::clear_params(const JSONFormattable& config) { if (config.exists("endpoint")) { endpoint.clear(); } if (config.exists("target_path")) { target_path.clear(); } if (config.exists("region")) { region.clear(); } if (config.exists("host_style")) { /* default */ host_style = PathStyle; } if (config.exists("target_storage_class")) { target_storage_class.clear(); } if (config.exists("access_key")) { key.id.clear(); } if (config.exists("secret")) { key.key.clear(); } if (config.exists("multipart_sync_threshold")) { multipart_sync_threshold = DEFAULT_MULTIPART_SYNC_PART_SIZE; } if (config.exists("multipart_min_part_size")) { multipart_min_part_size = DEFAULT_MULTIPART_SYNC_PART_SIZE; } if (config.exists("acls")) { const JSONFormattable& cc = config["acls"]; if (cc.is_array()) { for (auto& c : cc.array()) { RGWTierACLMapping m; m.init(c); acl_mappings.erase(m.source_id); } } else { RGWTierACLMapping m; m.init(cc); acl_mappings.erase(m.source_id); } } return 0; } void rgw_meta_sync_info::generate_test_instances(list<rgw_meta_sync_info*>& o) { auto info = new rgw_meta_sync_info; info->state = rgw_meta_sync_info::StateBuildingFullSyncMaps; info->period = "periodid"; info->realm_epoch = 5; o.push_back(info); o.push_back(new rgw_meta_sync_info); } void rgw_meta_sync_marker::generate_test_instances(list<rgw_meta_sync_marker*>& o) { auto marker = new rgw_meta_sync_marker; marker->state = rgw_meta_sync_marker::IncrementalSync; marker->marker = "01234"; marker->realm_epoch = 5; o.push_back(marker); o.push_back(new rgw_meta_sync_marker); } void rgw_meta_sync_status::generate_test_instances(list<rgw_meta_sync_status*>& o) { o.push_back(new rgw_meta_sync_status); } void RGWZoneParams::generate_test_instances(list<RGWZoneParams*> &o) { o.push_back(new RGWZoneParams); o.push_back(new RGWZoneParams); } void RGWPeriodLatestEpochInfo::generate_test_instances(list<RGWPeriodLatestEpochInfo*> &o) { RGWPeriodLatestEpochInfo *z = new RGWPeriodLatestEpochInfo; o.push_back(z); o.push_back(new RGWPeriodLatestEpochInfo); } void RGWZoneGroup::generate_test_instances(list<RGWZoneGroup*>& o) { RGWZoneGroup *r = new RGWZoneGroup; o.push_back(r); o.push_back(new RGWZoneGroup); } void RGWPeriodLatestEpochInfo::dump(Formatter *f) const { encode_json("latest_epoch", epoch, f); } void RGWPeriodLatestEpochInfo::decode_json(JSONObj *obj) { JSONDecoder::decode_json("latest_epoch", epoch, obj); } void RGWNameToId::dump(Formatter *f) const { encode_json("obj_id", obj_id, f); } void RGWNameToId::decode_json(JSONObj *obj) { JSONDecoder::decode_json("obj_id", obj_id, obj); }
46,852
30.131561
136
cc
null
ceph-main/src/rgw/driver/rados/rgw_zone.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 <ostream> #include "rgw_zone_types.h" #include "rgw_common.h" #include "rgw_sal_fwd.h" #include "rgw_sync_policy.h" class RGWSyncModulesManager; class RGWSI_SysObj; class RGWSI_Zone; class RGWSystemMetaObj { public: std::string id; std::string name; CephContext *cct{nullptr}; RGWSI_SysObj *sysobj_svc{nullptr}; RGWSI_Zone *zone_svc{nullptr}; int store_name(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y); int store_info(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y); int read_info(const DoutPrefixProvider *dpp, const std::string& obj_id, optional_yield y, bool old_format = false); int read_id(const DoutPrefixProvider *dpp, const std::string& obj_name, std::string& obj_id, optional_yield y); int read_default(const DoutPrefixProvider *dpp, RGWDefaultSystemMetaObjInfo& default_info, const std::string& oid, optional_yield y); /* read and use default id */ int use_default(const DoutPrefixProvider *dpp, optional_yield y, bool old_format = false); public: RGWSystemMetaObj() {} RGWSystemMetaObj(const std::string& _name): name(_name) {} RGWSystemMetaObj(const std::string& _id, const std::string& _name) : id(_id), name(_name) {} RGWSystemMetaObj(CephContext *_cct, RGWSI_SysObj *_sysobj_svc) { reinit_instance(_cct, _sysobj_svc); } RGWSystemMetaObj(const std::string& _name, CephContext *_cct, RGWSI_SysObj *_sysobj_svc): name(_name) { reinit_instance(_cct, _sysobj_svc); } const std::string& get_name() const { return name; } const std::string& get_id() const { return id; } void set_name(const std::string& _name) { name = _name;} void set_id(const std::string& _id) { id = _id;} void clear_id() { id.clear(); } virtual ~RGWSystemMetaObj() {} virtual void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(name, bl); ENCODE_FINISH(bl); } virtual void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); decode(name, bl); DECODE_FINISH(bl); } void reinit_instance(CephContext *_cct, RGWSI_SysObj *_sysobj_svc); int init(const DoutPrefixProvider *dpp, CephContext *_cct, RGWSI_SysObj *_sysobj_svc, optional_yield y, bool setup_obj = true, bool old_format = false); virtual int read_default_id(const DoutPrefixProvider *dpp, std::string& default_id, optional_yield y, bool old_format = false); virtual int set_as_default(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = false); int delete_default(); virtual int create(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = true); int delete_obj(const DoutPrefixProvider *dpp, optional_yield y, bool old_format = false); int rename(const DoutPrefixProvider *dpp, const std::string& new_name, optional_yield y); int update(const DoutPrefixProvider *dpp, optional_yield y) { return store_info(dpp, false, y);} int update_name(const DoutPrefixProvider *dpp, optional_yield y) { return store_name(dpp, false, y);} int read(const DoutPrefixProvider *dpp, optional_yield y); int write(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y); virtual rgw_pool get_pool(CephContext *cct) const = 0; virtual const std::string get_default_oid(bool old_format = false) const = 0; virtual const std::string& get_names_oid_prefix() const = 0; virtual const std::string& get_info_oid_prefix(bool old_format = false) const = 0; virtual std::string get_predefined_id(CephContext *cct) const = 0; virtual const std::string& get_predefined_name(CephContext *cct) const = 0; void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWSystemMetaObj) struct RGWZoneParams : RGWSystemMetaObj { rgw_pool domain_root; rgw_pool control_pool; rgw_pool gc_pool; rgw_pool lc_pool; rgw_pool log_pool; rgw_pool intent_log_pool; rgw_pool usage_log_pool; rgw_pool user_keys_pool; rgw_pool user_email_pool; rgw_pool user_swift_pool; rgw_pool user_uid_pool; rgw_pool roles_pool; rgw_pool reshard_pool; rgw_pool otp_pool; rgw_pool oidc_pool; rgw_pool notif_pool; RGWAccessKey system_key; std::map<std::string, RGWZonePlacementInfo> placement_pools; std::string realm_id; JSONFormattable tier_config; RGWZoneParams() : RGWSystemMetaObj() {} explicit RGWZoneParams(const std::string& name) : RGWSystemMetaObj(name){} RGWZoneParams(const rgw_zone_id& id, const std::string& name) : RGWSystemMetaObj(id.id, name) {} RGWZoneParams(const rgw_zone_id& id, const std::string& name, const std::string& _realm_id) : RGWSystemMetaObj(id.id, name), realm_id(_realm_id) {} virtual ~RGWZoneParams(); rgw_pool get_pool(CephContext *cct) const override; const std::string get_default_oid(bool old_format = false) const override; const std::string& get_names_oid_prefix() const override; const std::string& get_info_oid_prefix(bool old_format = false) const override; std::string get_predefined_id(CephContext *cct) const override; const std::string& get_predefined_name(CephContext *cct) const override; int init(const DoutPrefixProvider *dpp, CephContext *_cct, RGWSI_SysObj *_sysobj_svc, optional_yield y, bool setup_obj = true, bool old_format = false); using RGWSystemMetaObj::init; int read_default_id(const DoutPrefixProvider *dpp, std::string& default_id, optional_yield y, bool old_format = false) override; int set_as_default(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = false) override; int create_default(const DoutPrefixProvider *dpp, optional_yield y, bool old_format = false); int create(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = true) override; int fix_pool_names(const DoutPrefixProvider *dpp, optional_yield y); const std::string& get_compression_type(const rgw_placement_rule& placement_rule) const; void encode(bufferlist& bl) const override { ENCODE_START(14, 1, bl); encode(domain_root, bl); encode(control_pool, bl); encode(gc_pool, bl); encode(log_pool, bl); encode(intent_log_pool, bl); encode(usage_log_pool, bl); encode(user_keys_pool, bl); encode(user_email_pool, bl); encode(user_swift_pool, bl); encode(user_uid_pool, bl); RGWSystemMetaObj::encode(bl); encode(system_key, bl); encode(placement_pools, bl); rgw_pool unused_metadata_heap; encode(unused_metadata_heap, bl); encode(realm_id, bl); encode(lc_pool, bl); std::map<std::string, std::string, ltstr_nocase> old_tier_config; encode(old_tier_config, bl); encode(roles_pool, bl); encode(reshard_pool, bl); encode(otp_pool, bl); encode(tier_config, bl); encode(oidc_pool, bl); encode(notif_pool, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) override { DECODE_START(14, bl); decode(domain_root, bl); decode(control_pool, bl); decode(gc_pool, bl); decode(log_pool, bl); decode(intent_log_pool, bl); decode(usage_log_pool, bl); decode(user_keys_pool, bl); decode(user_email_pool, bl); decode(user_swift_pool, bl); decode(user_uid_pool, bl); if (struct_v >= 6) { RGWSystemMetaObj::decode(bl); } else if (struct_v >= 2) { decode(name, bl); id = name; } if (struct_v >= 3) decode(system_key, bl); if (struct_v >= 4) decode(placement_pools, bl); if (struct_v >= 5) { rgw_pool unused_metadata_heap; decode(unused_metadata_heap, bl); } if (struct_v >= 6) { decode(realm_id, bl); } if (struct_v >= 7) { decode(lc_pool, bl); } else { lc_pool = log_pool.name + ":lc"; } std::map<std::string, std::string, ltstr_nocase> old_tier_config; if (struct_v >= 8) { decode(old_tier_config, bl); } if (struct_v >= 9) { decode(roles_pool, bl); } else { roles_pool = name + ".rgw.meta:roles"; } if (struct_v >= 10) { decode(reshard_pool, bl); } else { reshard_pool = log_pool.name + ":reshard"; } if (struct_v >= 11) { ::decode(otp_pool, bl); } else { otp_pool = name + ".rgw.otp"; } if (struct_v >= 12) { ::decode(tier_config, bl); } else { for (auto& kv : old_tier_config) { tier_config.set(kv.first, kv.second); } } if (struct_v >= 13) { ::decode(oidc_pool, bl); } else { oidc_pool = name + ".rgw.meta:oidc"; } if (struct_v >= 14) { decode(notif_pool, bl); } else { notif_pool = log_pool.name + ":notif"; } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWZoneParams*>& o); bool get_placement(const std::string& placement_id, RGWZonePlacementInfo *placement) const { auto iter = placement_pools.find(placement_id); if (iter == placement_pools.end()) { return false; } *placement = iter->second; return true; } /* * return data pool of the head object */ bool get_head_data_pool(const rgw_placement_rule& placement_rule, const rgw_obj& obj, rgw_pool* pool) const { const rgw_data_placement_target& explicit_placement = obj.bucket.explicit_placement; if (!explicit_placement.data_pool.empty()) { if (!obj.in_extra_data) { *pool = explicit_placement.data_pool; } else { *pool = explicit_placement.get_data_extra_pool(); } return true; } if (placement_rule.empty()) { return false; } auto iter = placement_pools.find(placement_rule.name); if (iter == placement_pools.end()) { return false; } if (!obj.in_extra_data) { *pool = iter->second.get_data_pool(placement_rule.storage_class); } else { *pool = iter->second.get_data_extra_pool(); } return true; } bool valid_placement(const rgw_placement_rule& rule) const { auto iter = placement_pools.find(rule.name); if (iter == placement_pools.end()) { return false; } return iter->second.storage_class_exists(rule.storage_class); } }; WRITE_CLASS_ENCODER(RGWZoneParams) struct RGWZoneGroup : public RGWSystemMetaObj { std::string api_name; std::list<std::string> endpoints; bool is_master = false; rgw_zone_id master_zone; std::map<rgw_zone_id, RGWZone> zones; std::map<std::string, RGWZoneGroupPlacementTarget> placement_targets; rgw_placement_rule default_placement; std::list<std::string> hostnames; std::list<std::string> hostnames_s3website; // TODO: Maybe convert hostnames to a map<std::string,std::list<std::string>> for // endpoint_type->hostnames /* 20:05 < _robbat21irssi> maybe I do someting like: if (hostname_map.empty()) { populate all map keys from hostnames; }; 20:05 < _robbat21irssi> but that's a later compatability migration planning bit 20:06 < yehudasa> more like if (!hostnames.empty()) { 20:06 < yehudasa> for (std::list<std::string>::iterator iter = hostnames.begin(); iter != hostnames.end(); ++iter) { 20:06 < yehudasa> hostname_map["s3"].append(iter->second); 20:07 < yehudasa> hostname_map["s3website"].append(iter->second); 20:07 < yehudasa> s/append/push_back/g 20:08 < _robbat21irssi> inner loop over APIs 20:08 < yehudasa> yeah, probably 20:08 < _robbat21irssi> s3, s3website, swift, swith_auth, swift_website */ std::map<std::string, std::list<std::string> > api_hostname_map; std::map<std::string, std::list<std::string> > api_endpoints_map; std::string realm_id; rgw_sync_policy_info sync_policy; rgw::zone_features::set enabled_features; RGWZoneGroup(): is_master(false){} RGWZoneGroup(const std::string &id, const std::string &name):RGWSystemMetaObj(id, name) {} explicit RGWZoneGroup(const std::string &_name):RGWSystemMetaObj(_name) {} RGWZoneGroup(const std::string &_name, bool _is_master, CephContext *cct, RGWSI_SysObj* sysobj_svc, const std::string& _realm_id, const std::list<std::string>& _endpoints) : RGWSystemMetaObj(_name, cct , sysobj_svc), endpoints(_endpoints), is_master(_is_master), realm_id(_realm_id) {} virtual ~RGWZoneGroup(); bool is_master_zonegroup() const { return is_master;} void update_master(const DoutPrefixProvider *dpp, bool _is_master, optional_yield y) { is_master = _is_master; post_process_params(dpp, y); } void post_process_params(const DoutPrefixProvider *dpp, optional_yield y); void encode(bufferlist& bl) const override { ENCODE_START(6, 1, bl); encode(name, bl); encode(api_name, bl); encode(is_master, bl); encode(endpoints, bl); encode(master_zone, bl); encode(zones, bl); encode(placement_targets, bl); encode(default_placement, bl); encode(hostnames, bl); encode(hostnames_s3website, bl); RGWSystemMetaObj::encode(bl); encode(realm_id, bl); encode(sync_policy, bl); encode(enabled_features, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) override { DECODE_START(6, bl); decode(name, bl); decode(api_name, bl); decode(is_master, bl); decode(endpoints, bl); decode(master_zone, bl); decode(zones, bl); decode(placement_targets, bl); decode(default_placement, bl); if (struct_v >= 2) { decode(hostnames, bl); } if (struct_v >= 3) { decode(hostnames_s3website, bl); } if (struct_v >= 4) { RGWSystemMetaObj::decode(bl); decode(realm_id, bl); } else { id = name; } if (struct_v >= 5) { decode(sync_policy, bl); } if (struct_v >= 6) { decode(enabled_features, bl); } DECODE_FINISH(bl); } int read_default_id(const DoutPrefixProvider *dpp, std::string& default_id, optional_yield y, bool old_format = false) override; int set_as_default(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = false) override; int create_default(const DoutPrefixProvider *dpp, optional_yield y, bool old_format = false); int equals(const std::string& other_zonegroup) const; int add_zone(const DoutPrefixProvider *dpp, const RGWZoneParams& zone_params, bool *is_master, bool *read_only, const std::list<std::string>& endpoints, const std::string *ptier_type, bool *psync_from_all, std::list<std::string>& sync_from, std::list<std::string>& sync_from_rm, std::string *predirect_zone, std::optional<int> bucket_index_max_shards, RGWSyncModulesManager *sync_mgr, const rgw::zone_features::set& enable_features, const rgw::zone_features::set& disable_features, optional_yield y); int remove_zone(const DoutPrefixProvider *dpp, const std::string& zone_id, optional_yield y); int rename_zone(const DoutPrefixProvider *dpp, const RGWZoneParams& zone_params, optional_yield y); rgw_pool get_pool(CephContext *cct) const override; const std::string get_default_oid(bool old_region_format = false) const override; const std::string& get_info_oid_prefix(bool old_region_format = false) const override; const std::string& get_names_oid_prefix() const override; std::string get_predefined_id(CephContext *cct) const override; const std::string& get_predefined_name(CephContext *cct) const override; void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWZoneGroup*>& o); bool supports(std::string_view feature) const { return enabled_features.contains(feature); } }; WRITE_CLASS_ENCODER(RGWZoneGroup) struct RGWPeriodMap { std::string id; std::map<std::string, RGWZoneGroup> zonegroups; std::map<std::string, RGWZoneGroup> zonegroups_by_api; std::map<std::string, uint32_t> short_zone_ids; std::string master_zonegroup; void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& bl); int update(const RGWZoneGroup& zonegroup, CephContext *cct); void dump(Formatter *f) const; void decode_json(JSONObj *obj); void reset() { zonegroups.clear(); zonegroups_by_api.clear(); master_zonegroup.clear(); } uint32_t get_zone_short_id(const std::string& zone_id) const; bool find_zone_by_id(const rgw_zone_id& zone_id, RGWZoneGroup *zonegroup, RGWZone *zone) const; bool find_zone_by_name(const std::string& zone_id, RGWZoneGroup *zonegroup, RGWZone *zone) const; }; WRITE_CLASS_ENCODER(RGWPeriodMap) struct RGWPeriodConfig { RGWQuota quota; RGWRateLimitInfo user_ratelimit; RGWRateLimitInfo bucket_ratelimit; // rate limit unauthenticated user RGWRateLimitInfo anon_ratelimit; void encode(bufferlist& bl) const { ENCODE_START(2, 1, bl); encode(quota.bucket_quota, bl); encode(quota.user_quota, bl); encode(bucket_ratelimit, bl); encode(user_ratelimit, bl); encode(anon_ratelimit, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(2, bl); decode(quota.bucket_quota, bl); decode(quota.user_quota, bl); if (struct_v >= 2) { decode(bucket_ratelimit, bl); decode(user_ratelimit, bl); decode(anon_ratelimit, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); // the period config must be stored in a local object outside of the period, // so that it can be used in a default configuration where no realm/period // exists int read(const DoutPrefixProvider *dpp, RGWSI_SysObj *sysobj_svc, const std::string& realm_id, optional_yield y); int write(const DoutPrefixProvider *dpp, RGWSI_SysObj *sysobj_svc, const std::string& realm_id, optional_yield y); static std::string get_oid(const std::string& realm_id); static rgw_pool get_pool(CephContext *cct); }; WRITE_CLASS_ENCODER(RGWPeriodConfig) class RGWRealm; class RGWPeriod; class RGWRealm : public RGWSystemMetaObj { public: std::string current_period; epoch_t epoch{0}; //< realm epoch, incremented for each new period int create_control(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y); int delete_control(const DoutPrefixProvider *dpp, optional_yield y); public: RGWRealm() {} RGWRealm(const std::string& _id, const std::string& _name = "") : RGWSystemMetaObj(_id, _name) {} RGWRealm(CephContext *_cct, RGWSI_SysObj *_sysobj_svc): RGWSystemMetaObj(_cct, _sysobj_svc) {} RGWRealm(const std::string& _name, CephContext *_cct, RGWSI_SysObj *_sysobj_svc): RGWSystemMetaObj(_name, _cct, _sysobj_svc){} virtual ~RGWRealm() override; void encode(bufferlist& bl) const override { ENCODE_START(1, 1, bl); RGWSystemMetaObj::encode(bl); encode(current_period, bl); encode(epoch, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) override { DECODE_START(1, bl); RGWSystemMetaObj::decode(bl); decode(current_period, bl); decode(epoch, bl); DECODE_FINISH(bl); } int create(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = true) override; int delete_obj(const DoutPrefixProvider *dpp, optional_yield y); rgw_pool get_pool(CephContext *cct) const override; const std::string get_default_oid(bool old_format = false) const override; const std::string& get_names_oid_prefix() const override; const std::string& get_info_oid_prefix(bool old_format = false) const override; std::string get_predefined_id(CephContext *cct) const override; const std::string& get_predefined_name(CephContext *cct) const override; using RGWSystemMetaObj::read_id; // expose as public for radosgw-admin void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWRealm*>& o); const std::string& get_current_period() const { return current_period; } int set_current_period(const DoutPrefixProvider *dpp, RGWPeriod& period, optional_yield y); void clear_current_period_and_epoch() { current_period.clear(); epoch = 0; } epoch_t get_epoch() const { return epoch; } std::string get_control_oid() const; /// send a notify on the realm control object int notify_zone(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y); /// notify the zone of a new period int notify_new_period(const DoutPrefixProvider *dpp, const RGWPeriod& period, optional_yield y); int find_zone(const DoutPrefixProvider *dpp, const rgw_zone_id& zid, RGWPeriod *pperiod, RGWZoneGroup *pzonegroup, bool *pfound, optional_yield y) const; }; WRITE_CLASS_ENCODER(RGWRealm) struct RGWPeriodLatestEpochInfo { epoch_t epoch = 0; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(epoch, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(epoch, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWPeriodLatestEpochInfo*>& o); }; WRITE_CLASS_ENCODER(RGWPeriodLatestEpochInfo) /* * The RGWPeriod object contains the entire configuration of a * RGWRealm, including its RGWZoneGroups and RGWZones. Consistency of * this configuration is maintained across all zones by passing around * the RGWPeriod object in its JSON representation. * * If a new configuration changes which zone is the metadata master * zone (i.e., master zone of the master zonegroup), then a new * RGWPeriod::id (a uuid) is generated, its RGWPeriod::realm_epoch is * incremented, and the RGWRealm object is updated to reflect that new * current_period id and epoch. If the configuration changes BUT which * zone is the metadata master does NOT change, then only the * RGWPeriod::epoch is incremented (and the RGWPeriod::id remains the * same). * * When a new RGWPeriod is created with a new RGWPeriod::id (uuid), it * is linked back to its predecessor RGWPeriod through the * RGWPeriod::predecessor_uuid field, thus creating a "linked * list"-like structure of RGWPeriods back to the cluster's creation. */ class RGWPeriod { public: std::string id; //< a uuid epoch_t epoch{0}; std::string predecessor_uuid; std::vector<std::string> sync_status; RGWPeriodMap period_map; RGWPeriodConfig period_config; std::string master_zonegroup; rgw_zone_id master_zone; std::string realm_id; std::string realm_name; epoch_t realm_epoch{1}; //< realm epoch when period was made current CephContext *cct{nullptr}; RGWSI_SysObj *sysobj_svc{nullptr}; int read_info(const DoutPrefixProvider *dpp, optional_yield y); int read_latest_epoch(const DoutPrefixProvider *dpp, RGWPeriodLatestEpochInfo& epoch_info, optional_yield y, RGWObjVersionTracker *objv = nullptr); int use_latest_epoch(const DoutPrefixProvider *dpp, optional_yield y); int use_current_period(); const std::string get_period_oid() const; const std::string get_period_oid_prefix() const; // gather the metadata sync status for each shard; only for use on master zone int update_sync_status(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const RGWPeriod &current_period, std::ostream& error_stream, bool force_if_stale); public: RGWPeriod() {} explicit RGWPeriod(const std::string& period_id, epoch_t _epoch = 0) : id(period_id), epoch(_epoch) {} const std::string& get_id() const { return id; } epoch_t get_epoch() const { return epoch; } epoch_t get_realm_epoch() const { return realm_epoch; } const std::string& get_predecessor() const { return predecessor_uuid; } const rgw_zone_id& get_master_zone() const { return master_zone; } const std::string& get_master_zonegroup() const { return master_zonegroup; } const std::string& get_realm() const { return realm_id; } const std::string& get_realm_name() const { return realm_name; } const RGWPeriodMap& get_map() const { return period_map; } RGWPeriodConfig& get_config() { return period_config; } const RGWPeriodConfig& get_config() const { return period_config; } const std::vector<std::string>& get_sync_status() const { return sync_status; } rgw_pool get_pool(CephContext *cct) const; const std::string& get_latest_epoch_oid() const; const std::string& get_info_oid_prefix() const; void set_user_quota(RGWQuotaInfo& user_quota) { period_config.quota.user_quota = user_quota; } void set_bucket_quota(RGWQuotaInfo& bucket_quota) { period_config.quota.bucket_quota = bucket_quota; } void set_id(const std::string& _id) { this->id = _id; period_map.id = _id; } void set_epoch(epoch_t epoch) { this->epoch = epoch; } void set_realm_epoch(epoch_t epoch) { realm_epoch = epoch; } void set_predecessor(const std::string& predecessor) { predecessor_uuid = predecessor; } void set_realm_id(const std::string& _realm_id) { realm_id = _realm_id; } int reflect(const DoutPrefixProvider *dpp, optional_yield y); int get_zonegroup(RGWZoneGroup& zonegroup, const std::string& zonegroup_id) const; bool is_single_zonegroup() const { return (period_map.zonegroups.size() <= 1); } /* returns true if there are several zone groups with a least one zone */ bool is_multi_zonegroups_with_zones() const { int count = 0; for (const auto& zg: period_map.zonegroups) { if (zg.second.zones.size() > 0) { if (count++ > 0) { return true; } } } return false; } bool find_zone(const DoutPrefixProvider *dpp, const rgw_zone_id& zid, RGWZoneGroup *pzonegroup, optional_yield y) const; int get_latest_epoch(const DoutPrefixProvider *dpp, epoch_t& epoch, optional_yield y); int set_latest_epoch(const DoutPrefixProvider *dpp, optional_yield y, epoch_t epoch, bool exclusive = false, RGWObjVersionTracker *objv = nullptr); // update latest_epoch if the given epoch is higher, else return -EEXIST int update_latest_epoch(const DoutPrefixProvider *dpp, epoch_t epoch, optional_yield y); int init(const DoutPrefixProvider *dpp, CephContext *_cct, RGWSI_SysObj *_sysobj_svc, const std::string &period_realm_id, optional_yield y, const std::string &period_realm_name = "", bool setup_obj = true); int init(const DoutPrefixProvider *dpp, CephContext *_cct, RGWSI_SysObj *_sysobj_svc, optional_yield y, bool setup_obj = true); int create(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive = true); int delete_obj(const DoutPrefixProvider *dpp, optional_yield y); int store_info(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y); int add_zonegroup(const DoutPrefixProvider *dpp, const RGWZoneGroup& zonegroup, optional_yield y); void fork(); int update(const DoutPrefixProvider *dpp, optional_yield y); // commit a staging period; only for use on master zone int commit(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, RGWRealm& realm, const RGWPeriod &current_period, std::ostream& error_stream, optional_yield y, bool force_if_stale = false); void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(epoch, bl); encode(realm_epoch, bl); encode(predecessor_uuid, bl); encode(sync_status, bl); encode(period_map, bl); encode(master_zone, bl); encode(master_zonegroup, bl); encode(period_config, bl); encode(realm_id, bl); encode(realm_name, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); decode(epoch, bl); decode(realm_epoch, bl); decode(predecessor_uuid, bl); decode(sync_status, bl); decode(period_map, bl); decode(master_zone, bl); decode(master_zonegroup, bl); decode(period_config, bl); decode(realm_id, bl); decode(realm_name, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWPeriod*>& o); static std::string get_staging_id(const std::string& realm_id) { return realm_id + ":staging"; } }; WRITE_CLASS_ENCODER(RGWPeriod) namespace rgw { /// Look up a realm by its id. If no id is given, look it up by name. /// If no name is given, fall back to the cluster's default realm. int read_realm(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, std::string_view realm_id, std::string_view realm_name, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer = nullptr); /// Create a realm and its initial period. If the info.id is empty, a /// random uuid will be generated. int create_realm(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer = nullptr); /// Set the given realm as the cluster's default realm. int set_default_realm(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWRealm& info, bool exclusive = false); /// Update the current_period of an existing realm. int realm_set_current_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, sal::RealmWriter& writer, RGWRealm& realm, const RGWPeriod& period); /// Overwrite the local zonegroup and period config objects with the new /// configuration contained in the given period. int reflect_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWPeriod& info); /// Return the staging period id for the given realm. std::string get_staging_period_id(std::string_view realm_id); /// Convert the given period into a separate staging period, where /// radosgw-admin can make changes to it without effecting the running /// configuration. void fork_period(const DoutPrefixProvider* dpp, RGWPeriod& info); /// Read all zonegroups in the period's realm and add them to the period. int update_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, RGWPeriod& info); /// Validates the given 'staging' period and tries to commit it as the /// realm's new current period. int commit_period(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, sal::Driver* driver, RGWRealm& realm, sal::RealmWriter& realm_writer, const RGWPeriod& current_period, RGWPeriod& info, std::ostream& error_stream, bool force_if_stale); /// Look up a zonegroup by its id. If no id is given, look it up by name. /// If no name is given, fall back to the cluster's default zonegroup. int read_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, std::string_view zonegroup_id, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer = nullptr); /// Initialize and create the given zonegroup. If the given info.id is empty, /// a random uuid will be generated. May fail with -EEXIST. int create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, RGWZoneGroup& info); /// Set the given zonegroup as its realm's default zonegroup. int set_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneGroup& info, bool exclusive = false); /// Add a zone to the zonegroup, or update an existing zone entry. int add_zone_to_group(const DoutPrefixProvider* dpp, RGWZoneGroup& zonegroup, const RGWZoneParams& zone_params, const bool *pis_master, const bool *pread_only, const std::list<std::string>& endpoints, const std::string *ptier_type, const bool *psync_from_all, const std::list<std::string>& sync_from, const std::list<std::string>& sync_from_rm, const std::string *predirect_zone, std::optional<int> bucket_index_max_shards, const rgw::zone_features::set& enable_features, const rgw::zone_features::set& disable_features); /// Remove a zone by id from its zonegroup, promoting a new master zone if /// necessary. int remove_zone_from_group(const DoutPrefixProvider* dpp, RGWZoneGroup& info, const rgw_zone_id& zone_id); /// Look up a zone by its id. If no id is given, look it up by name. If no name /// is given, fall back to the realm's default zone. int read_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, std::string_view zone_id, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer = nullptr); /// Initialize and create a new zone. If the given info.id is empty, a random /// uuid will be generated. Pool names are initialized with the zone name as a /// prefix. If any pool names conflict with existing zones, a random suffix is /// added. int create_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, bool exclusive, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer = nullptr); /// Initialize the zone's pool names using the zone name as a prefix. If a pool /// name conflicts with an existing zone's pool, add a unique suffix. int init_zone_pool_names(const DoutPrefixProvider *dpp, optional_yield y, const std::set<rgw_pool>& pools, RGWZoneParams& info); /// Set the given zone as its realm's default zone. int set_default_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneParams& info, bool exclusive = false); /// Delete an existing zone and remove it from any zonegroups that contain it. int delete_zone(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWZoneParams& info, sal::ZoneWriter& writer); /// Global state about the site configuration. Initialized once during /// startup and may be reinitialized by RGWRealmReloader, but is otherwise /// immutable at runtime. class SiteConfig { public: /// Return the local zone params. const RGWZoneParams& get_zone_params() const { return zone_params; } /// Return the current realm configuration, if a realm is present. const std::optional<RGWRealm>& get_realm() const { return realm; } /// Return the current period configuration, if a period is present. const std::optional<RGWPeriod>& get_period() const { return period; } /// Return the zonegroup configuration. const RGWZoneGroup& get_zonegroup() const { return *zonegroup; } /// Return the public zone configuration. const RGWZone& get_zone() const { return *zone; } /// Load or reload the multisite configuration from storage. This is not /// thread-safe, so requires careful coordination with the RGWRealmReloader. int load(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore); private: int load_period_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const RGWRealm& realm, const rgw_zone_id& zone_id); int load_local_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, sal::ConfigStore* cfgstore, const rgw_zone_id& zone_id); RGWZoneParams zone_params; std::optional<RGWRealm> realm; std::optional<RGWPeriod> period; std::optional<RGWZoneGroup> local_zonegroup; const RGWZoneGroup* zonegroup = nullptr; const RGWZone* zone = nullptr; }; } // namespace rgw
36,835
36.511202
141
h
null
ceph-main/src/rgw/driver/rados/sync_fairness.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 <mutex> #include <random> #include <vector> #include <boost/container/flat_map.hpp> #include "include/encoding.h" #include "include/rados/librados.hpp" #include "rgw_sal_rados.h" #include "rgw_cr_rados.h" #include "sync_fairness.h" #include <boost/asio/yield.hpp> #define dout_subsys ceph_subsys_rgw namespace rgw::sync_fairness { using bid_value = uint16_t; using bid_vector = std::vector<bid_value>; // bid per replication log shard using notifier_id = uint64_t; using bidder_map = boost::container::flat_map<notifier_id, bid_vector>; struct BidRequest { bid_vector bids; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(bids, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(bids, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(BidRequest); struct BidResponse { bid_vector bids; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(bids, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(bids, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(BidResponse); static void encode_notify_request(const bid_vector& bids, bufferlist& bl) { BidRequest request; request.bids = bids; // copy the vector encode(request, bl); } static int apply_notify_responses(const bufferlist& bl, bidder_map& bidders) { bc::flat_map<std::pair<uint64_t, uint64_t>, bufferlist> replies; std::vector<std::pair<uint64_t, uint64_t>> timeouts; try { // decode notify responses auto p = bl.cbegin(); using ceph::decode; decode(replies, p); decode(timeouts, p); // add peers that replied for (const auto& peer : replies) { auto q = peer.second.cbegin(); BidResponse response; decode(response, q); uint64_t peer_id = peer.first.first; bidders[peer_id] = std::move(response.bids); } // remove peers that timed out for (const auto& peer : timeouts) { uint64_t peer_id = peer.first; bidders.erase(peer_id); } } catch (const buffer::error& e) { return -EIO; } return 0; } // server interface to handle bid notifications from peers struct Server { virtual ~Server() = default; virtual void on_peer_bid(uint64_t peer_id, bid_vector peer_bids, bid_vector& my_bids) = 0; }; // rados watcher for sync fairness notifications class Watcher : public librados::WatchCtx2 { const DoutPrefixProvider* dpp; sal::RadosStore* const store; rgw_raw_obj obj; Server* server; rgw_rados_ref ref; uint64_t handle = 0; public: Watcher(const DoutPrefixProvider* dpp, sal::RadosStore* store, const rgw_raw_obj& obj, Server* server) : dpp(dpp), store(store), obj(obj), server(server) {} ~Watcher() { stop(); } int start() { int r = store->getRados()->get_raw_obj_ref(dpp, obj, &ref); if (r < 0) { return r; } // register a watch on the control object r = ref.pool.ioctx().watch2(ref.obj.oid, &handle, this); if (r == -ENOENT) { constexpr bool exclusive = true; r = ref.pool.ioctx().create(ref.obj.oid, exclusive); if (r == -EEXIST || r == 0) { r = ref.pool.ioctx().watch2(ref.obj.oid, &handle, this); } } if (r < 0) { ldpp_dout(dpp, -1) << "Failed to watch " << ref.obj << " with " << cpp_strerror(-r) << dendl; ref.pool.ioctx().close(); return r; } ldpp_dout(dpp, 10) << "Watching " << ref.obj.oid << dendl; return 0; } int restart() { int r = ref.pool.ioctx().unwatch2(handle); if (r < 0) { ldpp_dout(dpp, -1) << "Failed to unwatch on " << ref.obj << " with " << cpp_strerror(-r) << dendl; } r = ref.pool.ioctx().watch2(ref.obj.oid, &handle, this); if (r < 0) { ldpp_dout(dpp, -1) << "Failed to restart watch on " << ref.obj << " with " << cpp_strerror(-r) << dendl; ref.pool.ioctx().close(); } return r; } void stop() { if (handle) { ref.pool.ioctx().unwatch2(handle); ref.pool.ioctx().close(); } } // respond to bid notifications void handle_notify(uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) { if (cookie != handle) { return; } BidRequest request; try { auto p = bl.cbegin(); decode(request, p); } catch (const buffer::error& e) { ldpp_dout(dpp, -1) << "Failed to decode notification: " << e.what() << dendl; return; } BidResponse response; server->on_peer_bid(notifier_id, std::move(request.bids), response.bids); bufferlist reply; encode(response, reply); ref.pool.ioctx().notify_ack(ref.obj.oid, notify_id, cookie, reply); } // reestablish the watch if it gets disconnected void handle_error(uint64_t cookie, int err) { if (cookie != handle) { return; } if (err == -ENOTCONN) { ldpp_dout(dpp, 4) << "Disconnected watch on " << ref.obj << dendl; restart(); } } }; // Watcher class RadosBidManager; // RGWRadosNotifyCR wrapper coroutine class NotifyCR : public RGWCoroutine { rgw::sal::RadosStore* store; RadosBidManager* mgr; rgw_raw_obj obj; bufferlist request; bufferlist response; public: NotifyCR(rgw::sal::RadosStore* store, RadosBidManager* mgr, const rgw_raw_obj& obj, const bid_vector& my_bids) : RGWCoroutine(store->ctx()), store(store), mgr(mgr), obj(obj) { encode_notify_request(my_bids, request); } int operate(const DoutPrefixProvider* dpp) override; }; class RadosBidManager : public BidManager, public Server, public DoutPrefix { sal::RadosStore* store; rgw_raw_obj obj; Watcher watcher; std::mutex mutex; bid_vector my_bids; bidder_map all_bids; public: RadosBidManager(sal::RadosStore* store, const rgw_raw_obj& watch_obj, std::size_t num_shards) : DoutPrefix(store->ctx(), dout_subsys, "sync fairness: "), store(store), obj(watch_obj), watcher(this, store, watch_obj, this) { // fill my_bids with random values std::random_device rd; std::default_random_engine rng{rd()}; my_bids.resize(num_shards); for(bid_value i = 0; i < num_shards; ++i) { my_bids[i] = i; } std::shuffle(my_bids.begin(), my_bids.end(), rng); } int start() override { return watcher.start(); } void on_peer_bid(uint64_t peer_id, bid_vector peer_bids, bid_vector& my_bids) override { ldpp_dout(this, 10) << "received bids from peer " << peer_id << dendl; auto lock = std::scoped_lock{mutex}; all_bids[peer_id] = std::move(peer_bids); my_bids = this->my_bids; } bool is_highest_bidder(std::size_t index) { auto lock = std::scoped_lock{mutex}; const bid_value my_bid = my_bids.at(index); // may throw for (const auto& peer_bids : all_bids) { const bid_value peer_bid = peer_bids.second.at(index); // may throw if (peer_bid > my_bid) { return false; } } return true; } RGWCoroutine* notify_cr() { auto lock = std::scoped_lock{mutex}; return new NotifyCR(store, this, obj, my_bids); } void notify_response(const bufferlist& bl) { ldpp_dout(this, 10) << "received notify response from peers" << dendl; auto lock = std::scoped_lock{mutex}; // clear existing bids in case any peers went away. note that this may // remove newer bids from peer notifications that raced with ours all_bids.clear(); apply_notify_responses(bl, all_bids); } }; int NotifyCR::operate(const DoutPrefixProvider* dpp) { static constexpr uint64_t timeout_ms = 15'000; reenter(this) { yield call(new RGWRadosNotifyCR(store, obj, request, timeout_ms, &response)); if (retcode < 0) { return set_cr_error(retcode); } mgr->notify_response(response); return set_cr_done(); } return 0; } auto create_rados_bid_manager(sal::RadosStore* store, const rgw_raw_obj& watch_obj, std::size_t num_shards) -> std::unique_ptr<BidManager> { return std::make_unique<RadosBidManager>(store, watch_obj, num_shards); } } // namespace rgw::sync_fairness
8,772
23.923295
83
cc
null
ceph-main/src/rgw/driver/rados/sync_fairness.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include <memory> namespace rgw::sal { class RadosStore; } struct rgw_raw_obj; class RGWCoroutine; /// watch/notify protocol to coordinate the sharing of sync locks /// /// each gateway generates a set of random bids, and broadcasts them regularly /// to other active gateways. in response, the peer gateways send their own set /// of bids /// /// sync will only lock and process log shards where it holds the highest bid namespace rgw::sync_fairness { class BidManager { public: virtual ~BidManager() {} /// establish a watch, creating the control object if necessary virtual int start() = 0; /// returns true if we're the highest bidder on the given shard index virtual bool is_highest_bidder(std::size_t index) = 0; /// return a coroutine that broadcasts our current bids and records the /// bids from other peers that respond virtual RGWCoroutine* notify_cr() = 0; }; // rados BidManager factory auto create_rados_bid_manager(sal::RadosStore* store, const rgw_raw_obj& watch_obj, std::size_t num_shards) -> std::unique_ptr<BidManager>; } // namespace rgw::sync_fairness
1,584
28.351852
79
h
null
ceph-main/src/rgw/driver/rados/config/impl.cc
// 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 "impl.h" #include "common/async/yield_context.h" #include "common/errno.h" #include "rgw_string.h" #include "rgw_zone.h" namespace rgw::rados { // default pool names constexpr std::string_view default_zone_root_pool = "rgw.root"; constexpr std::string_view default_zonegroup_root_pool = "rgw.root"; constexpr std::string_view default_realm_root_pool = "rgw.root"; constexpr std::string_view default_period_root_pool = "rgw.root"; static rgw_pool default_pool(std::string_view name, std::string_view default_name) { return std::string{name_or_default(name, default_name)}; } ConfigImpl::ConfigImpl(const ceph::common::ConfigProxy& conf) : realm_pool(default_pool(conf->rgw_realm_root_pool, default_realm_root_pool)), period_pool(default_pool(conf->rgw_period_root_pool, default_period_root_pool)), zonegroup_pool(default_pool(conf->rgw_zonegroup_root_pool, default_zonegroup_root_pool)), zone_pool(default_pool(conf->rgw_zone_root_pool, default_zone_root_pool)) { } int ConfigImpl::read(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, bufferlist& bl, RGWObjVersionTracker* objv) { librados::IoCtx ioctx; int r = rgw_init_ioctx(dpp, &rados, pool, ioctx, true, false); if (r < 0) { return r; } librados::ObjectReadOperation op; if (objv) { objv->prepare_op_for_read(&op); } op.read(0, 0, &bl, nullptr); return rgw_rados_operate(dpp, ioctx, oid, &op, nullptr, y); } int ConfigImpl::write(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, Create create, const bufferlist& bl, RGWObjVersionTracker* objv) { librados::IoCtx ioctx; int r = rgw_init_ioctx(dpp, &rados, pool, ioctx, true, false); if (r < 0) { return r; } librados::ObjectWriteOperation op; switch (create) { case Create::MustNotExist: op.create(true); break; case Create::MayExist: op.create(false); break; case Create::MustExist: op.assert_exists(); break; } if (objv) { objv->prepare_op_for_write(&op); } op.write_full(bl); r = rgw_rados_operate(dpp, ioctx, oid, &op, y); if (r >= 0 && objv) { objv->apply_write(); } return r; } int ConfigImpl::remove(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, RGWObjVersionTracker* objv) { librados::IoCtx ioctx; int r = rgw_init_ioctx(dpp, &rados, pool, ioctx, true, false); if (r < 0) { return r; } librados::ObjectWriteOperation op; if (objv) { objv->prepare_op_for_write(&op); } op.remove(); r = rgw_rados_operate(dpp, ioctx, oid, &op, y); if (r >= 0 && objv) { objv->apply_write(); } return r; } int ConfigImpl::notify(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, bufferlist& bl, uint64_t timeout_ms) { librados::IoCtx ioctx; int r = rgw_init_ioctx(dpp, &rados, pool, ioctx, true, false); if (r < 0) { return r; } return rgw_rados_notify(dpp, ioctx, oid, bl, timeout_ms, nullptr, y); } } // namespace rgw::rados
3,758
27.915385
71
cc
null
ceph-main/src/rgw/driver/rados/config/impl.h
// vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "include/rados/librados.hpp" #include "common/dout.h" #include "rgw_basic_types.h" #include "rgw_tools.h" #include "rgw_sal_config.h" namespace rgw::rados { // write options that control object creation enum class Create { MustNotExist, // fail with EEXIST if the object already exists MayExist, // create if the object didn't exist, overwrite if it did MustExist, // fail with ENOENT if the object doesn't exist }; struct ConfigImpl { librados::Rados rados; const rgw_pool realm_pool; const rgw_pool period_pool; const rgw_pool zonegroup_pool; const rgw_pool zone_pool; ConfigImpl(const ceph::common::ConfigProxy& conf); int read(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, bufferlist& bl, RGWObjVersionTracker* objv); template <typename T> int read(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, T& data, RGWObjVersionTracker* objv) { bufferlist bl; int r = read(dpp, y, pool, oid, bl, objv); if (r < 0) { return r; } try { auto p = bl.cbegin(); decode(data, p); } catch (const buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: failed to decode obj from " << pool << ":" << oid << dendl; return -EIO; } return 0; } int write(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, Create create, const bufferlist& bl, RGWObjVersionTracker* objv); template <typename T> int write(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, Create create, const T& data, RGWObjVersionTracker* objv) { bufferlist bl; encode(data, bl); return write(dpp, y, pool, oid, create, bl, objv); } int remove(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, RGWObjVersionTracker* objv); int list(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& marker, std::regular_invocable<std::string> auto filter, std::span<std::string> entries, sal::ListResult<std::string>& result) { librados::IoCtx ioctx; int r = rgw_init_ioctx(dpp, &rados, pool, ioctx, true, false); if (r < 0) { return r; } librados::ObjectCursor oc; if (!oc.from_str(marker)) { ldpp_dout(dpp, 10) << "failed to parse cursor: " << marker << dendl; return -EINVAL; } std::size_t count = 0; try { auto iter = ioctx.nobjects_begin(oc); const auto end = ioctx.nobjects_end(); for (; count < entries.size() && iter != end; ++iter) { std::string entry = filter(iter->get_oid()); if (!entry.empty()) { entries[count++] = std::move(entry); } } if (iter == end) { result.next.clear(); } else { result.next = iter.get_cursor().to_str(); } } catch (const std::exception& e) { ldpp_dout(dpp, 10) << "NObjectIterator exception " << e.what() << dendl; return -EIO; } result.entries = entries.first(count); return 0; } int notify(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, bufferlist& bl, uint64_t timeout_ms); }; inline std::string_view name_or_default(std::string_view name, std::string_view default_name) { if (!name.empty()) { return name; } return default_name; } } // namespace rgw::rados
4,066
28.05
78
h
null
ceph-main/src/rgw/driver/rados/config/period.cc
// 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 "common/dout.h" #include "common/errno.h" #include "rgw_zone.h" #include "driver/rados/config/store.h" #include "impl.h" namespace rgw::rados { // period oids constexpr std::string_view period_info_oid_prefix = "periods."; constexpr std::string_view period_latest_epoch_info_oid = ".latest_epoch"; constexpr std::string_view period_staging_suffix = ":staging"; static std::string period_oid(std::string_view period_id, uint32_t epoch) { // omit the epoch for the staging period if (period_id.ends_with(period_staging_suffix)) { return string_cat_reserve(period_info_oid_prefix, period_id); } return fmt::format("{}{}.{}", period_info_oid_prefix, period_id, epoch); } static std::string latest_epoch_oid(const ceph::common::ConfigProxy& conf, std::string_view period_id) { return string_cat_reserve( period_info_oid_prefix, period_id, name_or_default(conf->rgw_period_latest_epoch_info_oid, period_latest_epoch_info_oid)); } static int read_latest_epoch(const DoutPrefixProvider* dpp, optional_yield y, ConfigImpl* impl, std::string_view period_id, uint32_t& epoch, RGWObjVersionTracker* objv) { const auto& pool = impl->period_pool; const auto latest_oid = latest_epoch_oid(dpp->get_cct()->_conf, period_id); RGWPeriodLatestEpochInfo latest; int r = impl->read(dpp, y, pool, latest_oid, latest, objv); if (r >= 0) { epoch = latest.epoch; } return r; } static int write_latest_epoch(const DoutPrefixProvider* dpp, optional_yield y, ConfigImpl* impl, bool exclusive, std::string_view period_id, uint32_t epoch, RGWObjVersionTracker* objv) { const auto& pool = impl->period_pool; const auto latest_oid = latest_epoch_oid(dpp->get_cct()->_conf, period_id); const auto create = exclusive ? Create::MustNotExist : Create::MayExist; RGWPeriodLatestEpochInfo latest{epoch}; return impl->write(dpp, y, pool, latest_oid, create, latest, objv); } static int delete_latest_epoch(const DoutPrefixProvider* dpp, optional_yield y, ConfigImpl* impl, std::string_view period_id, RGWObjVersionTracker* objv) { const auto& pool = impl->period_pool; const auto latest_oid = latest_epoch_oid(dpp->get_cct()->_conf, period_id); return impl->remove(dpp, y, pool, latest_oid, objv); } static int update_latest_epoch(const DoutPrefixProvider* dpp, optional_yield y, ConfigImpl* impl, std::string_view period_id, uint32_t epoch) { static constexpr int MAX_RETRIES = 20; for (int i = 0; i < MAX_RETRIES; i++) { uint32_t existing_epoch = 0; RGWObjVersionTracker objv; bool exclusive = false; // read existing epoch int r = read_latest_epoch(dpp, y, impl, period_id, existing_epoch, &objv); if (r == -ENOENT) { // use an exclusive create to set the epoch atomically exclusive = true; objv.generate_new_write_ver(dpp->get_cct()); ldpp_dout(dpp, 20) << "creating initial latest_epoch=" << epoch << " for period=" << period_id << dendl; } else if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to read latest_epoch" << dendl; return r; } else if (epoch <= existing_epoch) { r = -EEXIST; // fail with EEXIST if epoch is not newer ldpp_dout(dpp, 10) << "found existing latest_epoch " << existing_epoch << " >= given epoch " << epoch << ", returning r=" << r << dendl; return r; } else { ldpp_dout(dpp, 20) << "updating latest_epoch from " << existing_epoch << " -> " << epoch << " on period=" << period_id << dendl; } r = write_latest_epoch(dpp, y, impl, exclusive, period_id, epoch, &objv); if (r == -EEXIST) { continue; // exclusive create raced with another update, retry } else if (r == -ECANCELED) { continue; // write raced with a conflicting version, retry } if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to write latest_epoch" << dendl; return r; } return 0; // return success } return -ECANCELED; // fail after max retries } int RadosConfigStore::create_period(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWPeriod& info) { if (info.get_id().empty()) { ldpp_dout(dpp, 0) << "period cannot have an empty id" << dendl; return -EINVAL; } if (info.get_epoch() == 0) { ldpp_dout(dpp, 0) << "period cannot have an empty epoch" << dendl; return -EINVAL; } const auto& pool = impl->period_pool; const auto info_oid = period_oid(info.get_id(), info.get_epoch()); const auto create = exclusive ? Create::MustNotExist : Create::MayExist; RGWObjVersionTracker objv; objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, info_oid, create, info, &objv); if (r < 0) { return r; } (void) update_latest_epoch(dpp, y, impl.get(), info.get_id(), info.get_epoch()); return 0; } int RadosConfigStore::read_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id, std::optional<uint32_t> epoch, RGWPeriod& info) { int r = 0; if (!epoch) { epoch = 0; r = read_latest_epoch(dpp, y, impl.get(), period_id, *epoch, nullptr); if (r < 0) { return r; } } const auto& pool = impl->period_pool; const auto info_oid = period_oid(period_id, *epoch); return impl->read(dpp, y, pool, info_oid, info, nullptr); } int RadosConfigStore::delete_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id) { const auto& pool = impl->period_pool; // read the latest_epoch uint32_t latest_epoch = 0; RGWObjVersionTracker latest_objv; int r = read_latest_epoch(dpp, y, impl.get(), period_id, latest_epoch, &latest_objv); if (r < 0 && r != -ENOENT) { // just delete epoch=0 on ENOENT ldpp_dout(dpp, 0) << "failed to read latest epoch for period " << period_id << ": " << cpp_strerror(r) << dendl; return r; } for (uint32_t epoch = 0; epoch <= latest_epoch; epoch++) { const auto info_oid = period_oid(period_id, epoch); r = impl->remove(dpp, y, pool, info_oid, nullptr); if (r < 0 && r != -ENOENT) { // ignore ENOENT ldpp_dout(dpp, 0) << "failed to delete period " << info_oid << ": " << cpp_strerror(r) << dendl; return r; } } return delete_latest_epoch(dpp, y, impl.get(), period_id, &latest_objv); } int RadosConfigStore::list_period_ids(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) { const auto& pool = impl->period_pool; constexpr auto prefix = [] (std::string oid) -> std::string { if (!oid.starts_with(period_info_oid_prefix)) { return {}; } if (!oid.ends_with(period_latest_epoch_info_oid)) { return {}; } // trim the prefix and suffix const std::size_t count = oid.size() - period_info_oid_prefix.size() - period_latest_epoch_info_oid.size(); return oid.substr(period_info_oid_prefix.size(), count); }; return impl->list(dpp, y, pool, marker, prefix, entries, result); } } // namespace rgw::rados
8,201
34.506494
82
cc
null
ceph-main/src/rgw/driver/rados/config/period_config.cc
// vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "rgw_zone.h" #include "driver/rados/config/store.h" #include "impl.h" namespace rgw::rados { // period config oids constexpr std::string_view period_config_prefix = "period_config."; constexpr std::string_view period_config_realm_default = "default"; std::string period_config_oid(std::string_view realm_id) { if (realm_id.empty()) { realm_id = period_config_realm_default; } return string_cat_reserve(period_config_prefix, realm_id); } int RadosConfigStore::read_period_config(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWPeriodConfig& info) { const auto& pool = impl->period_pool; const auto oid = period_config_oid(realm_id); return impl->read(dpp, y, pool, oid, info, nullptr); } int RadosConfigStore::write_period_config(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, const RGWPeriodConfig& info) { const auto& pool = impl->period_pool; const auto oid = period_config_oid(realm_id); const auto create = exclusive ? Create::MustNotExist : Create::MayExist; return impl->write(dpp, y, pool, oid, create, info, nullptr); } } // namespace rgw::rados
1,760
30.446429
75
cc
null
ceph-main/src/rgw/driver/rados/config/realm.cc
// 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 "common/dout.h" #include "common/errno.h" #include "rgw_realm_watcher.h" #include "rgw_zone.h" #include "driver/rados/config/store.h" #include "impl.h" namespace rgw::rados { // realm oids constexpr std::string_view realm_names_oid_prefix = "realms_names."; constexpr std::string_view realm_info_oid_prefix = "realms."; constexpr std::string_view realm_control_oid_suffix = ".control"; constexpr std::string_view default_realm_info_oid = "default.realm"; static std::string realm_info_oid(std::string_view realm_id) { return string_cat_reserve(realm_info_oid_prefix, realm_id); } static std::string realm_name_oid(std::string_view realm_id) { return string_cat_reserve(realm_names_oid_prefix, realm_id); } static std::string realm_control_oid(std::string_view realm_id) { return string_cat_reserve(realm_info_oid_prefix, realm_id, realm_control_oid_suffix); } static std::string default_realm_oid(const ceph::common::ConfigProxy& conf) { return std::string{name_or_default(conf->rgw_default_realm_info_oid, default_realm_info_oid)}; } int RadosConfigStore::write_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id) { const auto& pool = impl->realm_pool; const auto oid = default_realm_oid(dpp->get_cct()->_conf); const auto create = exclusive ? Create::MustNotExist : Create::MayExist; RGWDefaultSystemMetaObjInfo default_info; default_info.default_id = realm_id; return impl->write(dpp, y, pool, oid, create, default_info, nullptr); } int RadosConfigStore::read_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string& realm_id) { const auto& pool = impl->realm_pool; const auto oid = default_realm_oid(dpp->get_cct()->_conf); RGWDefaultSystemMetaObjInfo default_info; int r = impl->read(dpp, y, pool, oid, default_info, nullptr); if (r >= 0) { realm_id = default_info.default_id; } return r; } int RadosConfigStore::delete_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y) { const auto& pool = impl->realm_pool; const auto oid = default_realm_oid(dpp->get_cct()->_conf); return impl->remove(dpp, y, pool, oid, nullptr); } class RadosRealmWriter : public sal::RealmWriter { ConfigImpl* impl; RGWObjVersionTracker objv; std::string realm_id; std::string realm_name; public: RadosRealmWriter(ConfigImpl* impl, RGWObjVersionTracker objv, std::string_view realm_id, std::string_view realm_name) : impl(impl), objv(std::move(objv)), realm_id(realm_id), realm_name(realm_name) { } int write(const DoutPrefixProvider* dpp, optional_yield y, const RGWRealm& info) override { if (realm_id != info.get_id() || realm_name != info.get_name()) { return -EINVAL; // can't modify realm id or name directly } const auto& pool = impl->realm_pool; const auto info_oid = realm_info_oid(info.get_id()); return impl->write(dpp, y, pool, info_oid, Create::MustExist, info, &objv); } int rename(const DoutPrefixProvider* dpp, optional_yield y, RGWRealm& info, std::string_view new_name) override { if (realm_id != info.get_id() || realm_name != info.get_name()) { return -EINVAL; // can't modify realm id or name directly } if (new_name.empty()) { ldpp_dout(dpp, 0) << "realm cannot have an empty name" << dendl; return -EINVAL; } const auto& pool = impl->realm_pool; const auto name = RGWNameToId{info.get_id()}; const auto info_oid = realm_info_oid(info.get_id()); const auto old_oid = realm_name_oid(info.get_name()); const auto new_oid = realm_name_oid(new_name); // link the new name RGWObjVersionTracker new_objv; new_objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, new_oid, Create::MustNotExist, name, &new_objv); if (r < 0) { return r; } // write the info with updated name info.set_name(std::string{new_name}); r = impl->write(dpp, y, pool, info_oid, Create::MustExist, info, &objv); if (r < 0) { // on failure, unlink the new name (void) impl->remove(dpp, y, pool, new_oid, &new_objv); return r; } // unlink the old name (void) impl->remove(dpp, y, pool, old_oid, nullptr); realm_name = new_name; return 0; } int remove(const DoutPrefixProvider* dpp, optional_yield y) override { const auto& pool = impl->realm_pool; const auto info_oid = realm_info_oid(realm_id); int r = impl->remove(dpp, y, pool, info_oid, &objv); if (r < 0) { return r; } const auto name_oid = realm_name_oid(realm_name); (void) impl->remove(dpp, y, pool, name_oid, nullptr); const auto control_oid = realm_control_oid(realm_id); (void) impl->remove(dpp, y, pool, control_oid, nullptr); return 0; } }; // RadosRealmWriter int RadosConfigStore::create_realm(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) { if (info.get_id().empty()) { ldpp_dout(dpp, 0) << "realm cannot have an empty id" << dendl; return -EINVAL; } if (info.get_name().empty()) { ldpp_dout(dpp, 0) << "realm cannot have an empty name" << dendl; return -EINVAL; } const auto& pool = impl->realm_pool; const auto create = exclusive ? Create::MustNotExist : Create::MayExist; // write the realm info const auto info_oid = realm_info_oid(info.get_id()); RGWObjVersionTracker objv; objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, info_oid, create, info, &objv); if (r < 0) { return r; } // write the realm name const auto name_oid = realm_name_oid(info.get_name()); const auto name = RGWNameToId{info.get_id()}; RGWObjVersionTracker name_objv; name_objv.generate_new_write_ver(dpp->get_cct()); r = impl->write(dpp, y, pool, name_oid, create, name, &name_objv); if (r < 0) { (void) impl->remove(dpp, y, pool, info_oid, &objv); return r; } // create control object for watch/notify const auto control_oid = realm_control_oid(info.get_id()); bufferlist empty_bl; r = impl->write(dpp, y, pool, control_oid, Create::MayExist, empty_bl, nullptr); if (r < 0) { (void) impl->remove(dpp, y, pool, name_oid, &name_objv); (void) impl->remove(dpp, y, pool, info_oid, &objv); return r; } if (writer) { *writer = std::make_unique<RadosRealmWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_realm_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) { const auto& pool = impl->realm_pool; const auto info_oid = realm_info_oid(realm_id); RGWObjVersionTracker objv; int r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosRealmWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_realm_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) { const auto& pool = impl->realm_pool; // look up realm id by name RGWNameToId name; const auto name_oid = realm_name_oid(realm_name); int r = impl->read(dpp, y, pool, name_oid, name, nullptr); if (r < 0) { return r; } const auto info_oid = realm_info_oid(name.obj_id); RGWObjVersionTracker objv; r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosRealmWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_default_realm(const DoutPrefixProvider* dpp, optional_yield y, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) { const auto& pool = impl->realm_pool; // read default realm id RGWDefaultSystemMetaObjInfo default_info; const auto default_oid = default_realm_oid(dpp->get_cct()->_conf); int r = impl->read(dpp, y, pool, default_oid, default_info, nullptr); if (r < 0) { return r; } const auto info_oid = realm_info_oid(default_info.default_id); RGWObjVersionTracker objv; r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosRealmWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, std::string& realm_id) { const auto& pool = impl->realm_pool; RGWNameToId name; // look up realm id by name const auto name_oid = realm_name_oid(realm_name); int r = impl->read(dpp, y, pool, name_oid, name, nullptr); if (r < 0) { return r; } realm_id = std::move(name.obj_id); return 0; } int RadosConfigStore::realm_notify_new_period(const DoutPrefixProvider* dpp, optional_yield y, const RGWPeriod& period) { const auto& pool = impl->realm_pool; const auto control_oid = realm_control_oid(period.get_realm()); bufferlist bl; using ceph::encode; // push the period to dependent zonegroups/zones encode(RGWRealmNotify::ZonesNeedPeriod, bl); encode(period, bl); // reload the gateway with the new period encode(RGWRealmNotify::Reload, bl); constexpr uint64_t timeout_ms = 0; return impl->notify(dpp, y, pool, control_oid, bl, timeout_ms); } int RadosConfigStore::list_realm_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) { const auto& pool = impl->realm_pool; constexpr auto prefix = [] (std::string oid) -> std::string { if (!oid.starts_with(realm_names_oid_prefix)) { return {}; } return oid.substr(realm_names_oid_prefix.size()); }; return impl->list(dpp, y, pool, marker, prefix, entries, result); } } // namespace rgw::rados
11,737
31.158904
83
cc
null
ceph-main/src/rgw/driver/rados/config/store.cc
// 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 "include/rados/librados.hpp" #include "common/errno.h" #include "impl.h" #include "store.h" namespace rgw::rados { RadosConfigStore::RadosConfigStore(std::unique_ptr<ConfigImpl> impl) : impl(std::move(impl)) { } RadosConfigStore::~RadosConfigStore() = default; auto create_config_store(const DoutPrefixProvider* dpp) -> std::unique_ptr<RadosConfigStore> { auto impl = std::make_unique<ConfigImpl>(dpp->get_cct()->_conf); // initialize a Rados client int r = impl->rados.init_with_context(dpp->get_cct()); if (r < 0) { ldpp_dout(dpp, -1) << "Rados client initialization failed with " << cpp_strerror(-r) << dendl; return nullptr; } r = impl->rados.connect(); if (r < 0) { ldpp_dout(dpp, -1) << "Rados client connection failed with " << cpp_strerror(-r) << dendl; return nullptr; } return std::make_unique<RadosConfigStore>(std::move(impl)); } } // namespace rgw::rados
1,282
23.207547
68
cc
null
ceph-main/src/rgw/driver/rados/config/store.h
// vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <list> #include <memory> #include <string> #include "rgw_common.h" #include "rgw_sal_config.h" class DoutPrefixProvider; class optional_yield; namespace rgw::rados { struct ConfigImpl; class RadosConfigStore : public sal::ConfigStore { public: explicit RadosConfigStore(std::unique_ptr<ConfigImpl> impl); virtual ~RadosConfigStore() override; // Realm virtual int write_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id) override; virtual int read_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string& realm_id) override; virtual int delete_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y) override; virtual int create_realm(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_realm_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_realm_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_default_realm(const DoutPrefixProvider* dpp, optional_yield y, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, std::string& realm_id) override; virtual int realm_notify_new_period(const DoutPrefixProvider* dpp, optional_yield y, const RGWPeriod& period) override; virtual int list_realm_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // Period virtual int create_period(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWPeriod& info) override; virtual int read_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id, std::optional<uint32_t> epoch, RGWPeriod& info) override; virtual int delete_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id) override; virtual int list_period_ids(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // ZoneGroup virtual int write_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zonegroup_id) override; virtual int read_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zonegroup_id) override; virtual int delete_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; virtual int create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int read_zonegroup_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int read_zonegroup_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int read_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int list_zonegroup_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // Zone virtual int write_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zone_id) override; virtual int read_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zone_id) override; virtual int delete_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; virtual int create_zone(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int read_zone_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int read_zone_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int read_default_zone(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int list_zone_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // PeriodConfig virtual int read_period_config(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWPeriodConfig& info) override; virtual int write_period_config(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, const RGWPeriodConfig& info) override; private: std::unique_ptr<ConfigImpl> impl; }; // RadosConfigStore /// RadosConfigStore factory function auto create_config_store(const DoutPrefixProvider* dpp) -> std::unique_ptr<RadosConfigStore>; } // namespace rgw::rados
9,218
49.377049
93
h
null
ceph-main/src/rgw/driver/rados/config/zone.cc
// 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 "common/dout.h" #include "common/errno.h" #include "rgw_zone.h" #include "driver/rados/config/store.h" #include "impl.h" namespace rgw::rados { // zone oids constexpr std::string_view zone_info_oid_prefix = "zone_info."; constexpr std::string_view zone_names_oid_prefix = "zone_names."; std::string zone_info_oid(std::string_view zone_id) { return string_cat_reserve(zone_info_oid_prefix, zone_id); } std::string zone_name_oid(std::string_view zone_id) { return string_cat_reserve(zone_names_oid_prefix, zone_id); } std::string default_zone_oid(const ceph::common::ConfigProxy& conf, std::string_view realm_id) { return fmt::format("{}.{}", conf->rgw_default_zone_info_oid, realm_id); } int RadosConfigStore::write_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zone_id) { const auto& pool = impl->zone_pool; const auto default_oid = default_zone_oid(dpp->get_cct()->_conf, realm_id); const auto create = exclusive ? Create::MustNotExist : Create::MayExist; RGWDefaultSystemMetaObjInfo default_info; default_info.default_id = zone_id; return impl->write(dpp, y, pool, default_oid, create, default_info, nullptr); } int RadosConfigStore::read_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zone_id) { const auto& pool = impl->zone_pool; const auto default_oid = default_zone_oid(dpp->get_cct()->_conf, realm_id); RGWDefaultSystemMetaObjInfo default_info; int r = impl->read(dpp, y, pool, default_oid, default_info, nullptr); if (r >= 0) { zone_id = default_info.default_id; } return r; } int RadosConfigStore::delete_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) { const auto& pool = impl->zone_pool; const auto default_oid = default_zone_oid(dpp->get_cct()->_conf, realm_id); return impl->remove(dpp, y, pool, default_oid, nullptr); } class RadosZoneWriter : public sal::ZoneWriter { ConfigImpl* impl; RGWObjVersionTracker objv; std::string zone_id; std::string zone_name; public: RadosZoneWriter(ConfigImpl* impl, RGWObjVersionTracker objv, std::string_view zone_id, std::string_view zone_name) : impl(impl), objv(std::move(objv)), zone_id(zone_id), zone_name(zone_name) { } int write(const DoutPrefixProvider* dpp, optional_yield y, const RGWZoneParams& info) override { if (zone_id != info.get_id() || zone_name != info.get_name()) { return -EINVAL; // can't modify zone id or name directly } const auto& pool = impl->zone_pool; const auto info_oid = zone_info_oid(info.get_id()); return impl->write(dpp, y, pool, info_oid, Create::MustExist, info, &objv); } int rename(const DoutPrefixProvider* dpp, optional_yield y, RGWZoneParams& info, std::string_view new_name) override { if (zone_id != info.get_id() || zone_name != info.get_name()) { return -EINVAL; // can't modify zone id or name directly } if (new_name.empty()) { ldpp_dout(dpp, 0) << "zone cannot have an empty name" << dendl; return -EINVAL; } const auto& pool = impl->zone_pool; const auto name = RGWNameToId{info.get_id()}; const auto info_oid = zone_info_oid(info.get_id()); const auto old_oid = zone_name_oid(info.get_name()); const auto new_oid = zone_name_oid(new_name); // link the new name RGWObjVersionTracker new_objv; new_objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, new_oid, Create::MustNotExist, name, &new_objv); if (r < 0) { return r; } // write the info with updated name info.set_name(std::string{new_name}); r = impl->write(dpp, y, pool, info_oid, Create::MustExist, info, &objv); if (r < 0) { // on failure, unlink the new name (void) impl->remove(dpp, y, pool, new_oid, &new_objv); return r; } // unlink the old name (void) impl->remove(dpp, y, pool, old_oid, nullptr); zone_name = new_name; return 0; } int remove(const DoutPrefixProvider* dpp, optional_yield y) override { const auto& pool = impl->zone_pool; const auto info_oid = zone_info_oid(zone_id); int r = impl->remove(dpp, y, pool, info_oid, &objv); if (r < 0) { return r; } const auto name_oid = zone_name_oid(zone_name); (void) impl->remove(dpp, y, pool, name_oid, nullptr); return 0; } }; // RadosZoneWriter int RadosConfigStore::create_zone(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) { if (info.get_id().empty()) { ldpp_dout(dpp, 0) << "zone cannot have an empty id" << dendl; return -EINVAL; } if (info.get_name().empty()) { ldpp_dout(dpp, 0) << "zone cannot have an empty name" << dendl; return -EINVAL; } const auto& pool = impl->zone_pool; const auto create = exclusive ? Create::MustNotExist : Create::MayExist; // write the zone info const auto info_oid = zone_info_oid(info.get_id()); RGWObjVersionTracker objv; objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, info_oid, create, info, &objv); if (r < 0) { return r; } // write the zone name const auto name_oid = zone_name_oid(info.get_name()); const auto name = RGWNameToId{info.get_id()}; RGWObjVersionTracker name_objv; name_objv.generate_new_write_ver(dpp->get_cct()); r = impl->write(dpp, y, pool, name_oid, create, name, &name_objv); if (r < 0) { (void) impl->remove(dpp, y, pool, info_oid, &objv); return r; } if (writer) { *writer = std::make_unique<RadosZoneWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_zone_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) { const auto& pool = impl->zone_pool; const auto info_oid = zone_info_oid(zone_id); RGWObjVersionTracker objv; int r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosZoneWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_zone_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) { const auto& pool = impl->zone_pool; // look up zone id by name const auto name_oid = zone_name_oid(zone_name); RGWNameToId name; int r = impl->read(dpp, y, pool, name_oid, name, nullptr); if (r < 0) { return r; } const auto info_oid = zone_info_oid(name.obj_id); RGWObjVersionTracker objv; r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosZoneWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_default_zone(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) { const auto& pool = impl->zone_pool; // read default zone id const auto default_oid = default_zone_oid(dpp->get_cct()->_conf, realm_id); RGWDefaultSystemMetaObjInfo default_info; int r = impl->read(dpp, y, pool, default_oid, default_info, nullptr); if (r < 0) { return r; } const auto info_oid = zone_info_oid(default_info.default_id); RGWObjVersionTracker objv; r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosZoneWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::list_zone_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) { const auto& pool = impl->zone_pool; constexpr auto prefix = [] (std::string oid) -> std::string { if (!oid.starts_with(zone_names_oid_prefix)) { return {}; } return oid.substr(zone_names_oid_prefix.size()); }; return impl->list(dpp, y, pool, marker, prefix, entries, result); } } // namespace rgw::rados
9,991
30.923323
81
cc
null
ceph-main/src/rgw/driver/rados/config/zonegroup.cc
// 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 "common/dout.h" #include "common/errno.h" #include "rgw_zone.h" #include "driver/rados/config/store.h" #include "impl.h" namespace rgw::rados { // zonegroup oids constexpr std::string_view zonegroup_names_oid_prefix = "zonegroups_names."; constexpr std::string_view zonegroup_info_oid_prefix = "zonegroup_info."; constexpr std::string_view default_zonegroup_info_oid = "default.zonegroup"; static std::string zonegroup_info_oid(std::string_view zonegroup_id) { return string_cat_reserve(zonegroup_info_oid_prefix, zonegroup_id); } static std::string zonegroup_name_oid(std::string_view zonegroup_id) { return string_cat_reserve(zonegroup_names_oid_prefix, zonegroup_id); } static std::string default_zonegroup_oid(const ceph::common::ConfigProxy& conf, std::string_view realm_id) { const auto prefix = name_or_default(conf->rgw_default_zonegroup_info_oid, default_zonegroup_info_oid); return fmt::format("{}.{}", prefix, realm_id); } int RadosConfigStore::write_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zonegroup_id) { const auto& pool = impl->zonegroup_pool; const auto oid = default_zonegroup_oid(dpp->get_cct()->_conf, realm_id); const auto create = exclusive ? Create::MustNotExist : Create::MayExist; RGWDefaultSystemMetaObjInfo default_info; default_info.default_id = zonegroup_id; return impl->write(dpp, y, pool, oid, create, default_info, nullptr); } int RadosConfigStore::read_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zonegroup_id) { const auto& pool = impl->zonegroup_pool; const auto oid = default_zonegroup_oid(dpp->get_cct()->_conf, realm_id); RGWDefaultSystemMetaObjInfo default_info; int r = impl->read(dpp, y, pool, oid, default_info, nullptr); if (r >= 0) { zonegroup_id = default_info.default_id; } return r; } int RadosConfigStore::delete_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) { const auto& pool = impl->zonegroup_pool; const auto oid = default_zonegroup_oid(dpp->get_cct()->_conf, realm_id); return impl->remove(dpp, y, pool, oid, nullptr); } class RadosZoneGroupWriter : public sal::ZoneGroupWriter { ConfigImpl* impl; RGWObjVersionTracker objv; std::string zonegroup_id; std::string zonegroup_name; public: RadosZoneGroupWriter(ConfigImpl* impl, RGWObjVersionTracker objv, std::string_view zonegroup_id, std::string_view zonegroup_name) : impl(impl), objv(std::move(objv)), zonegroup_id(zonegroup_id), zonegroup_name(zonegroup_name) { } int write(const DoutPrefixProvider* dpp, optional_yield y, const RGWZoneGroup& info) override { if (zonegroup_id != info.get_id() || zonegroup_name != info.get_name()) { return -EINVAL; // can't modify zonegroup id or name directly } const auto& pool = impl->zonegroup_pool; const auto info_oid = zonegroup_info_oid(info.get_id()); return impl->write(dpp, y, pool, info_oid, Create::MustExist, info, &objv); } int rename(const DoutPrefixProvider* dpp, optional_yield y, RGWZoneGroup& info, std::string_view new_name) override { if (zonegroup_id != info.get_id() || zonegroup_name != info.get_name()) { return -EINVAL; // can't modify zonegroup id or name directly } if (new_name.empty()) { ldpp_dout(dpp, 0) << "zonegroup cannot have an empty name" << dendl; return -EINVAL; } const auto& pool = impl->zonegroup_pool; const auto name = RGWNameToId{info.get_id()}; const auto info_oid = zonegroup_info_oid(info.get_id()); const auto old_oid = zonegroup_name_oid(info.get_name()); const auto new_oid = zonegroup_name_oid(new_name); // link the new name RGWObjVersionTracker new_objv; new_objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, new_oid, Create::MustNotExist, name, &new_objv); if (r < 0) { return r; } // write the info with updated name info.set_name(std::string{new_name}); r = impl->write(dpp, y, pool, info_oid, Create::MustExist, info, &objv); if (r < 0) { // on failure, unlink the new name (void) impl->remove(dpp, y, pool, new_oid, &new_objv); return r; } // unlink the old name (void) impl->remove(dpp, y, pool, old_oid, nullptr); zonegroup_name = new_name; return 0; } int remove(const DoutPrefixProvider* dpp, optional_yield y) override { const auto& pool = impl->zonegroup_pool; const auto info_oid = zonegroup_info_oid(zonegroup_id); int r = impl->remove(dpp, y, pool, info_oid, &objv); if (r < 0) { return r; } const auto name_oid = zonegroup_name_oid(zonegroup_name); (void) impl->remove(dpp, y, pool, name_oid, nullptr); return 0; } }; // RadosZoneGroupWriter int RadosConfigStore::create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) { if (info.get_id().empty()) { ldpp_dout(dpp, 0) << "zonegroup cannot have an empty id" << dendl; return -EINVAL; } if (info.get_name().empty()) { ldpp_dout(dpp, 0) << "zonegroup cannot have an empty name" << dendl; return -EINVAL; } const auto& pool = impl->zonegroup_pool; const auto create = exclusive ? Create::MustNotExist : Create::MayExist; // write the zonegroup info const auto info_oid = zonegroup_info_oid(info.get_id()); RGWObjVersionTracker objv; objv.generate_new_write_ver(dpp->get_cct()); int r = impl->write(dpp, y, pool, info_oid, create, info, &objv); if (r < 0) { return r; } // write the zonegroup name const auto name_oid = zonegroup_name_oid(info.get_name()); const auto name = RGWNameToId{info.get_id()}; RGWObjVersionTracker name_objv; name_objv.generate_new_write_ver(dpp->get_cct()); r = impl->write(dpp, y, pool, name_oid, create, name, &name_objv); if (r < 0) { (void) impl->remove(dpp, y, pool, info_oid, &objv); return r; } if (writer) { *writer = std::make_unique<RadosZoneGroupWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_zonegroup_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) { const auto& pool = impl->zonegroup_pool; const auto info_oid = zonegroup_info_oid(zonegroup_id); RGWObjVersionTracker objv; int r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosZoneGroupWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_zonegroup_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) { const auto& pool = impl->zonegroup_pool; // look up zonegroup id by name RGWNameToId name; const auto name_oid = zonegroup_name_oid(zonegroup_name); int r = impl->read(dpp, y, pool, name_oid, name, nullptr); if (r < 0) { return r; } const auto info_oid = zonegroup_info_oid(name.obj_id); RGWObjVersionTracker objv; r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosZoneGroupWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::read_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) { const auto& pool = impl->zonegroup_pool; // read default zonegroup id RGWDefaultSystemMetaObjInfo default_info; const auto default_oid = default_zonegroup_oid(dpp->get_cct()->_conf, realm_id); int r = impl->read(dpp, y, pool, default_oid, default_info, nullptr); if (r < 0) { return r; } const auto info_oid = zonegroup_info_oid(default_info.default_id); RGWObjVersionTracker objv; r = impl->read(dpp, y, pool, info_oid, info, &objv); if (r < 0) { return r; } if (writer) { *writer = std::make_unique<RadosZoneGroupWriter>( impl.get(), std::move(objv), info.get_id(), info.get_name()); } return 0; } int RadosConfigStore::list_zonegroup_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) { const auto& pool = impl->zonegroup_pool; constexpr auto prefix = [] (std::string oid) -> std::string { if (!oid.starts_with(zonegroup_names_oid_prefix)) { return {}; } return oid.substr(zonegroup_names_oid_prefix.size()); }; return impl->list(dpp, y, pool, marker, prefix, entries, result); } } // namespace rgw::rados
10,804
33.193038
91
cc
null
ceph-main/src/rgw/jwt-cpp/base.h
#pragma once #include <string> #include <array> namespace jwt { namespace alphabet { struct base64 { static const std::array<char, 64>& data() { static std::array<char, 64> data = { {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}}; return data; }; static const std::string& fill() { static std::string fill = "="; return fill; } }; struct base64url { static const std::array<char, 64>& data() { static std::array<char, 64> data = { {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'}}; return data; }; static const std::string& fill() { static std::string fill = "%3d"; return fill; } }; } class base { public: template<typename T> static std::string encode(const std::string& bin) { return encode(bin, T::data(), T::fill()); } template<typename T> static std::string decode(const std::string& base) { return decode(base, T::data(), T::fill()); } private: static std::string encode(const std::string& bin, const std::array<char, 64>& alphabet, const std::string& fill) { size_t size = bin.size(); std::string res; // clear incomplete bytes size_t fast_size = size - size % 3; for (size_t i = 0; i < fast_size;) { uint32_t octet_a = (unsigned char)bin[i++]; uint32_t octet_b = (unsigned char)bin[i++]; uint32_t octet_c = (unsigned char)bin[i++]; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; res += alphabet[(triple >> 3 * 6) & 0x3F]; res += alphabet[(triple >> 2 * 6) & 0x3F]; res += alphabet[(triple >> 1 * 6) & 0x3F]; res += alphabet[(triple >> 0 * 6) & 0x3F]; } if (fast_size == size) return res; size_t mod = size % 3; uint32_t octet_a = fast_size < size ? (unsigned char)bin[fast_size++] : 0; uint32_t octet_b = fast_size < size ? (unsigned char)bin[fast_size++] : 0; uint32_t octet_c = fast_size < size ? (unsigned char)bin[fast_size++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; switch (mod) { case 1: res += alphabet[(triple >> 3 * 6) & 0x3F]; res += alphabet[(triple >> 2 * 6) & 0x3F]; res += fill; res += fill; break; case 2: res += alphabet[(triple >> 3 * 6) & 0x3F]; res += alphabet[(triple >> 2 * 6) & 0x3F]; res += alphabet[(triple >> 1 * 6) & 0x3F]; res += fill; break; default: break; } return res; } static std::string decode(const std::string& base, const std::array<char, 64>& alphabet, const std::string& fill) { size_t size = base.size(); size_t fill_cnt = 0; while (size > fill.size()) { if (base.substr(size - fill.size(), fill.size()) == fill) { fill_cnt++; size -= fill.size(); if(fill_cnt > 2) throw std::runtime_error("Invalid input"); } else break; } if ((size + fill_cnt) % 4 != 0) throw std::runtime_error("Invalid input"); size_t out_size = size / 4 * 3; std::string res; res.reserve(out_size); auto get_sextet = [&](size_t offset) { for (size_t i = 0; i < alphabet.size(); i++) { if (alphabet[i] == base[offset]) return i; } throw std::runtime_error("Invalid input"); }; size_t fast_size = size - size % 4; for (size_t i = 0; i < fast_size;) { uint32_t sextet_a = get_sextet(i++); uint32_t sextet_b = get_sextet(i++); uint32_t sextet_c = get_sextet(i++); uint32_t sextet_d = get_sextet(i++); uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); res += (triple >> 2 * 8) & 0xFF; res += (triple >> 1 * 8) & 0xFF; res += (triple >> 0 * 8) & 0xFF; } if (fill_cnt == 0) return res; uint32_t triple = (get_sextet(fast_size) << 3 * 6) + (get_sextet(fast_size + 1) << 2 * 6); switch (fill_cnt) { case 1: triple |= (get_sextet(fast_size + 2) << 1 * 6); res += (triple >> 2 * 8) & 0xFF; res += (triple >> 1 * 8) & 0xFF; break; case 2: res += (triple >> 2 * 8) & 0xFF; break; default: break; } return res; } }; }
5,000
28.591716
117
h
null
ceph-main/src/rgw/jwt-cpp/jwt.h
#pragma once #define PICOJSON_USE_INT64 #include "picojson/picojson.h" #include "base.h" #include <set> #include <chrono> #include <unordered_map> #include <memory> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/pem.h> #include <openssl/ec.h> #include <openssl/err.h> //If openssl version less than 1.1 #if OPENSSL_VERSION_NUMBER < 269484032 #define OPENSSL10 #endif #ifndef JWT_CLAIM_EXPLICIT #define JWT_CLAIM_EXPLICIT 1 #endif namespace jwt { using date = std::chrono::system_clock::time_point; struct signature_verification_exception : public std::runtime_error { signature_verification_exception() : std::runtime_error("signature verification failed") {} explicit signature_verification_exception(const std::string& msg) : std::runtime_error(msg) {} explicit signature_verification_exception(const char* msg) : std::runtime_error(msg) {} }; struct signature_generation_exception : public std::runtime_error { signature_generation_exception() : std::runtime_error("signature generation failed") {} explicit signature_generation_exception(const std::string& msg) : std::runtime_error(msg) {} explicit signature_generation_exception(const char* msg) : std::runtime_error(msg) {} }; struct rsa_exception : public std::runtime_error { explicit rsa_exception(const std::string& msg) : std::runtime_error(msg) {} explicit rsa_exception(const char* msg) : std::runtime_error(msg) {} }; struct ecdsa_exception : public std::runtime_error { explicit ecdsa_exception(const std::string& msg) : std::runtime_error(msg) {} explicit ecdsa_exception(const char* msg) : std::runtime_error(msg) {} }; struct token_verification_exception : public std::runtime_error { token_verification_exception() : std::runtime_error("token verification failed") {} explicit token_verification_exception(const std::string& msg) : std::runtime_error("token verification failed: " + msg) {} }; namespace helper { inline std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") { // TODO: Cannot find the exact version this change happended #if OPENSSL_VERSION_NUMBER <= 0x1000114fL std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(BIO_new_mem_buf(const_cast<char*>(certstr.data()), certstr.size()), BIO_free_all); #else std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(BIO_new_mem_buf(certstr.data(), certstr.size()), BIO_free_all); #endif std::unique_ptr<BIO, decltype(&BIO_free_all)> keybio(BIO_new(BIO_s_mem()), BIO_free_all); std::unique_ptr<X509, decltype(&X509_free)> cert(PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast<char*>(pw.c_str())), X509_free); if (!cert) throw rsa_exception("Error loading cert into memory"); std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(X509_get_pubkey(cert.get()), EVP_PKEY_free); if(!key) throw rsa_exception("Error getting public key from certificate"); if(!PEM_write_bio_PUBKEY(keybio.get(), key.get())) throw rsa_exception("Error writing public key data in PEM format"); char* ptr = nullptr; auto len = BIO_get_mem_data(keybio.get(), &ptr); if(len <= 0 || ptr == nullptr) throw rsa_exception("Failed to convert pubkey to pem"); std::string res(ptr, len); return res; } inline std::shared_ptr<EVP_PKEY> load_public_key_from_string(const std::string& key, const std::string& password = "") { std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); if(key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") { auto epkey = helper::extract_pubkey_from_cert(key, password); if ((size_t)BIO_write(pubkey_bio.get(), epkey.data(), epkey.size()) != epkey.size()) throw rsa_exception("failed to load public key: bio_write failed"); } else { if ((size_t)BIO_write(pubkey_bio.get(), key.data(), key.size()) != key.size()) throw rsa_exception("failed to load public key: bio_write failed"); } std::shared_ptr<EVP_PKEY> pkey(PEM_read_bio_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)password.c_str()), EVP_PKEY_free); if (!pkey) throw rsa_exception("failed to load public key: PEM_read_bio_PUBKEY failed:" + std::string(ERR_error_string(ERR_get_error(), NULL))); return pkey; } inline std::shared_ptr<EVP_PKEY> load_private_key_from_string(const std::string& key, const std::string& password = "") { std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); if ((size_t)BIO_write(privkey_bio.get(), key.data(), key.size()) != key.size()) throw rsa_exception("failed to load private key: bio_write failed"); std::shared_ptr<EVP_PKEY> pkey(PEM_read_bio_PrivateKey(privkey_bio.get(), nullptr, nullptr, const_cast<char*>(password.c_str())), EVP_PKEY_free); if (!pkey) throw rsa_exception("failed to load private key: PEM_read_bio_PrivateKey failed"); return pkey; } } namespace algorithm { /** * "none" algorithm. * * Returns and empty signature and checks if the given signature is empty. */ struct none { /// Return an empty string std::string sign(const std::string&) const { return ""; } /// Check if the given signature is empty. JWT's with "none" algorithm should not contain a signature. void verify(const std::string&, const std::string& signature) const { if (!signature.empty()) throw signature_verification_exception(); } /// Get algorithm name std::string name() const { return "none"; } }; /** * Base class for HMAC family of algorithms */ struct hmacsha { /** * Construct new hmac algorithm * \param key Key to use for HMAC * \param md Pointer to hash function * \param name Name of the algorithm */ hmacsha(std::string key, const EVP_MD*(*md)(), const std::string& name) : secret(std::move(key)), md(md), alg_name(name) {} /** * Sign jwt data * \param data The data to sign * \return HMAC signature for the given data * \throws signature_generation_exception */ std::string sign(const std::string& data) const { std::string res; res.resize(EVP_MAX_MD_SIZE); unsigned int len = res.size(); if (HMAC(md(), secret.data(), secret.size(), (const unsigned char*)data.data(), data.size(), (unsigned char*)res.data(), &len) == nullptr) throw signature_generation_exception(); res.resize(len); return res; } /** * Check if signature is valid * \param data The data to check signature against * \param signature Signature provided by the jwt * \throws signature_verification_exception If the provided signature does not match */ void verify(const std::string& data, const std::string& signature) const { try { auto res = sign(data); bool matched = true; for (size_t i = 0; i < std::min<size_t>(res.size(), signature.size()); i++) if (res[i] != signature[i]) matched = false; if (res.size() != signature.size()) matched = false; if (!matched) throw signature_verification_exception(); } catch (const signature_generation_exception&) { throw signature_verification_exception(); } } /** * Returns the algorithm name provided to the constructor * \return Algorithmname */ std::string name() const { return alg_name; } private: /// HMAC secrect const std::string secret; /// HMAC hash generator const EVP_MD*(*md)(); /// Algorithmname const std::string alg_name; }; /** * Base class for RSA family of algorithms */ struct rsa { /** * Construct new rsa algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. * \param md Pointer to hash function * \param name Name of the algorithm */ rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), const std::string& name) : md(md), alg_name(name) { if (!private_key.empty()) { pkey = helper::load_private_key_from_string(private_key, private_key_password); } else if(!public_key.empty()) { pkey = helper::load_public_key_from_string(public_key, public_key_password); } else throw rsa_exception("at least one of public or private key need to be present"); } /** * Sign jwt data * \param data The data to sign * \return RSA signature for the given data * \throws signature_generation_exception */ std::string sign(const std::string& data) const { #ifdef OPENSSL10 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_destroy); #else std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_free); #endif if (!ctx) throw signature_generation_exception("failed to create signature: could not create context"); if (!EVP_SignInit(ctx.get(), md())) throw signature_generation_exception("failed to create signature: SignInit failed"); std::string res; res.resize(EVP_PKEY_size(pkey.get())); unsigned int len = 0; if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) throw signature_generation_exception(); if (!EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get())) throw signature_generation_exception(); res.resize(len); return res; } /** * Check if signature is valid * \param data The data to check signature against * \param signature Signature provided by the jwt * \throws signature_verification_exception If the provided signature does not match */ void verify(const std::string& data, const std::string& signature) const { #ifdef OPENSSL10 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_destroy); #else std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_free); #endif if (!ctx) throw signature_verification_exception("failed to verify signature: could not create context"); if (!EVP_VerifyInit(ctx.get(), md())) throw signature_verification_exception("failed to verify signature: VerifyInit failed"); if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size())) throw signature_verification_exception("failed to verify signature: VerifyUpdate failed"); auto res = EVP_VerifyFinal(ctx.get(), (const unsigned char*)signature.data(), signature.size(), pkey.get()); if (res != 1) throw signature_verification_exception("evp verify final failed: " + std::to_string(res) + " " + ERR_error_string(ERR_get_error(), NULL)); } /** * Returns the algorithm name provided to the constructor * \return Algorithmname */ std::string name() const { return alg_name; } private: /// OpenSSL structure containing converted keys std::shared_ptr<EVP_PKEY> pkey; /// Hash generator const EVP_MD*(*md)(); /// Algorithmname const std::string alg_name; }; /** * Base class for ECDSA family of algorithms */ struct ecdsa { /** * Construct new ecdsa algorithm * \param public_key ECDSA public key in PEM format * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. * \param md Pointer to hash function * \param name Name of the algorithm */ ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), const std::string& name, size_t siglen) : md(md), alg_name(name), signature_length(siglen) { if (!public_key.empty()) { std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); if(public_key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") { auto epkey = helper::extract_pubkey_from_cert(public_key, public_key_password); if ((size_t)BIO_write(pubkey_bio.get(), epkey.data(), epkey.size()) != epkey.size()) throw ecdsa_exception("failed to load public key: bio_write failed"); } else { if ((size_t)BIO_write(pubkey_bio.get(), public_key.data(), public_key.size()) != public_key.size()) throw ecdsa_exception("failed to load public key: bio_write failed"); } pkey.reset(PEM_read_bio_EC_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)public_key_password.c_str()), EC_KEY_free); if (!pkey) throw ecdsa_exception("failed to load public key: PEM_read_bio_EC_PUBKEY failed:" + std::string(ERR_error_string(ERR_get_error(), NULL))); size_t keysize = EC_GROUP_get_degree(EC_KEY_get0_group(pkey.get())); if(keysize != signature_length*4 && (signature_length != 132 || keysize != 521)) throw ecdsa_exception("invalid key size"); } if (!private_key.empty()) { std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); if ((size_t)BIO_write(privkey_bio.get(), private_key.data(), private_key.size()) != private_key.size()) throw rsa_exception("failed to load private key: bio_write failed"); pkey.reset(PEM_read_bio_ECPrivateKey(privkey_bio.get(), nullptr, nullptr, const_cast<char*>(private_key_password.c_str())), EC_KEY_free); if (!pkey) throw rsa_exception("failed to load private key: PEM_read_bio_ECPrivateKey failed"); size_t keysize = EC_GROUP_get_degree(EC_KEY_get0_group(pkey.get())); if(keysize != signature_length*4 && (signature_length != 132 || keysize != 521)) throw ecdsa_exception("invalid key size"); } if(!pkey) throw rsa_exception("at least one of public or private key need to be present"); if(EC_KEY_check_key(pkey.get()) == 0) throw ecdsa_exception("failed to load key: key is invalid"); } /** * Sign jwt data * \param data The data to sign * \return ECDSA signature for the given data * \throws signature_generation_exception */ std::string sign(const std::string& data) const { const std::string hash = generate_hash(data); std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_do_sign((const unsigned char*)hash.data(), hash.size(), pkey.get()), ECDSA_SIG_free); if(!sig) throw signature_generation_exception(); #ifdef OPENSSL10 auto rr = bn2raw(sig->r); auto rs = bn2raw(sig->s); #else const BIGNUM *r; const BIGNUM *s; ECDSA_SIG_get0(sig.get(), &r, &s); auto rr = bn2raw(r); auto rs = bn2raw(s); #endif if(rr.size() > signature_length/2 || rs.size() > signature_length/2) throw std::logic_error("bignum size exceeded expected length"); while(rr.size() != signature_length/2) rr = '\0' + rr; while(rs.size() != signature_length/2) rs = '\0' + rs; return rr + rs; } /** * Check if signature is valid * \param data The data to check signature against * \param signature Signature provided by the jwt * \throws signature_verification_exception If the provided signature does not match */ void verify(const std::string& data, const std::string& signature) const { const std::string hash = generate_hash(data); auto r = raw2bn(signature.substr(0, signature.size() / 2)); auto s = raw2bn(signature.substr(signature.size() / 2)); #ifdef OPENSSL10 ECDSA_SIG sig; sig.r = r.get(); sig.s = s.get(); if(ECDSA_do_verify((const unsigned char*)hash.data(), hash.size(), &sig, pkey.get()) != 1) throw signature_verification_exception("Invalid signature"); #else std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_SIG_new(), ECDSA_SIG_free); ECDSA_SIG_set0(sig.get(), r.release(), s.release()); if(ECDSA_do_verify((const unsigned char*)hash.data(), hash.size(), sig.get(), pkey.get()) != 1) throw signature_verification_exception("Invalid signature"); #endif } /** * Returns the algorithm name provided to the constructor * \return Algorithmname */ std::string name() const { return alg_name; } private: /** * Convert a OpenSSL BIGNUM to a std::string * \param bn BIGNUM to convert * \return bignum as string */ #ifdef OPENSSL10 static std::string bn2raw(BIGNUM* bn) #else static std::string bn2raw(const BIGNUM* bn) #endif { std::string res; res.resize(BN_num_bytes(bn)); BN_bn2bin(bn, (unsigned char*)res.data()); return res; } /** * Convert an std::string to a OpenSSL BIGNUM * \param raw String to convert * \return BIGNUM representation */ static std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw) { return std::unique_ptr<BIGNUM, decltype(&BN_free)>(BN_bin2bn((const unsigned char*)raw.data(), raw.size(), nullptr), BN_free); } /** * Hash the provided data using the hash function specified in constructor * \param data Data to hash * \return Hash of data */ std::string generate_hash(const std::string& data) const { #ifdef OPENSSL10 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy); #else std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free); #endif if(EVP_DigestInit(ctx.get(), md()) == 0) throw signature_generation_exception("EVP_DigestInit failed"); if(EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0) throw signature_generation_exception("EVP_DigestUpdate failed"); unsigned int len = 0; std::string res; res.resize(EVP_MD_CTX_size(ctx.get())); if(EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == 0) throw signature_generation_exception("EVP_DigestFinal failed"); res.resize(len); return res; } /// OpenSSL struct containing keys std::shared_ptr<EC_KEY> pkey; /// Hash generator function const EVP_MD*(*md)(); /// Algorithmname const std::string alg_name; /// Length of the resulting signature const size_t signature_length; }; /** * Base class for PSS-RSA family of algorithms */ struct pss { /** * Construct new pss algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. * \param md Pointer to hash function * \param name Name of the algorithm */ pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), const std::string& name) : md(md), alg_name(name) { if (!private_key.empty()) { pkey = helper::load_private_key_from_string(private_key, private_key_password); } else if(!public_key.empty()) { pkey = helper::load_public_key_from_string(public_key, public_key_password); } else throw rsa_exception("at least one of public or private key need to be present"); } /** * Sign jwt data * \param data The data to sign * \return ECDSA signature for the given data * \throws signature_generation_exception */ std::string sign(const std::string& data) const { auto hash = this->generate_hash(data); std::unique_ptr<RSA, decltype(&RSA_free)> key(EVP_PKEY_get1_RSA(pkey.get()), RSA_free); const int size = RSA_size(key.get()); std::string padded(size, 0x00); if (!RSA_padding_add_PKCS1_PSS_mgf1(key.get(), (unsigned char*)padded.data(), (const unsigned char*)hash.data(), md(), md(), -1)) throw signature_generation_exception("failed to create signature: RSA_padding_add_PKCS1_PSS_mgf1 failed"); std::string res(size, 0x00); if (RSA_private_encrypt(size, (const unsigned char*)padded.data(), (unsigned char*)res.data(), key.get(), RSA_NO_PADDING) < 0) throw signature_generation_exception("failed to create signature: RSA_private_encrypt failed"); return res; } /** * Check if signature is valid * \param data The data to check signature against * \param signature Signature provided by the jwt * \throws signature_verification_exception If the provided signature does not match */ void verify(const std::string& data, const std::string& signature) const { auto hash = this->generate_hash(data); std::unique_ptr<RSA, decltype(&RSA_free)> key(EVP_PKEY_get1_RSA(pkey.get()), RSA_free); const int size = RSA_size(key.get()); std::string sig(size, 0x00); if(!RSA_public_decrypt(signature.size(), (const unsigned char*)signature.data(), (unsigned char*)sig.data(), key.get(), RSA_NO_PADDING)) throw signature_verification_exception("Invalid signature"); if(!RSA_verify_PKCS1_PSS_mgf1(key.get(), (const unsigned char*)hash.data(), md(), md(), (const unsigned char*)sig.data(), -1)) throw signature_verification_exception("Invalid signature"); } /** * Returns the algorithm name provided to the constructor * \return Algorithmname */ std::string name() const { return alg_name; } private: /** * Hash the provided data using the hash function specified in constructor * \param data Data to hash * \return Hash of data */ std::string generate_hash(const std::string& data) const { #ifdef OPENSSL10 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy); #else std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free); #endif if(EVP_DigestInit(ctx.get(), md()) == 0) throw signature_generation_exception("EVP_DigestInit failed"); if(EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0) throw signature_generation_exception("EVP_DigestUpdate failed"); unsigned int len = 0; std::string res; res.resize(EVP_MD_CTX_size(ctx.get())); if(EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == 0) throw signature_generation_exception("EVP_DigestFinal failed"); res.resize(len); return res; } /// OpenSSL structure containing keys std::shared_ptr<EVP_PKEY> pkey; /// Hash generator function const EVP_MD*(*md)(); /// Algorithmname const std::string alg_name; }; /** * HS256 algorithm */ struct hs256 : public hmacsha { /** * Construct new instance of algorithm * \param key HMAC signing key */ explicit hs256(std::string key) : hmacsha(std::move(key), EVP_sha256, "HS256") {} }; /** * HS384 algorithm */ struct hs384 : public hmacsha { /** * Construct new instance of algorithm * \param key HMAC signing key */ explicit hs384(std::string key) : hmacsha(std::move(key), EVP_sha384, "HS384") {} }; /** * HS512 algorithm */ struct hs512 : public hmacsha { /** * Construct new instance of algorithm * \param key HMAC signing key */ explicit hs512(std::string key) : hmacsha(std::move(key), EVP_sha512, "HS512") {} }; /** * RS256 algorithm */ struct rs256 : public rsa { /** * Construct new instance of algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit rs256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256") {} }; /** * RS384 algorithm */ struct rs384 : public rsa { /** * Construct new instance of algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit rs384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384") {} }; /** * RS512 algorithm */ struct rs512 : public rsa { /** * Construct new instance of algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit rs512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512") {} }; /** * ES256 algorithm */ struct es256 : public ecdsa { /** * Construct new instance of algorithm * \param public_key ECDSA public key in PEM format * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit es256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256", 64) {} }; /** * ES384 algorithm */ struct es384 : public ecdsa { /** * Construct new instance of algorithm * \param public_key ECDSA public key in PEM format * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit es384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384", 96) {} }; /** * ES512 algorithm */ struct es512 : public ecdsa { /** * Construct new instance of algorithm * \param public_key ECDSA public key in PEM format * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit es512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512", 132) {} }; /** * PS256 algorithm */ struct ps256 : public pss { /** * Construct new instance of algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit ps256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256") {} }; /** * PS384 algorithm */ struct ps384 : public pss { /** * Construct new instance of algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit ps384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384") {} }; /** * PS512 algorithm */ struct ps512 : public pss { /** * Construct new instance of algorithm * \param public_key RSA public key in PEM format * \param private_key RSA private key or empty string if not available. If empty, signing will always fail. * \param public_key_password Password to decrypt public key pem. * \param privat_key_password Password to decrypt private key pem. */ explicit ps512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512") {} }; } /** * Convenience wrapper for JSON value */ class claim { picojson::value val; public: enum class type { null, boolean, number, string, array, object, int64 }; claim() : val() {} #if JWT_CLAIM_EXPLICIT explicit claim(std::string s) : val(std::move(s)) {} explicit claim(const date& s) : val(int64_t(std::chrono::system_clock::to_time_t(s))) {} explicit claim(const std::set<std::string>& s) : val(picojson::array(s.cbegin(), s.cend())) {} explicit claim(const picojson::value& val) : val(val) {} #else claim(std::string s) : val(std::move(s)) {} claim(const date& s) : val(int64_t(std::chrono::system_clock::to_time_t(s))) {} claim(const std::set<std::string>& s) : val(picojson::array(s.cbegin(), s.cend())) {} claim(const picojson::value& val) : val(val) {} #endif template<typename Iterator> claim(Iterator start, Iterator end) : val(picojson::array()) { auto& arr = val.get<picojson::array>(); for(; start != end; start++) { arr.push_back(picojson::value(*start)); } } /** * Get wrapped json object * \return Wrapped json object */ picojson::value to_json() const { return val; } /** * Get type of contained object * \return Type * \throws std::logic_error An internal error occured */ type get_type() const { if (val.is<picojson::null>()) return type::null; else if (val.is<bool>()) return type::boolean; else if (val.is<int64_t>()) return type::int64; else if (val.is<double>()) return type::number; else if (val.is<std::string>()) return type::string; else if (val.is<picojson::array>()) return type::array; else if (val.is<picojson::object>()) return type::object; else throw std::logic_error("internal error"); } /** * Get the contained object as a string * \return content as string * \throws std::bad_cast Content was not a string */ const std::string& as_string() const { if (!val.is<std::string>()) throw std::bad_cast(); return val.get<std::string>(); } /** * Get the contained object as a date * \return content as date * \throws std::bad_cast Content was not a date */ date as_date() const { return std::chrono::system_clock::from_time_t(as_int()); } /** * Get the contained object as an array * \return content as array * \throws std::bad_cast Content was not an array */ const picojson::array& as_array() const { if (!val.is<picojson::array>()) throw std::bad_cast(); return val.get<picojson::array>(); } /** * Get the contained object as a set of strings * \return content as set of strings * \throws std::bad_cast Content was not a set */ const std::set<std::string> as_set() const { std::set<std::string> res; for(auto& e : as_array()) { if(!e.is<std::string>()) throw std::bad_cast(); res.insert(e.get<std::string>()); } return res; } /** * Get the contained object as an integer * \return content as int * \throws std::bad_cast Content was not an int */ int64_t as_int() const { if (!val.is<int64_t>()) throw std::bad_cast(); return val.get<int64_t>(); } /** * Get the contained object as a bool * \return content as bool * \throws std::bad_cast Content was not a bool */ bool as_bool() const { if (!val.is<bool>()) throw std::bad_cast(); return val.get<bool>(); } /** * Get the contained object as a number * \return content as double * \throws std::bad_cast Content was not a number */ double as_number() const { if (!val.is<double>()) throw std::bad_cast(); return val.get<double>(); } /** * Get the contained object as an object * \return content as object * \throws std::bad_cast Content was not an object */ const picojson::object& as_object() const { if (!val.is<picojson::object>()) throw std::bad_cast(); return val.get<picojson::object>(); } }; /** * Base class that represents a token payload. * Contains Convenience accessors for common claims. */ class payload { protected: std::unordered_map<std::string, claim> payload_claims; public: /** * Check if issuer is present ("iss") * \return true if present, false otherwise */ bool has_issuer() const noexcept { return has_payload_claim("iss"); } /** * Check if subject is present ("sub") * \return true if present, false otherwise */ bool has_subject() const noexcept { return has_payload_claim("sub"); } /** * Check if audience is present ("aud") * \return true if present, false otherwise */ bool has_audience() const noexcept { return has_payload_claim("aud"); } /** * Check if expires is present ("exp") * \return true if present, false otherwise */ bool has_expires_at() const noexcept { return has_payload_claim("exp"); } /** * Check if not before is present ("nbf") * \return true if present, false otherwise */ bool has_not_before() const noexcept { return has_payload_claim("nbf"); } /** * Check if issued at is present ("iat") * \return true if present, false otherwise */ bool has_issued_at() const noexcept { return has_payload_claim("iat"); } /** * Check if token id is present ("jti") * \return true if present, false otherwise */ bool has_id() const noexcept { return has_payload_claim("jti"); } /** * Get issuer claim * \return issuer as string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_issuer() const { return get_payload_claim("iss").as_string(); } /** * Get subject claim * \return subject as string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_subject() const { return get_payload_claim("sub").as_string(); } /** * Get audience claim * \return audience as a set of strings * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a set (Should not happen in a valid token) */ std::set<std::string> get_audience() const { auto aud = get_payload_claim("aud"); if(aud.get_type() == jwt::claim::type::string) return { aud.as_string()}; else return aud.as_set(); } /** * Get expires claim * \return expires as a date in utc * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a date (Should not happen in a valid token) */ const date get_expires_at() const { return get_payload_claim("exp").as_date(); } /** * Get not valid before claim * \return nbf date in utc * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a date (Should not happen in a valid token) */ const date get_not_before() const { return get_payload_claim("nbf").as_date(); } /** * Get issued at claim * \return issued at as date in utc * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a date (Should not happen in a valid token) */ const date get_issued_at() const { return get_payload_claim("iat").as_date(); } /** * Get id claim * \return id as string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_id() const { return get_payload_claim("jti").as_string(); } /** * Check if a payload claim is present * \return true if claim was present, false otherwise */ bool has_payload_claim(const std::string& name) const noexcept { return payload_claims.count(name) != 0; } /** * Get payload claim * \return Requested claim * \throws std::runtime_error If claim was not present */ const claim& get_payload_claim(const std::string& name) const { if (!has_payload_claim(name)) throw std::runtime_error("claim not found"); return payload_claims.at(name); } /** * Get all payload claims * \return map of claims */ std::unordered_map<std::string, claim> get_payload_claims() const { return payload_claims; } }; /** * Base class that represents a token header. * Contains Convenience accessors for common claims. */ class header { protected: std::unordered_map<std::string, claim> header_claims; public: /** * Check if algortihm is present ("alg") * \return true if present, false otherwise */ bool has_algorithm() const noexcept { return has_header_claim("alg"); } /** * Check if type is present ("typ") * \return true if present, false otherwise */ bool has_type() const noexcept { return has_header_claim("typ"); } /** * Check if content type is present ("cty") * \return true if present, false otherwise */ bool has_content_type() const noexcept { return has_header_claim("cty"); } /** * Check if key id is present ("kid") * \return true if present, false otherwise */ bool has_key_id() const noexcept { return has_header_claim("kid"); } /** * Get algorithm claim * \return algorithm as string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_algorithm() const { return get_header_claim("alg").as_string(); } /** * Get type claim * \return type as a string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_type() const { return get_header_claim("typ").as_string(); } /** * Get content type claim * \return content type as string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_content_type() const { return get_header_claim("cty").as_string(); } /** * Get key id claim * \return key id as string * \throws std::runtime_error If claim was not present * \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token) */ const std::string& get_key_id() const { return get_header_claim("kid").as_string(); } /** * Check if a header claim is present * \return true if claim was present, false otherwise */ bool has_header_claim(const std::string& name) const noexcept { return header_claims.count(name) != 0; } /** * Get header claim * \return Requested claim * \throws std::runtime_error If claim was not present */ const claim& get_header_claim(const std::string& name) const { if (!has_header_claim(name)) throw std::runtime_error("claim not found"); return header_claims.at(name); } /** * Get all header claims * \return map of claims */ std::unordered_map<std::string, claim> get_header_claims() const { return header_claims; } }; /** * Class containing all information about a decoded token */ class decoded_jwt : public header, public payload { protected: /// Unmodifed token, as passed to constructor const std::string token; /// Header part decoded from base64 std::string header; /// Unmodified header part in base64 std::string header_base64; /// Payload part decoded from base64 std::string payload; /// Unmodified payload part in base64 std::string payload_base64; /// Signature part decoded from base64 std::string signature; /// Unmodified signature part in base64 std::string signature_base64; public: /** * Constructor * Parses a given token * \param token The token to parse * \throws std::invalid_argument Token is not in correct format * \throws std::runtime_error Base64 decoding failed or invalid json */ explicit decoded_jwt(const std::string& token) : token(token) { auto hdr_end = token.find('.'); if (hdr_end == std::string::npos) throw std::invalid_argument("invalid token supplied"); auto payload_end = token.find('.', hdr_end + 1); if (payload_end == std::string::npos) throw std::invalid_argument("invalid token supplied"); header = header_base64 = token.substr(0, hdr_end); payload = payload_base64 = token.substr(hdr_end + 1, payload_end - hdr_end - 1); signature = signature_base64 = token.substr(payload_end + 1); // Fix padding: JWT requires padding to get removed auto fix_padding = [](std::string& str) { switch (str.size() % 4) { case 1: str += alphabet::base64url::fill(); #ifdef __has_cpp_attribute #if __has_cpp_attribute(fallthrough) [[fallthrough]]; #endif #endif case 2: str += alphabet::base64url::fill(); #ifdef __has_cpp_attribute #if __has_cpp_attribute(fallthrough) [[fallthrough]]; #endif #endif case 3: str += alphabet::base64url::fill(); #ifdef __has_cpp_attribute #if __has_cpp_attribute(fallthrough) [[fallthrough]]; #endif #endif default: break; } }; fix_padding(header); fix_padding(payload); fix_padding(signature); header = base::decode<alphabet::base64url>(header); payload = base::decode<alphabet::base64url>(payload); signature = base::decode<alphabet::base64url>(signature); auto parse_claims = [](const std::string& str) { std::unordered_map<std::string, claim> res; picojson::value val; if (!picojson::parse(val, str).empty()) throw std::runtime_error("Invalid json"); for (auto& e : val.get<picojson::object>()) { res.insert({ e.first, claim(e.second) }); } return res; }; header_claims = parse_claims(header); payload_claims = parse_claims(payload); } /** * Get token string, as passed to constructor * \return token as passed to constructor */ const std::string& get_token() const noexcept { return token; } /** * Get header part as json string * \return header part after base64 decoding */ const std::string& get_header() const noexcept { return header; } /** * Get payload part as json string * \return payload part after base64 decoding */ const std::string& get_payload() const noexcept { return payload; } /** * Get signature part as json string * \return signature part after base64 decoding */ const std::string& get_signature() const noexcept { return signature; } /** * Get header part as base64 string * \return header part before base64 decoding */ const std::string& get_header_base64() const noexcept { return header_base64; } /** * Get payload part as base64 string * \return payload part before base64 decoding */ const std::string& get_payload_base64() const noexcept { return payload_base64; } /** * Get signature part as base64 string * \return signature part before base64 decoding */ const std::string& get_signature_base64() const noexcept { return signature_base64; } }; /** * Builder class to build and sign a new token * Use jwt::create() to get an instance of this class. */ class builder { std::unordered_map<std::string, claim> header_claims; std::unordered_map<std::string, claim> payload_claims; builder() {} friend builder create(); public: /** * Set a header claim. * \param id Name of the claim * \param c Claim to add * \return *this to allow for method chaining */ builder& set_header_claim(const std::string& id, claim c) { header_claims[id] = std::move(c); return *this; } /** * Set a payload claim. * \param id Name of the claim * \param c Claim to add * \return *this to allow for method chaining */ builder& set_payload_claim(const std::string& id, claim c) { payload_claims[id] = std::move(c); return *this; } /** * Set algorithm claim * You normally don't need to do this, as the algorithm is automatically set if you don't change it. * \param str Name of algorithm * \return *this to allow for method chaining */ builder& set_algorithm(const std::string& str) { return set_header_claim("alg", claim(str)); } /** * Set type claim * \param str Type to set * \return *this to allow for method chaining */ builder& set_type(const std::string& str) { return set_header_claim("typ", claim(str)); } /** * Set content type claim * \param str Type to set * \return *this to allow for method chaining */ builder& set_content_type(const std::string& str) { return set_header_claim("cty", claim(str)); } /** * Set key id claim * \param str Key id to set * \return *this to allow for method chaining */ builder& set_key_id(const std::string& str) { return set_header_claim("kid", claim(str)); } /** * Set issuer claim * \param str Issuer to set * \return *this to allow for method chaining */ builder& set_issuer(const std::string& str) { return set_payload_claim("iss", claim(str)); } /** * Set subject claim * \param str Subject to set * \return *this to allow for method chaining */ builder& set_subject(const std::string& str) { return set_payload_claim("sub", claim(str)); } /** * Set audience claim * \param l Audience set * \return *this to allow for method chaining */ builder& set_audience(const std::set<std::string>& l) { return set_payload_claim("aud", claim(l)); } /** * Set audience claim * \param aud Single audience * \return *this to allow for method chaining */ builder& set_audience(const std::string& aud) { return set_payload_claim("aud", claim(aud)); } /** * Set expires at claim * \param d Expires time * \return *this to allow for method chaining */ builder& set_expires_at(const date& d) { return set_payload_claim("exp", claim(d)); } /** * Set not before claim * \param d First valid time * \return *this to allow for method chaining */ builder& set_not_before(const date& d) { return set_payload_claim("nbf", claim(d)); } /** * Set issued at claim * \param d Issued at time, should be current time * \return *this to allow for method chaining */ builder& set_issued_at(const date& d) { return set_payload_claim("iat", claim(d)); } /** * Set id claim * \param str ID to set * \return *this to allow for method chaining */ builder& set_id(const std::string& str) { return set_payload_claim("jti", claim(str)); } /** * Sign token and return result * \param algo Instance of an algorithm to sign the token with * \return Final token as a string */ template<typename T> std::string sign(const T& algo) const { picojson::object obj_header; obj_header["alg"] = picojson::value(algo.name()); for (auto& e : header_claims) { obj_header[e.first] = e.second.to_json(); } picojson::object obj_payload; for (auto& e : payload_claims) { obj_payload.insert({ e.first, e.second.to_json() }); } auto encode = [](const std::string& data) { auto base = base::encode<alphabet::base64url>(data); auto pos = base.find(alphabet::base64url::fill()); base = base.substr(0, pos); return base; }; std::string header = encode(picojson::value(obj_header).serialize()); std::string payload = encode(picojson::value(obj_payload).serialize()); std::string token = header + "." + payload; return token + "." + encode(algo.sign(token)); } }; /** * Verifier class used to check if a decoded token contains all claims required by your application and has a valid signature. */ template<typename Clock> class verifier { struct algo_base { virtual ~algo_base() {} virtual void verify(const std::string& data, const std::string& sig) = 0; }; template<typename T> struct algo : public algo_base { T alg; explicit algo(T a) : alg(a) {} virtual void verify(const std::string& data, const std::string& sig) override { alg.verify(data, sig); } }; /// Required claims std::unordered_map<std::string, claim> claims; /// Leeway time for exp, nbf and iat size_t default_leeway = 0; /// Instance of clock type Clock clock; /// Supported algorithms std::unordered_map<std::string, std::shared_ptr<algo_base>> algs; public: /** * Constructor for building a new verifier instance * \param c Clock instance */ explicit verifier(Clock c) : clock(c) {} /** * Set default leeway to use. * \param leeway Default leeway to use if not specified otherwise * \return *this to allow chaining */ verifier& leeway(size_t leeway) { default_leeway = leeway; return *this; } /** * Set leeway for expires at. * If not specified the default leeway will be used. * \param leeway Set leeway to use for expires at. * \return *this to allow chaining */ verifier& expires_at_leeway(size_t leeway) { return with_claim("exp", claim(std::chrono::system_clock::from_time_t(leeway))); } /** * Set leeway for not before. * If not specified the default leeway will be used. * \param leeway Set leeway to use for not before. * \return *this to allow chaining */ verifier& not_before_leeway(size_t leeway) { return with_claim("nbf", claim(std::chrono::system_clock::from_time_t(leeway))); } /** * Set leeway for issued at. * If not specified the default leeway will be used. * \param leeway Set leeway to use for issued at. * \return *this to allow chaining */ verifier& issued_at_leeway(size_t leeway) { return with_claim("iat", claim(std::chrono::system_clock::from_time_t(leeway))); } /** * Set an issuer to check for. * Check is casesensitive. * \param iss Issuer to check for. * \return *this to allow chaining */ verifier& with_issuer(const std::string& iss) { return with_claim("iss", claim(iss)); } /** * Set a subject to check for. * Check is casesensitive. * \param sub Subject to check for. * \return *this to allow chaining */ verifier& with_subject(const std::string& sub) { return with_claim("sub", claim(sub)); } /** * Set an audience to check for. * If any of the specified audiences is not present in the token the check fails. * \param aud Audience to check for. * \return *this to allow chaining */ verifier& with_audience(const std::set<std::string>& aud) { return with_claim("aud", claim(aud)); } /** * Set an id to check for. * Check is casesensitive. * \param id ID to check for. * \return *this to allow chaining */ verifier& with_id(const std::string& id) { return with_claim("jti", claim(id)); } /** * Specify a claim to check for. * \param name Name of the claim to check for * \param c Claim to check for * \return *this to allow chaining */ verifier& with_claim(const std::string& name, claim c) { claims[name] = c; return *this; } /** * Add an algorithm available for checking. * \param alg Algorithm to allow * \return *this to allow chaining */ template<typename Algorithm> verifier& allow_algorithm(Algorithm alg) { algs[alg.name()] = std::make_shared<algo<Algorithm>>(alg); return *this; } /** * Verify the given token. * \param jwt Token to check * \throws token_verification_exception Verification failed */ void verify(const decoded_jwt& jwt) const { const std::string data = jwt.get_header_base64() + "." + jwt.get_payload_base64(); const std::string sig = jwt.get_signature(); const std::string& algo = jwt.get_algorithm(); if (algs.count(algo) == 0) throw token_verification_exception("wrong algorithm"); algs.at(algo)->verify(data, sig); auto assert_claim_eq = [](const decoded_jwt& jwt, const std::string& key, const claim& c) { if (!jwt.has_payload_claim(key)) throw token_verification_exception("decoded_jwt is missing " + key + " claim"); auto& jc = jwt.get_payload_claim(key); if (jc.get_type() != c.get_type()) throw token_verification_exception("claim " + key + " type mismatch"); if (c.get_type() == claim::type::int64) { if (c.as_date() != jc.as_date()) throw token_verification_exception("claim " + key + " does not match expected"); } else if (c.get_type() == claim::type::array) { auto s1 = c.as_set(); auto s2 = jc.as_set(); if (s1.size() != s2.size()) throw token_verification_exception("claim " + key + " does not match expected"); auto it1 = s1.cbegin(); auto it2 = s2.cbegin(); while (it1 != s1.cend() && it2 != s2.cend()) { if (*it1++ != *it2++) throw token_verification_exception("claim " + key + " does not match expected"); } } else if (c.get_type() == claim::type::string) { if (c.as_string() != jc.as_string()) throw token_verification_exception("claim " + key + " does not match expected"); } else throw token_verification_exception("internal error"); }; auto time = clock.now(); if (jwt.has_expires_at()) { auto leeway = claims.count("exp") == 1 ? std::chrono::system_clock::to_time_t(claims.at("exp").as_date()) : default_leeway; auto exp = jwt.get_expires_at(); if (time > exp + std::chrono::seconds(leeway)) throw token_verification_exception("token expired"); } if (jwt.has_issued_at()) { auto leeway = claims.count("iat") == 1 ? std::chrono::system_clock::to_time_t(claims.at("iat").as_date()) : default_leeway; auto iat = jwt.get_issued_at(); if (time < iat - std::chrono::seconds(leeway)) throw token_verification_exception("token expired"); } if (jwt.has_not_before()) { auto leeway = claims.count("nbf") == 1 ? std::chrono::system_clock::to_time_t(claims.at("nbf").as_date()) : default_leeway; auto nbf = jwt.get_not_before(); if (time < nbf - std::chrono::seconds(leeway)) throw token_verification_exception("token expired"); } for (auto& c : claims) { if (c.first == "exp" || c.first == "iat" || c.first == "nbf") { // Nothing to do here, already checked } else if (c.first == "aud") { if (!jwt.has_audience()) throw token_verification_exception("token doesn't contain the required audience"); auto aud = jwt.get_audience(); auto expected = c.second.as_set(); for (auto& e : expected) if (aud.count(e) == 0) throw token_verification_exception("token doesn't contain the required audience"); } else { assert_claim_eq(jwt, c.first, c.second); } } } }; /** * Create a verifier using the given clock * \param c Clock instance to use * \return verifier instance */ template<typename Clock> verifier<Clock> verify(Clock c) { return verifier<Clock>(c); } /** * Default clock class using std::chrono::system_clock as a backend. */ struct default_clock { std::chrono::system_clock::time_point now() const { return std::chrono::system_clock::now(); } }; /** * Create a verifier using the default clock * \return verifier instance */ inline verifier<default_clock> verify() { return verify<default_clock>({}); } /** * Return a builder instance to create a new token */ inline builder create() { return builder(); } /** * Decode a token * \param token Token to decode * \return Decoded token * \throws std::invalid_argument Token is not in correct format * \throws std::runtime_error Base64 decoding failed or invalid json */ inline decoded_jwt decode(const std::string& token) { return decoded_jwt(token); } }
57,647
34.673267
214
h
null
ceph-main/src/rgw/picojson/picojson.h
/* * Copyright 2009-2010 Cybozu Labs, Inc. * Copyright 2011-2014 Kazuho Oku * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef picojson_h #define picojson_h #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <cstddef> #include <iostream> #include <iterator> #include <limits> #include <map> #include <stdexcept> #include <string> #include <vector> #include <utility> // for isnan/isinf #if __cplusplus >= 201103L #include <cmath> #else extern "C" { #ifdef _MSC_VER #include <float.h> #elif defined(__INTEL_COMPILER) #include <mathimf.h> #else #include <math.h> #endif } #endif #ifndef PICOJSON_USE_RVALUE_REFERENCE #if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || (defined(_MSC_VER) && _MSC_VER >= 1600) #define PICOJSON_USE_RVALUE_REFERENCE 1 #else #define PICOJSON_USE_RVALUE_REFERENCE 0 #endif #endif // PICOJSON_USE_RVALUE_REFERENCE #ifndef PICOJSON_NOEXCEPT #if PICOJSON_USE_RVALUE_REFERENCE #define PICOJSON_NOEXCEPT noexcept #else #define PICOJSON_NOEXCEPT throw() #endif #endif // experimental support for int64_t (see README.mkdn for detail) #ifdef PICOJSON_USE_INT64 //#define __STDC_FORMAT_MACROS #include <cerrno> #if __cplusplus >= 201103L #include <cinttypes> #else extern "C" { #include <inttypes.h> } #endif #endif // to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0 #ifndef PICOJSON_USE_LOCALE #define PICOJSON_USE_LOCALE 1 #endif #if PICOJSON_USE_LOCALE extern "C" { #include <locale.h> } #endif #ifndef PICOJSON_ASSERT #define PICOJSON_ASSERT(e) \ do { \ if (!(e)) \ throw std::runtime_error(#e); \ } while (0) #endif #ifdef _MSC_VER #define SNPRINTF _snprintf_s #pragma warning(push) #pragma warning(disable : 4244) // conversion from int to char #pragma warning(disable : 4127) // conditional expression is constant #pragma warning(disable : 4702) // unreachable code #else #define SNPRINTF snprintf #endif namespace picojson { enum { null_type, boolean_type, number_type, string_type, array_type, object_type #ifdef PICOJSON_USE_INT64 , int64_type #endif }; enum { INDENT_WIDTH = 2 }; struct null {}; class value { public: typedef std::vector<value> array; typedef std::map<std::string, value> object; union _storage { bool boolean_; double number_; #ifdef PICOJSON_USE_INT64 int64_t int64_; #endif std::string *string_; array *array_; object *object_; }; protected: int type_; _storage u_; public: value(); value(int type, bool); explicit value(bool b); #ifdef PICOJSON_USE_INT64 explicit value(int64_t i); #endif explicit value(double n); explicit value(const std::string &s); explicit value(const array &a); explicit value(const object &o); #if PICOJSON_USE_RVALUE_REFERENCE explicit value(std::string &&s); explicit value(array &&a); explicit value(object &&o); #endif explicit value(const char *s); value(const char *s, size_t len); ~value(); value(const value &x); value &operator=(const value &x); #if PICOJSON_USE_RVALUE_REFERENCE value(value &&x) PICOJSON_NOEXCEPT; value &operator=(value &&x) PICOJSON_NOEXCEPT; #endif void swap(value &x) PICOJSON_NOEXCEPT; template <typename T> bool is() const; template <typename T> const T &get() const; template <typename T> T &get(); template <typename T> void set(const T &); #if PICOJSON_USE_RVALUE_REFERENCE template <typename T> void set(T &&); #endif bool evaluate_as_boolean() const; const value &get(const size_t idx) const; const value &get(const std::string &key) const; value &get(const size_t idx); value &get(const std::string &key); bool contains(const size_t idx) const; bool contains(const std::string &key) const; std::string to_str() const; template <typename Iter> void serialize(Iter os, bool prettify = false) const; std::string serialize(bool prettify = false) const; private: template <typename T> value(const T *); // intentionally defined to block implicit conversion of pointer to bool template <typename Iter> static void _indent(Iter os, int indent); template <typename Iter> void _serialize(Iter os, int indent) const; std::string _serialize(int indent) const; void clear(); }; typedef value::array array; typedef value::object object; inline value::value() : type_(null_type), u_() { } inline value::value(int type, bool) : type_(type), u_() { switch (type) { #define INIT(p, v) \ case p##type: \ u_.p = v; \ break INIT(boolean_, false); INIT(number_, 0.0); #ifdef PICOJSON_USE_INT64 INIT(int64_, 0); #endif INIT(string_, new std::string()); INIT(array_, new array()); INIT(object_, new object()); #undef INIT default: break; } } inline value::value(bool b) : type_(boolean_type), u_() { u_.boolean_ = b; } #ifdef PICOJSON_USE_INT64 inline value::value(int64_t i) : type_(int64_type), u_() { u_.int64_ = i; } #endif inline value::value(double n) : type_(number_type), u_() { if ( #ifdef _MSC_VER !_finite(n) #elif __cplusplus >= 201103L std::isnan(n) || std::isinf(n) #else isnan(n) || isinf(n) #endif ) { throw std::overflow_error(""); } u_.number_ = n; } inline value::value(const std::string &s) : type_(string_type), u_() { u_.string_ = new std::string(s); } inline value::value(const array &a) : type_(array_type), u_() { u_.array_ = new array(a); } inline value::value(const object &o) : type_(object_type), u_() { u_.object_ = new object(o); } #if PICOJSON_USE_RVALUE_REFERENCE inline value::value(std::string &&s) : type_(string_type), u_() { u_.string_ = new std::string(std::move(s)); } inline value::value(array &&a) : type_(array_type), u_() { u_.array_ = new array(std::move(a)); } inline value::value(object &&o) : type_(object_type), u_() { u_.object_ = new object(std::move(o)); } #endif inline value::value(const char *s) : type_(string_type), u_() { u_.string_ = new std::string(s); } inline value::value(const char *s, size_t len) : type_(string_type), u_() { u_.string_ = new std::string(s, len); } inline void value::clear() { switch (type_) { #define DEINIT(p) \ case p##type: \ delete u_.p; \ break DEINIT(string_); DEINIT(array_); DEINIT(object_); #undef DEINIT default: break; } } inline value::~value() { clear(); } inline value::value(const value &x) : type_(x.type_), u_() { switch (type_) { #define INIT(p, v) \ case p##type: \ u_.p = v; \ break INIT(string_, new std::string(*x.u_.string_)); INIT(array_, new array(*x.u_.array_)); INIT(object_, new object(*x.u_.object_)); #undef INIT default: u_ = x.u_; break; } } inline value &value::operator=(const value &x) { if (this != &x) { value t(x); swap(t); } return *this; } #if PICOJSON_USE_RVALUE_REFERENCE inline value::value(value &&x) PICOJSON_NOEXCEPT : type_(null_type), u_() { swap(x); } inline value &value::operator=(value &&x) PICOJSON_NOEXCEPT { swap(x); return *this; } #endif inline void value::swap(value &x) PICOJSON_NOEXCEPT { std::swap(type_, x.type_); std::swap(u_, x.u_); } #define IS(ctype, jtype) \ template <> inline bool value::is<ctype>() const { \ return type_ == jtype##_type; \ } IS(null, null) IS(bool, boolean) #ifdef PICOJSON_USE_INT64 IS(int64_t, int64) #endif IS(std::string, string) IS(array, array) IS(object, object) #undef IS template <> inline bool value::is<double>() const { return type_ == number_type #ifdef PICOJSON_USE_INT64 || type_ == int64_type #endif ; } #define GET(ctype, var) \ template <> inline const ctype &value::get<ctype>() const { \ PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \ return var; \ } \ template <> inline ctype &value::get<ctype>() { \ PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \ return var; \ } GET(bool, u_.boolean_) GET(std::string, *u_.string_) GET(array, *u_.array_) GET(object, *u_.object_) #ifdef PICOJSON_USE_INT64 GET(double, (type_ == int64_type && (const_cast<value *>(this)->type_ = number_type, (const_cast<value *>(this)->u_.number_ = u_.int64_)), u_.number_)) GET(int64_t, u_.int64_) #else GET(double, u_.number_) #endif #undef GET #define SET(ctype, jtype, setter) \ template <> inline void value::set<ctype>(const ctype &_val) { \ clear(); \ type_ = jtype##_type; \ setter \ } SET(bool, boolean, u_.boolean_ = _val;) SET(std::string, string, u_.string_ = new std::string(_val);) SET(array, array, u_.array_ = new array(_val);) SET(object, object, u_.object_ = new object(_val);) SET(double, number, u_.number_ = _val;) #ifdef PICOJSON_USE_INT64 SET(int64_t, int64, u_.int64_ = _val;) #endif #undef SET #if PICOJSON_USE_RVALUE_REFERENCE #define MOVESET(ctype, jtype, setter) \ template <> inline void value::set<ctype>(ctype && _val) { \ clear(); \ type_ = jtype##_type; \ setter \ } MOVESET(std::string, string, u_.string_ = new std::string(std::move(_val));) MOVESET(array, array, u_.array_ = new array(std::move(_val));) MOVESET(object, object, u_.object_ = new object(std::move(_val));) #undef MOVESET #endif inline bool value::evaluate_as_boolean() const { switch (type_) { case null_type: return false; case boolean_type: return u_.boolean_; case number_type: return u_.number_ != 0; #ifdef PICOJSON_USE_INT64 case int64_type: return u_.int64_ != 0; #endif case string_type: return !u_.string_->empty(); default: return true; } } inline const value &value::get(const size_t idx) const { static value s_null; PICOJSON_ASSERT(is<array>()); return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; } inline value &value::get(const size_t idx) { static value s_null; PICOJSON_ASSERT(is<array>()); return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; } inline const value &value::get(const std::string &key) const { static value s_null; PICOJSON_ASSERT(is<object>()); object::const_iterator i = u_.object_->find(key); return i != u_.object_->end() ? i->second : s_null; } inline value &value::get(const std::string &key) { static value s_null; PICOJSON_ASSERT(is<object>()); object::iterator i = u_.object_->find(key); return i != u_.object_->end() ? i->second : s_null; } inline bool value::contains(const size_t idx) const { PICOJSON_ASSERT(is<array>()); return idx < u_.array_->size(); } inline bool value::contains(const std::string &key) const { PICOJSON_ASSERT(is<object>()); object::const_iterator i = u_.object_->find(key); return i != u_.object_->end(); } inline std::string value::to_str() const { switch (type_) { case null_type: return "null"; case boolean_type: return u_.boolean_ ? "true" : "false"; #ifdef PICOJSON_USE_INT64 case int64_type: { char buf[sizeof("-9223372036854775808")]; SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_); return buf; } #endif case number_type: { char buf[256]; double tmp; SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_); #if PICOJSON_USE_LOCALE char *decimal_point = localeconv()->decimal_point; if (strcmp(decimal_point, ".") != 0) { size_t decimal_point_len = strlen(decimal_point); for (char *p = buf; *p != '\0'; ++p) { if (strncmp(p, decimal_point, decimal_point_len) == 0) { return std::string(buf, p) + "." + (p + decimal_point_len); } } } #endif return buf; } case string_type: return *u_.string_; case array_type: return "array"; case object_type: return "object"; default: PICOJSON_ASSERT(0); #ifdef _MSC_VER __assume(0); #endif } return std::string(); } template <typename Iter> void copy(const std::string &s, Iter oi) { std::copy(s.begin(), s.end(), oi); } template <typename Iter> struct serialize_str_char { Iter oi; void operator()(char c) { switch (c) { #define MAP(val, sym) \ case val: \ copy(sym, oi); \ break MAP('"', "\\\""); MAP('\\', "\\\\"); MAP('/', "\\/"); MAP('\b', "\\b"); MAP('\f', "\\f"); MAP('\n', "\\n"); MAP('\r', "\\r"); MAP('\t', "\\t"); #undef MAP default: if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) { char buf[7]; SNPRINTF(buf, sizeof(buf), "\\u%04x", c & 0xff); copy(buf, buf + 6, oi); } else { *oi++ = c; } break; } } }; template <typename Iter> void serialize_str(const std::string &s, Iter oi) { *oi++ = '"'; serialize_str_char<Iter> process_char = {oi}; std::for_each(s.begin(), s.end(), process_char); *oi++ = '"'; } template <typename Iter> void value::serialize(Iter oi, bool prettify) const { return _serialize(oi, prettify ? 0 : -1); } inline std::string value::serialize(bool prettify) const { return _serialize(prettify ? 0 : -1); } template <typename Iter> void value::_indent(Iter oi, int indent) { *oi++ = '\n'; for (int i = 0; i < indent * INDENT_WIDTH; ++i) { *oi++ = ' '; } } template <typename Iter> void value::_serialize(Iter oi, int indent) const { switch (type_) { case string_type: serialize_str(*u_.string_, oi); break; case array_type: { *oi++ = '['; if (indent != -1) { ++indent; } for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) { if (i != u_.array_->begin()) { *oi++ = ','; } if (indent != -1) { _indent(oi, indent); } i->_serialize(oi, indent); } if (indent != -1) { --indent; if (!u_.array_->empty()) { _indent(oi, indent); } } *oi++ = ']'; break; } case object_type: { *oi++ = '{'; if (indent != -1) { ++indent; } for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) { if (i != u_.object_->begin()) { *oi++ = ','; } if (indent != -1) { _indent(oi, indent); } serialize_str(i->first, oi); *oi++ = ':'; if (indent != -1) { *oi++ = ' '; } i->second._serialize(oi, indent); } if (indent != -1) { --indent; if (!u_.object_->empty()) { _indent(oi, indent); } } *oi++ = '}'; break; } default: copy(to_str(), oi); break; } if (indent == 0) { *oi++ = '\n'; } } inline std::string value::_serialize(int indent) const { std::string s; _serialize(std::back_inserter(s), indent); return s; } template <typename Iter> class input { protected: Iter cur_, end_; bool consumed_; int line_; public: input(const Iter &first, const Iter &last) : cur_(first), end_(last), consumed_(false), line_(1) { } int getc() { if (consumed_) { if (*cur_ == '\n') { ++line_; } ++cur_; } if (cur_ == end_) { consumed_ = false; return -1; } consumed_ = true; return *cur_ & 0xff; } void ungetc() { consumed_ = false; } Iter cur() const { if (consumed_) { input<Iter> *self = const_cast<input<Iter> *>(this); self->consumed_ = false; ++self->cur_; } return cur_; } int line() const { return line_; } void skip_ws() { while (1) { int ch = getc(); if (!(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { ungetc(); break; } } } bool picojson_expect(const int expected) { skip_ws(); if (getc() != expected) { ungetc(); return false; } return true; } bool match(const std::string &pattern) { for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) { if (getc() != *pi) { ungetc(); return false; } } return true; } }; template <typename Iter> inline int _parse_quadhex(input<Iter> &in) { int uni_ch = 0, hex; for (int i = 0; i < 4; i++) { if ((hex = in.getc()) == -1) { return -1; } if ('0' <= hex && hex <= '9') { hex -= '0'; } else if ('A' <= hex && hex <= 'F') { hex -= 'A' - 0xa; } else if ('a' <= hex && hex <= 'f') { hex -= 'a' - 0xa; } else { in.ungetc(); return -1; } uni_ch = uni_ch * 16 + hex; } return uni_ch; } template <typename String, typename Iter> inline bool _parse_codepoint(String &out, input<Iter> &in) { int uni_ch; if ((uni_ch = _parse_quadhex(in)) == -1) { return false; } if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { if (0xdc00 <= uni_ch) { // a second 16-bit of a surrogate pair appeared return false; } // first 16-bit of surrogate pair, get the next one if (in.getc() != '\\' || in.getc() != 'u') { in.ungetc(); return false; } int second = _parse_quadhex(in); if (!(0xdc00 <= second && second <= 0xdfff)) { return false; } uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); uni_ch += 0x10000; } if (uni_ch < 0x80) { out.push_back(static_cast<char>(uni_ch)); } else { if (uni_ch < 0x800) { out.push_back(static_cast<char>(0xc0 | (uni_ch >> 6))); } else { if (uni_ch < 0x10000) { out.push_back(static_cast<char>(0xe0 | (uni_ch >> 12))); } else { out.push_back(static_cast<char>(0xf0 | (uni_ch >> 18))); out.push_back(static_cast<char>(0x80 | ((uni_ch >> 12) & 0x3f))); } out.push_back(static_cast<char>(0x80 | ((uni_ch >> 6) & 0x3f))); } out.push_back(static_cast<char>(0x80 | (uni_ch & 0x3f))); } return true; } template <typename String, typename Iter> inline bool _parse_string(String &out, input<Iter> &in) { while (1) { int ch = in.getc(); if (ch < ' ') { in.ungetc(); return false; } else if (ch == '"') { return true; } else if (ch == '\\') { if ((ch = in.getc()) == -1) { return false; } switch (ch) { #define MAP(sym, val) \ case sym: \ out.push_back(val); \ break MAP('"', '\"'); MAP('\\', '\\'); MAP('/', '/'); MAP('b', '\b'); MAP('f', '\f'); MAP('n', '\n'); MAP('r', '\r'); MAP('t', '\t'); #undef MAP case 'u': if (!_parse_codepoint(out, in)) { return false; } break; default: return false; } } else { out.push_back(static_cast<char>(ch)); } } return false; } template <typename Context, typename Iter> inline bool _parse_array(Context &ctx, input<Iter> &in) { if (!ctx.parse_array_start()) { return false; } size_t idx = 0; if (in.picojson_expect(']')) { return ctx.parse_array_stop(idx); } do { if (!ctx.parse_array_item(in, idx)) { return false; } idx++; } while (in.picojson_expect(',')); return in.picojson_expect(']') && ctx.parse_array_stop(idx); } template <typename Context, typename Iter> inline bool _parse_object(Context &ctx, input<Iter> &in) { if (!ctx.parse_object_start()) { return false; } if (in.picojson_expect('}')) { return true; } do { std::string key; if (!in.picojson_expect('"') || !_parse_string(key, in) || !in.picojson_expect(':')) { return false; } if (!ctx.parse_object_item(in, key)) { return false; } } while (in.picojson_expect(',')); return in.picojson_expect('}'); } template <typename Iter> inline std::string _parse_number(input<Iter> &in) { std::string num_str; while (1) { int ch = in.getc(); if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') { num_str.push_back(static_cast<char>(ch)); } else if (ch == '.') { #if PICOJSON_USE_LOCALE num_str += localeconv()->decimal_point; #else num_str.push_back('.'); #endif } else { in.ungetc(); break; } } return num_str; } template <typename Context, typename Iter> inline bool _parse(Context &ctx, input<Iter> &in) { in.skip_ws(); int ch = in.getc(); switch (ch) { #define IS(ch, text, op) \ case ch: \ if (in.match(text) && op) { \ return true; \ } else { \ return false; \ } IS('n', "ull", ctx.set_null()); IS('f', "alse", ctx.set_bool(false)); IS('t', "rue", ctx.set_bool(true)); #undef IS case '"': return ctx.parse_string(in); case '[': return _parse_array(ctx, in); case '{': return _parse_object(ctx, in); default: if (('0' <= ch && ch <= '9') || ch == '-') { double f; char *endp; in.ungetc(); std::string num_str(_parse_number(in)); if (num_str.empty()) { return false; } #ifdef PICOJSON_USE_INT64 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-type-limit-compare" { errno = 0; intmax_t ival = strtoimax(num_str.c_str(), &endp, 10); if (errno == 0 && std::numeric_limits<int64_t>::min() <= ival && ival <= std::numeric_limits<int64_t>::max() && endp == num_str.c_str() + num_str.size()) { ctx.set_int64(ival); return true; } } #pragma clang diagnostic pop #endif f = strtod(num_str.c_str(), &endp); if (endp == num_str.c_str() + num_str.size()) { ctx.set_number(f); return true; } return false; } break; } in.ungetc(); return false; } class deny_parse_context { public: bool set_null() { return false; } bool set_bool(bool) { return false; } #ifdef PICOJSON_USE_INT64 bool set_int64(int64_t) { return false; } #endif bool set_number(double) { return false; } template <typename Iter> bool parse_string(input<Iter> &) { return false; } bool parse_array_start() { return false; } template <typename Iter> bool parse_array_item(input<Iter> &, size_t) { return false; } bool parse_array_stop(size_t) { return false; } bool parse_object_start() { return false; } template <typename Iter> bool parse_object_item(input<Iter> &, const std::string &) { return false; } }; class default_parse_context { protected: value *out_; public: default_parse_context(value *out) : out_(out) { } bool set_null() { *out_ = value(); return true; } bool set_bool(bool b) { *out_ = value(b); return true; } #ifdef PICOJSON_USE_INT64 bool set_int64(int64_t i) { *out_ = value(i); return true; } #endif bool set_number(double f) { *out_ = value(f); return true; } template <typename Iter> bool parse_string(input<Iter> &in) { *out_ = value(string_type, false); return _parse_string(out_->get<std::string>(), in); } bool parse_array_start() { *out_ = value(array_type, false); return true; } template <typename Iter> bool parse_array_item(input<Iter> &in, size_t) { array &a = out_->get<array>(); a.push_back(value()); default_parse_context ctx(&a.back()); return _parse(ctx, in); } bool parse_array_stop(size_t) { return true; } bool parse_object_start() { *out_ = value(object_type, false); return true; } template <typename Iter> bool parse_object_item(input<Iter> &in, const std::string &key) { object &o = out_->get<object>(); default_parse_context ctx(&o[key]); return _parse(ctx, in); } private: default_parse_context(const default_parse_context &); default_parse_context &operator=(const default_parse_context &); }; class null_parse_context { public: struct dummy_str { void push_back(int) { } }; public: null_parse_context() { } bool set_null() { return true; } bool set_bool(bool) { return true; } #ifdef PICOJSON_USE_INT64 bool set_int64(int64_t) { return true; } #endif bool set_number(double) { return true; } template <typename Iter> bool parse_string(input<Iter> &in) { dummy_str s; return _parse_string(s, in); } bool parse_array_start() { return true; } template <typename Iter> bool parse_array_item(input<Iter> &in, size_t) { return _parse(*this, in); } bool parse_array_stop(size_t) { return true; } bool parse_object_start() { return true; } template <typename Iter> bool parse_object_item(input<Iter> &in, const std::string &) { return _parse(*this, in); } private: null_parse_context(const null_parse_context &); null_parse_context &operator=(const null_parse_context &); }; // obsolete, use the version below template <typename Iter> inline std::string parse(value &out, Iter &pos, const Iter &last) { std::string err; pos = parse(out, pos, last, &err); return err; } template <typename Context, typename Iter> inline Iter _parse(Context &ctx, const Iter &first, const Iter &last, std::string *err) { input<Iter> in(first, last); if (!_parse(ctx, in) && err != NULL) { char buf[64]; SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); *err = buf; while (1) { int ch = in.getc(); if (ch == -1 || ch == '\n') { break; } else if (ch >= ' ') { err->push_back(static_cast<char>(ch)); } } } return in.cur(); } template <typename Iter> inline Iter parse(value &out, const Iter &first, const Iter &last, std::string *err) { default_parse_context ctx(&out); return _parse(ctx, first, last, err); } inline std::string parse(value &out, const std::string &s) { std::string err; parse(out, s.begin(), s.end(), &err); return err; } inline std::string parse(value &out, std::istream &is) { std::string err; parse(out, std::istreambuf_iterator<char>(is.rdbuf()), std::istreambuf_iterator<char>(), &err); return err; } template <typename T> struct last_error_t { static std::string s; }; template <typename T> std::string last_error_t<T>::s; inline void set_last_error(const std::string &s) { last_error_t<bool>::s = s; } inline const std::string &get_last_error() { return last_error_t<bool>::s; } inline bool operator==(const value &x, const value &y) { if (x.is<null>()) return y.is<null>(); #define PICOJSON_CMP(type) \ if (x.is<type>()) \ return y.is<type>() && x.get<type>() == y.get<type>() PICOJSON_CMP(bool); PICOJSON_CMP(double); PICOJSON_CMP(std::string); PICOJSON_CMP(array); PICOJSON_CMP(object); #undef PICOJSON_CMP PICOJSON_ASSERT(0); #ifdef _MSC_VER __assume(0); #endif return false; } inline bool operator!=(const value &x, const value &y) { return !(x == y); } } #if !PICOJSON_USE_RVALUE_REFERENCE namespace std { template <> inline void swap(picojson::value &x, picojson::value &y) { x.swap(y); } } #endif inline std::istream &operator>>(std::istream &is, picojson::value &x) { picojson::set_last_error(std::string()); const std::string err(picojson::parse(x, is)); if (!err.empty()) { picojson::set_last_error(err); is.setstate(std::ios::failbit); } return is; } inline std::ostream &operator<<(std::ostream &os, const picojson::value &x) { x.serialize(std::ostream_iterator<char>(os)); return os; } #ifdef _MSC_VER #pragma warning(pop) #endif #endif
33,546
27.477929
132
h
null
ceph-main/src/rgw/services/svc_bi.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" class RGWBucketInfo; struct RGWBucketEnt; class RGWSI_BucketIndex : public RGWServiceInstance { public: RGWSI_BucketIndex(CephContext *cct) : RGWServiceInstance(cct) {} virtual ~RGWSI_BucketIndex() {} virtual int init_index(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout) = 0; virtual int clean_index(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout) = 0; virtual int read_stats(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWBucketEnt *stats, optional_yield y) = 0; virtual int handle_overwrite(const DoutPrefixProvider *dpp, const RGWBucketInfo& info, const RGWBucketInfo& orig_info, optional_yield y) = 0; };
1,402
30.177778
144
h
null
ceph-main/src/rgw/services/svc_bi_rados.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_bi_rados.h" #include "svc_bilog_rados.h" #include "svc_zone.h" #include "rgw_bucket.h" #include "rgw_zone.h" #include "rgw_datalog.h" #include "cls/rgw/cls_rgw_client.h" #define dout_subsys ceph_subsys_rgw using namespace std; static string dir_oid_prefix = ".dir."; RGWSI_BucketIndex_RADOS::RGWSI_BucketIndex_RADOS(CephContext *cct) : RGWSI_BucketIndex(cct) { } void RGWSI_BucketIndex_RADOS::init(RGWSI_Zone *zone_svc, RGWSI_RADOS *rados_svc, RGWSI_BILog_RADOS *bilog_svc, RGWDataChangesLog *datalog_rados_svc) { svc.zone = zone_svc; svc.rados = rados_svc; svc.bilog = bilog_svc; svc.datalog_rados = datalog_rados_svc; } int RGWSI_BucketIndex_RADOS::open_pool(const DoutPrefixProvider *dpp, const rgw_pool& pool, RGWSI_RADOS::Pool *index_pool, bool mostly_omap) { *index_pool = svc.rados->pool(pool); return index_pool->open(dpp, RGWSI_RADOS::OpenParams() .set_mostly_omap(mostly_omap)); } int RGWSI_BucketIndex_RADOS::open_bucket_index_pool(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWSI_RADOS::Pool *index_pool) { const rgw_pool& explicit_pool = bucket_info.bucket.explicit_placement.index_pool; if (!explicit_pool.empty()) { return open_pool(dpp, explicit_pool, index_pool, false); } auto& zonegroup = svc.zone->get_zonegroup(); auto& zone_params = svc.zone->get_zone_params(); const rgw_placement_rule *rule = &bucket_info.placement_rule; if (rule->empty()) { rule = &zonegroup.default_placement; } auto iter = zone_params.placement_pools.find(rule->name); if (iter == zone_params.placement_pools.end()) { ldpp_dout(dpp, 0) << "could not find placement rule " << *rule << " within zonegroup " << dendl; return -EINVAL; } int r = open_pool(dpp, iter->second.index_pool, index_pool, true); if (r < 0) return r; return 0; } int RGWSI_BucketIndex_RADOS::open_bucket_index_base(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWSI_RADOS::Pool *index_pool, string *bucket_oid_base) { const rgw_bucket& bucket = bucket_info.bucket; int r = open_bucket_index_pool(dpp, bucket_info, index_pool); if (r < 0) return r; if (bucket.bucket_id.empty()) { ldpp_dout(dpp, 0) << "ERROR: empty bucket_id for bucket operation" << dendl; return -EIO; } *bucket_oid_base = dir_oid_prefix; bucket_oid_base->append(bucket.bucket_id); return 0; } int RGWSI_BucketIndex_RADOS::open_bucket_index(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWSI_RADOS::Pool *index_pool, string *bucket_oid) { const rgw_bucket& bucket = bucket_info.bucket; int r = open_bucket_index_pool(dpp, bucket_info, index_pool); if (r < 0) { ldpp_dout(dpp, 20) << __func__ << ": open_bucket_index_pool() returned " << r << dendl; return r; } if (bucket.bucket_id.empty()) { ldpp_dout(dpp, 0) << "ERROR: empty bucket id for bucket operation" << dendl; return -EIO; } *bucket_oid = dir_oid_prefix; bucket_oid->append(bucket.bucket_id); return 0; } static char bucket_obj_with_generation(char *buf, size_t len, const string& bucket_oid_base, uint64_t gen_id, uint32_t shard_id) { return snprintf(buf, len, "%s.%" PRIu64 ".%d", bucket_oid_base.c_str(), gen_id, shard_id); } static char bucket_obj_without_generation(char *buf, size_t len, const string& bucket_oid_base, uint32_t shard_id) { return snprintf(buf, len, "%s.%d", bucket_oid_base.c_str(), shard_id); } static void get_bucket_index_objects(const string& bucket_oid_base, uint32_t num_shards, uint64_t gen_id, map<int, string> *_bucket_objects, int shard_id = -1) { auto& bucket_objects = *_bucket_objects; if (!num_shards) { bucket_objects[0] = bucket_oid_base; } else { char buf[bucket_oid_base.size() + 64]; if (shard_id < 0) { for (uint32_t i = 0; i < num_shards; ++i) { if (gen_id) { bucket_obj_with_generation(buf, sizeof(buf), bucket_oid_base, gen_id, i); } else { bucket_obj_without_generation(buf, sizeof(buf), bucket_oid_base, i); } bucket_objects[i] = buf; } } else { if (std::cmp_greater(shard_id, num_shards)) { return; } else { if (gen_id) { bucket_obj_with_generation(buf, sizeof(buf), bucket_oid_base, gen_id, shard_id); } else { // for backward compatibility, gen_id(0) will not be added in the object name bucket_obj_without_generation(buf, sizeof(buf), bucket_oid_base, shard_id); } bucket_objects[shard_id] = buf; } } } } static void get_bucket_instance_ids(const RGWBucketInfo& bucket_info, int num_shards, int shard_id, map<int, string> *result) { const rgw_bucket& bucket = bucket_info.bucket; string plain_id = bucket.name + ":" + bucket.bucket_id; if (!num_shards) { (*result)[0] = plain_id; } else { char buf[16]; if (shard_id < 0) { for (int i = 0; i < num_shards; ++i) { snprintf(buf, sizeof(buf), ":%d", i); (*result)[i] = plain_id + buf; } } else { if (shard_id > num_shards) { return; } snprintf(buf, sizeof(buf), ":%d", shard_id); (*result)[shard_id] = plain_id + buf; } } } int RGWSI_BucketIndex_RADOS::open_bucket_index(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, std::optional<int> _shard_id, const rgw::bucket_index_layout_generation& idx_layout, RGWSI_RADOS::Pool *index_pool, map<int, string> *bucket_objs, map<int, string> *bucket_instance_ids) { int shard_id = _shard_id.value_or(-1); string bucket_oid_base; int ret = open_bucket_index_base(dpp, bucket_info, index_pool, &bucket_oid_base); if (ret < 0) { ldpp_dout(dpp, 20) << __func__ << ": open_bucket_index_pool() returned " << ret << dendl; return ret; } get_bucket_index_objects(bucket_oid_base, idx_layout.layout.normal.num_shards, idx_layout.gen, bucket_objs, shard_id); if (bucket_instance_ids) { get_bucket_instance_ids(bucket_info, idx_layout.layout.normal.num_shards, shard_id, bucket_instance_ids); } return 0; } void RGWSI_BucketIndex_RADOS::get_bucket_index_object( const std::string& bucket_oid_base, const rgw::bucket_index_normal_layout& normal, uint64_t gen_id, int shard_id, std::string* bucket_obj) { if (!normal.num_shards) { // By default with no sharding, we use the bucket oid as itself (*bucket_obj) = bucket_oid_base; } else { char buf[bucket_oid_base.size() + 64]; if (gen_id) { bucket_obj_with_generation(buf, sizeof(buf), bucket_oid_base, gen_id, shard_id); (*bucket_obj) = buf; ldout(cct, 10) << "bucket_obj is " << (*bucket_obj) << dendl; } else { // for backward compatibility, gen_id(0) will not be added in the object name bucket_obj_without_generation(buf, sizeof(buf), bucket_oid_base, shard_id); (*bucket_obj) = buf; } } } int RGWSI_BucketIndex_RADOS::get_bucket_index_object( const std::string& bucket_oid_base, const rgw::bucket_index_normal_layout& normal, uint64_t gen_id, const std::string& obj_key, std::string* bucket_obj, int* shard_id) { int r = 0; switch (normal.hash_type) { case rgw::BucketHashType::Mod: if (!normal.num_shards) { // By default with no sharding, we use the bucket oid as itself (*bucket_obj) = bucket_oid_base; if (shard_id) { *shard_id = -1; } } else { uint32_t sid = bucket_shard_index(obj_key, normal.num_shards); char buf[bucket_oid_base.size() + 64]; if (gen_id) { bucket_obj_with_generation(buf, sizeof(buf), bucket_oid_base, gen_id, sid); } else { bucket_obj_without_generation(buf, sizeof(buf), bucket_oid_base, sid); } (*bucket_obj) = buf; if (shard_id) { *shard_id = (int)sid; } } break; default: r = -ENOTSUP; } return r; } int RGWSI_BucketIndex_RADOS::open_bucket_index_shard(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const string& obj_key, RGWSI_RADOS::Obj *bucket_obj, int *shard_id) { string bucket_oid_base; RGWSI_RADOS::Pool pool; int ret = open_bucket_index_base(dpp, bucket_info, &pool, &bucket_oid_base); if (ret < 0) { ldpp_dout(dpp, 20) << __func__ << ": open_bucket_index_pool() returned " << ret << dendl; return ret; } string oid; const auto& current_index = bucket_info.layout.current_index; ret = get_bucket_index_object(bucket_oid_base, current_index.layout.normal, current_index.gen, obj_key, &oid, shard_id); if (ret < 0) { ldpp_dout(dpp, 10) << "get_bucket_index_object() returned ret=" << ret << dendl; return ret; } *bucket_obj = svc.rados->obj(pool, oid); return 0; } int RGWSI_BucketIndex_RADOS::open_bucket_index_shard(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& index, int shard_id, RGWSI_RADOS::Obj *bucket_obj) { RGWSI_RADOS::Pool index_pool; string bucket_oid_base; int ret = open_bucket_index_base(dpp, bucket_info, &index_pool, &bucket_oid_base); if (ret < 0) { ldpp_dout(dpp, 20) << __func__ << ": open_bucket_index_pool() returned " << ret << dendl; return ret; } string oid; get_bucket_index_object(bucket_oid_base, index.layout.normal, index.gen, shard_id, &oid); *bucket_obj = svc.rados->obj(index_pool, oid); return 0; } int RGWSI_BucketIndex_RADOS::cls_bucket_head(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout, int shard_id, vector<rgw_bucket_dir_header> *headers, map<int, string> *bucket_instance_ids, optional_yield y) { RGWSI_RADOS::Pool index_pool; map<int, string> oids; int r = open_bucket_index(dpp, bucket_info, shard_id, idx_layout, &index_pool, &oids, bucket_instance_ids); if (r < 0) return r; map<int, struct rgw_cls_list_ret> list_results; for (auto& iter : oids) { list_results.emplace(iter.first, rgw_cls_list_ret()); } r = CLSRGWIssueGetDirHeader(index_pool.ioctx(), oids, list_results, cct->_conf->rgw_bucket_index_max_aio)(); if (r < 0) return r; map<int, struct rgw_cls_list_ret>::iterator iter = list_results.begin(); for(; iter != list_results.end(); ++iter) { headers->push_back(std::move(iter->second.dir.header)); } return 0; } int RGWSI_BucketIndex_RADOS::init_index(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout) { RGWSI_RADOS::Pool index_pool; string dir_oid = dir_oid_prefix; int r = open_bucket_index_pool(dpp, bucket_info, &index_pool); if (r < 0) { return r; } dir_oid.append(bucket_info.bucket.bucket_id); map<int, string> bucket_objs; get_bucket_index_objects(dir_oid, idx_layout.layout.normal.num_shards, idx_layout.gen, &bucket_objs); return CLSRGWIssueBucketIndexInit(index_pool.ioctx(), bucket_objs, cct->_conf->rgw_bucket_index_max_aio)(); } int RGWSI_BucketIndex_RADOS::clean_index(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout) { RGWSI_RADOS::Pool index_pool; std::string dir_oid = dir_oid_prefix; int r = open_bucket_index_pool(dpp, bucket_info, &index_pool); if (r < 0) { return r; } dir_oid.append(bucket_info.bucket.bucket_id); std::map<int, std::string> bucket_objs; get_bucket_index_objects(dir_oid, idx_layout.layout.normal.num_shards, idx_layout.gen, &bucket_objs); return CLSRGWIssueBucketIndexClean(index_pool.ioctx(), bucket_objs, cct->_conf->rgw_bucket_index_max_aio)(); } int RGWSI_BucketIndex_RADOS::read_stats(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWBucketEnt *result, optional_yield y) { vector<rgw_bucket_dir_header> headers; result->bucket = bucket_info.bucket; int r = cls_bucket_head(dpp, bucket_info, bucket_info.layout.current_index, RGW_NO_SHARD, &headers, nullptr, y); if (r < 0) { return r; } result->count = 0; result->size = 0; result->size_rounded = 0; auto hiter = headers.begin(); for (; hiter != headers.end(); ++hiter) { RGWObjCategory category = RGWObjCategory::Main; auto iter = (hiter->stats).find(category); if (iter != hiter->stats.end()) { struct rgw_bucket_category_stats& stats = iter->second; result->count += stats.num_entries; result->size += stats.total_size; result->size_rounded += stats.total_size_rounded; } } result->placement_rule = std::move(bucket_info.placement_rule); return 0; } int RGWSI_BucketIndex_RADOS::get_reshard_status(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, list<cls_rgw_bucket_instance_entry> *status) { map<int, string> bucket_objs; RGWSI_RADOS::Pool index_pool; int r = open_bucket_index(dpp, bucket_info, std::nullopt, bucket_info.layout.current_index, &index_pool, &bucket_objs, nullptr); if (r < 0) { return r; } for (auto i : bucket_objs) { cls_rgw_bucket_instance_entry entry; int ret = cls_rgw_get_bucket_resharding(index_pool.ioctx(), i.second, &entry); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, -1) << "ERROR: " << __func__ << ": cls_rgw_get_bucket_resharding() returned ret=" << ret << dendl; return ret; } status->push_back(entry); } return 0; } int RGWSI_BucketIndex_RADOS::handle_overwrite(const DoutPrefixProvider *dpp, const RGWBucketInfo& info, const RGWBucketInfo& orig_info, optional_yield y) { bool new_sync_enabled = info.datasync_flag_enabled(); bool old_sync_enabled = orig_info.datasync_flag_enabled(); if (old_sync_enabled == new_sync_enabled) { return 0; // datasync flag didn't change } if (info.layout.logs.empty()) { return 0; // no bilog } const auto& bilog = info.layout.logs.back(); if (bilog.layout.type != rgw::BucketLogType::InIndex) { return -ENOTSUP; } const int shards_num = rgw::num_shards(bilog.layout.in_index); int ret; if (!new_sync_enabled) { ret = svc.bilog->log_stop(dpp, info, bilog, -1); } else { ret = svc.bilog->log_start(dpp, info, bilog, -1); } if (ret < 0) { ldpp_dout(dpp, -1) << "ERROR: failed writing bilog (bucket=" << info.bucket << "); ret=" << ret << dendl; return ret; } for (int i = 0; i < shards_num; ++i) { ret = svc.datalog_rados->add_entry(dpp, info, bilog, i, y); if (ret < 0) { ldpp_dout(dpp, -1) << "ERROR: failed writing data log (info.bucket=" << info.bucket << ", shard_id=" << i << ")" << dendl; } // datalog error is not fatal } return 0; }
17,189
32.705882
157
cc
null
ceph-main/src/rgw/services/svc_bi_rados.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_datalog.h" #include "rgw_service.h" #include "rgw_tools.h" #include "svc_bi.h" #include "svc_rados.h" #include "svc_tier_rados.h" struct rgw_bucket_dir_header; class RGWSI_BILog_RADOS; #define RGW_NO_SHARD -1 #define RGW_SHARDS_PRIME_0 7877 #define RGW_SHARDS_PRIME_1 65521 /* * Defined Bucket Index Namespaces */ #define RGW_OBJ_NS_MULTIPART "multipart" #define RGW_OBJ_NS_SHADOW "shadow" class RGWSI_BucketIndex_RADOS : public RGWSI_BucketIndex { friend class RGWSI_BILog_RADOS; int open_pool(const DoutPrefixProvider *dpp, const rgw_pool& pool, RGWSI_RADOS::Pool *index_pool, bool mostly_omap); int open_bucket_index_pool(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWSI_RADOS::Pool *index_pool); int open_bucket_index_base(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWSI_RADOS::Pool *index_pool, std::string *bucket_oid_base); // return the index oid for the given shard id void get_bucket_index_object(const std::string& bucket_oid_base, const rgw::bucket_index_normal_layout& normal, uint64_t gen_id, int shard_id, std::string* bucket_obj); // return the index oid and shard id for the given object name int get_bucket_index_object(const std::string& bucket_oid_base, const rgw::bucket_index_normal_layout& normal, uint64_t gen_id, const std::string& obj_key, std::string* bucket_obj, int* shard_id); int cls_bucket_head(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout, int shard_id, std::vector<rgw_bucket_dir_header> *headers, std::map<int, std::string> *bucket_instance_ids, optional_yield y); public: struct Svc { RGWSI_Zone *zone{nullptr}; RGWSI_RADOS *rados{nullptr}; RGWSI_BILog_RADOS *bilog{nullptr}; RGWDataChangesLog *datalog_rados{nullptr}; } svc; RGWSI_BucketIndex_RADOS(CephContext *cct); void init(RGWSI_Zone *zone_svc, RGWSI_RADOS *rados_svc, RGWSI_BILog_RADOS *bilog_svc, RGWDataChangesLog *datalog_rados_svc); static int shards_max() { return RGW_SHARDS_PRIME_1; } static int shard_id(const std::string& key, int max_shards) { return rgw_shard_id(key, max_shards); } static uint32_t bucket_shard_index(const std::string& key, int num_shards) { uint32_t sid = ceph_str_hash_linux(key.c_str(), key.size()); uint32_t sid2 = sid ^ ((sid & 0xFF) << 24); return rgw_shards_mod(sid2, num_shards); } static uint32_t bucket_shard_index(const rgw_obj_key& obj_key, int num_shards) { std::string sharding_key; if (obj_key.ns == RGW_OBJ_NS_MULTIPART) { RGWMPObj mp; mp.from_meta(obj_key.name); sharding_key = mp.get_key(); } else { sharding_key = obj_key.name; } return bucket_shard_index(sharding_key, num_shards); } int init_index(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info,const rgw::bucket_index_layout_generation& idx_layout) override; int clean_index(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& idx_layout) override; /* RADOS specific */ int read_stats(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWBucketEnt *stats, optional_yield y) override; int get_reshard_status(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, std::list<cls_rgw_bucket_instance_entry> *status); int handle_overwrite(const DoutPrefixProvider *dpp, const RGWBucketInfo& info, const RGWBucketInfo& orig_info, optional_yield y) override; int open_bucket_index_shard(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const std::string& obj_key, RGWSI_RADOS::Obj *bucket_obj, int *shard_id); int open_bucket_index_shard(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_index_layout_generation& index, int shard_id, RGWSI_RADOS::Obj *bucket_obj); int open_bucket_index(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, RGWSI_RADOS::Pool *index_pool, std::string *bucket_oid); int open_bucket_index(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, std::optional<int> shard_id, const rgw::bucket_index_layout_generation& idx_layout, RGWSI_RADOS::Pool *index_pool, std::map<int, std::string> *bucket_objs, std::map<int, std::string> *bucket_instance_ids); };
5,875
34.185629
141
h
null
ceph-main/src/rgw/services/svc_bilog_rados.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_bilog_rados.h" #include "svc_bi_rados.h" #include "cls/rgw/cls_rgw_client.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_BILog_RADOS::RGWSI_BILog_RADOS(CephContext *cct) : RGWServiceInstance(cct) { } void RGWSI_BILog_RADOS::init(RGWSI_BucketIndex_RADOS *bi_rados_svc) { svc.bi = bi_rados_svc; } int RGWSI_BILog_RADOS::log_trim(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id, std::string_view start_marker, std::string_view end_marker) { RGWSI_RADOS::Pool index_pool; map<int, string> bucket_objs; BucketIndexShardsManager start_marker_mgr; BucketIndexShardsManager end_marker_mgr; const auto& current_index = rgw::log_to_index_layout(log_layout); int r = svc.bi->open_bucket_index(dpp, bucket_info, shard_id, current_index, &index_pool, &bucket_objs, nullptr); if (r < 0) { return r; } r = start_marker_mgr.from_string(start_marker, shard_id); if (r < 0) { return r; } r = end_marker_mgr.from_string(end_marker, shard_id); if (r < 0) { return r; } return CLSRGWIssueBILogTrim(index_pool.ioctx(), start_marker_mgr, end_marker_mgr, bucket_objs, cct->_conf->rgw_bucket_index_max_aio)(); } int RGWSI_BILog_RADOS::log_start(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id) { RGWSI_RADOS::Pool index_pool; map<int, string> bucket_objs; const auto& current_index = rgw::log_to_index_layout(log_layout); int r = svc.bi->open_bucket_index(dpp, bucket_info, shard_id, current_index, &index_pool, &bucket_objs, nullptr); if (r < 0) return r; return CLSRGWIssueResyncBucketBILog(index_pool.ioctx(), bucket_objs, cct->_conf->rgw_bucket_index_max_aio)(); } int RGWSI_BILog_RADOS::log_stop(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id) { RGWSI_RADOS::Pool index_pool; map<int, string> bucket_objs; const auto& current_index = rgw::log_to_index_layout(log_layout); int r = svc.bi->open_bucket_index(dpp, bucket_info, shard_id, current_index, &index_pool, &bucket_objs, nullptr); if (r < 0) return r; return CLSRGWIssueBucketBILogStop(index_pool.ioctx(), bucket_objs, cct->_conf->rgw_bucket_index_max_aio)(); } static void build_bucket_index_marker(const string& shard_id_str, const string& shard_marker, string *marker) { if (marker) { *marker = shard_id_str; marker->append(BucketIndexShardsManager::KEY_VALUE_SEPARATOR); marker->append(shard_marker); } } int RGWSI_BILog_RADOS::log_list(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id, string& marker, uint32_t max, std::list<rgw_bi_log_entry>& result, bool *truncated) { ldpp_dout(dpp, 20) << __func__ << ": " << bucket_info.bucket << " marker " << marker << " shard_id=" << shard_id << " max " << max << dendl; result.clear(); RGWSI_RADOS::Pool index_pool; map<int, string> oids; map<int, cls_rgw_bi_log_list_ret> bi_log_lists; const auto& current_index = rgw::log_to_index_layout(log_layout); int r = svc.bi->open_bucket_index(dpp, bucket_info, shard_id, current_index, &index_pool, &oids, nullptr); if (r < 0) return r; BucketIndexShardsManager marker_mgr; bool has_shards = (oids.size() > 1 || shard_id >= 0); // If there are multiple shards for the bucket index object, the marker // should have the pattern '{shard_id_1}#{shard_marker_1},{shard_id_2}# // {shard_marker_2}...', if there is no sharding, the bi_log_list should // only contain one record, and the key is the bucket instance id. r = marker_mgr.from_string(marker, shard_id); if (r < 0) return r; r = CLSRGWIssueBILogList(index_pool.ioctx(), marker_mgr, max, oids, bi_log_lists, cct->_conf->rgw_bucket_index_max_aio)(); if (r < 0) return r; map<int, list<rgw_bi_log_entry>::iterator> vcurrents; map<int, list<rgw_bi_log_entry>::iterator> vends; if (truncated) { *truncated = false; } map<int, cls_rgw_bi_log_list_ret>::iterator miter = bi_log_lists.begin(); for (; miter != bi_log_lists.end(); ++miter) { int shard_id = miter->first; vcurrents[shard_id] = miter->second.entries.begin(); vends[shard_id] = miter->second.entries.end(); if (truncated) { *truncated = (*truncated || miter->second.truncated); } } size_t total = 0; bool has_more = true; map<int, list<rgw_bi_log_entry>::iterator>::iterator viter; map<int, list<rgw_bi_log_entry>::iterator>::iterator eiter; while (total < max && has_more) { has_more = false; viter = vcurrents.begin(); eiter = vends.begin(); for (; total < max && viter != vcurrents.end(); ++viter, ++eiter) { assert (eiter != vends.end()); int shard_id = viter->first; list<rgw_bi_log_entry>::iterator& liter = viter->second; if (liter == eiter->second){ continue; } rgw_bi_log_entry& entry = *(liter); if (has_shards) { char buf[16]; snprintf(buf, sizeof(buf), "%d", shard_id); string tmp_id; build_bucket_index_marker(buf, entry.id, &tmp_id); entry.id.swap(tmp_id); } marker_mgr.add(shard_id, entry.id); result.push_back(entry); total++; has_more = true; ++liter; } } if (truncated) { for (viter = vcurrents.begin(), eiter = vends.begin(); viter != vcurrents.end(); ++viter, ++eiter) { assert (eiter != vends.end()); *truncated = (*truncated || (viter->second != eiter->second)); } } // Refresh marker, if there are multiple shards, the output will look like // '{shard_oid_1}#{shard_marker_1},{shard_oid_2}#{shard_marker_2}...', // if there is no sharding, the simply marker (without oid) is returned if (has_shards) { marker_mgr.to_string(&marker); } else { if (!result.empty()) { marker = result.rbegin()->id; } } return 0; } int RGWSI_BILog_RADOS::get_log_status(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id, map<int, string> *markers, optional_yield y) { vector<rgw_bucket_dir_header> headers; map<int, string> bucket_instance_ids; const auto& current_index = rgw::log_to_index_layout(log_layout); int r = svc.bi->cls_bucket_head(dpp, bucket_info, current_index, shard_id, &headers, &bucket_instance_ids, y); if (r < 0) return r; ceph_assert(headers.size() == bucket_instance_ids.size()); auto iter = headers.begin(); map<int, string>::iterator viter = bucket_instance_ids.begin(); for(; iter != headers.end(); ++iter, ++viter) { if (shard_id >= 0) { (*markers)[shard_id] = iter->max_marker; } else { (*markers)[viter->first] = iter->max_marker; } } return 0; }
7,333
32.18552
164
cc
null
ceph-main/src/rgw/services/svc_bilog_rados.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_rados.h" class RGWSI_BILog_RADOS : public RGWServiceInstance { public: struct Svc { RGWSI_BucketIndex_RADOS *bi{nullptr}; } svc; RGWSI_BILog_RADOS(CephContext *cct); void init(RGWSI_BucketIndex_RADOS *bi_rados_svc); int log_start(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id); int log_stop(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id); int log_trim(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id, std::string_view start_marker, std::string_view end_marker); int log_list(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id, std::string& marker, uint32_t max, std::list<rgw_bi_log_entry>& result, bool *truncated); int get_log_status(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& log_layout, int shard_id, std::map<int, std::string> *markers, optional_yield y); };
1,914
30.393443
148
h
null
ceph-main/src/rgw/services/svc_bucket.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_bucket.h" #define dout_subsys ceph_subsys_rgw std::string RGWSI_Bucket::get_entrypoint_meta_key(const rgw_bucket& bucket) { if (bucket.bucket_id.empty()) { return bucket.get_key(); } rgw_bucket b(bucket); b.bucket_id.clear(); return b.get_key(); } std::string RGWSI_Bucket::get_bi_meta_key(const rgw_bucket& bucket) { return bucket.get_key(); }
488
17.807692
75
cc
null
ceph-main/src/rgw/services/svc_bucket.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_bucket_types.h" class RGWSI_Bucket : public RGWServiceInstance { public: RGWSI_Bucket(CephContext *cct) : RGWServiceInstance(cct) {} virtual ~RGWSI_Bucket() {} static std::string get_entrypoint_meta_key(const rgw_bucket& bucket); static std::string get_bi_meta_key(const rgw_bucket& bucket); virtual RGWSI_Bucket_BE_Handler& get_ep_be_handler() = 0; virtual RGWSI_BucketInstance_BE_Handler& get_bi_be_handler() = 0; virtual int read_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWBucketEntryPoint *entry_point, RGWObjVersionTracker *objv_tracker, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none) = 0; virtual int store_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWBucketEntryPoint& info, bool exclusive, real_time mtime, std::map<std::string, bufferlist> *pattrs, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int remove_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int read_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none) = 0; virtual int read_bucket_info(RGWSI_Bucket_X_Ctx& ep_ctx, const rgw_bucket& bucket, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, boost::optional<obj_version> refresh_version, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int store_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo& info, std::optional<RGWBucketInfo *> orig_info, /* nullopt: orig_info was not fetched, nullptr: orig_info was not found (new bucket instance */ bool exclusive, real_time mtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int remove_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, const RGWBucketInfo& bucket_info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int read_bucket_stats(RGWSI_Bucket_X_Ctx& ctx, const rgw_bucket& bucket, RGWBucketEnt *ent, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int read_buckets_stats(RGWSI_Bucket_X_Ctx& ctx, std::map<std::string, RGWBucketEnt>& m, optional_yield y, const DoutPrefixProvider *dpp) = 0; };
5,165
45.125
134
h
null
ceph-main/src/rgw/services/svc_bucket_sobj.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_bucket_sobj.h" #include "svc_zone.h" #include "svc_sys_obj.h" #include "svc_sys_obj_cache.h" #include "svc_bi.h" #include "svc_meta.h" #include "svc_meta_be_sobj.h" #include "svc_sync_modules.h" #include "rgw_bucket.h" #include "rgw_tools.h" #include "rgw_zone.h" #define dout_subsys ceph_subsys_rgw #define RGW_BUCKET_INSTANCE_MD_PREFIX ".bucket.meta." using namespace std; class RGWSI_Bucket_SObj_Module : public RGWSI_MBSObj_Handler_Module { RGWSI_Bucket_SObj::Svc& svc; const string prefix; public: RGWSI_Bucket_SObj_Module(RGWSI_Bucket_SObj::Svc& _svc) : RGWSI_MBSObj_Handler_Module("bucket"), svc(_svc) {} void get_pool_and_oid(const string& key, rgw_pool *pool, string *oid) override { if (pool) { *pool = svc.zone->get_zone_params().domain_root; } if (oid) { *oid = key; } } const string& get_oid_prefix() override { return prefix; } bool is_valid_oid(const string& oid) override { return (!oid.empty() && oid[0] != '.'); } string key_to_oid(const string& key) override { return key; } string oid_to_key(const string& oid) override { /* should have been called after is_valid_oid(), * so no need to check for validity */ return oid; } }; class RGWSI_BucketInstance_SObj_Module : public RGWSI_MBSObj_Handler_Module { RGWSI_Bucket_SObj::Svc& svc; const string prefix; public: RGWSI_BucketInstance_SObj_Module(RGWSI_Bucket_SObj::Svc& _svc) : RGWSI_MBSObj_Handler_Module("bucket.instance"), svc(_svc), prefix(RGW_BUCKET_INSTANCE_MD_PREFIX) {} void get_pool_and_oid(const string& key, rgw_pool *pool, string *oid) override { if (pool) { *pool = svc.zone->get_zone_params().domain_root; } if (oid) { *oid = key_to_oid(key); } } const string& get_oid_prefix() override { return prefix; } bool is_valid_oid(const string& oid) override { return (oid.compare(0, prefix.size(), RGW_BUCKET_INSTANCE_MD_PREFIX) == 0); } // 'tenant/' is used in bucket instance keys for sync to avoid parsing ambiguity // with the existing instance[:shard] format. once we parse the shard, the / is // replaced with a : to match the [tenant:]instance format string key_to_oid(const string& key) override { string oid = prefix + key; // replace tenant/ with tenant: auto c = oid.find('/', prefix.size()); if (c != string::npos) { oid[c] = ':'; } return oid; } // convert bucket instance oids back to the tenant/ format for metadata keys. // it's safe to parse 'tenant:' only for oids, because they won't contain the // optional :shard at the end string oid_to_key(const string& oid) override { /* this should have been called after oid was checked for validity */ if (oid.size() < prefix.size()) { /* just sanity check */ return string(); } string key = oid.substr(prefix.size()); // find first : (could be tenant:bucket or bucket:instance) auto c = key.find(':'); if (c != string::npos) { // if we find another :, the first one was for tenant if (key.find(':', c + 1) != string::npos) { key[c] = '/'; } } return key; } /* * hash entry for mdlog placement. Use the same hash key we'd have for the bucket entry * point, so that the log entries end up at the same log shard, so that we process them * in order */ string get_hash_key(const string& key) override { string k = "bucket:"; int pos = key.find(':'); if (pos < 0) k.append(key); else k.append(key.substr(0, pos)); return k; } }; RGWSI_Bucket_SObj::RGWSI_Bucket_SObj(CephContext *cct): RGWSI_Bucket(cct) { } RGWSI_Bucket_SObj::~RGWSI_Bucket_SObj() { } void RGWSI_Bucket_SObj::init(RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_SysObj_Cache *_cache_svc, RGWSI_BucketIndex *_bi, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc, RGWSI_SyncModules *_sync_modules_svc, RGWSI_Bucket_Sync *_bucket_sync_svc) { svc.bucket = this; svc.zone = _zone_svc; svc.sysobj = _sysobj_svc; svc.cache = _cache_svc; svc.bi = _bi; svc.meta = _meta_svc; svc.meta_be = _meta_be_svc; svc.sync_modules = _sync_modules_svc; svc.bucket_sync = _bucket_sync_svc; } int RGWSI_Bucket_SObj::do_start(optional_yield, const DoutPrefixProvider *dpp) { binfo_cache.reset(new RGWChainedCacheImpl<bucket_info_cache_entry>); binfo_cache->init(svc.cache); /* create first backend handler for bucket entrypoints */ RGWSI_MetaBackend_Handler *ep_handler; int r = svc.meta->create_be_handler(RGWSI_MetaBackend::Type::MDBE_SOBJ, &ep_handler); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to create be handler: r=" << r << dendl; return r; } ep_be_handler = ep_handler; RGWSI_MetaBackend_Handler_SObj *ep_bh = static_cast<RGWSI_MetaBackend_Handler_SObj *>(ep_handler); auto ep_module = new RGWSI_Bucket_SObj_Module(svc); ep_be_module.reset(ep_module); ep_bh->set_module(ep_module); /* create a second backend handler for bucket instance */ RGWSI_MetaBackend_Handler *bi_handler; r = svc.meta->create_be_handler(RGWSI_MetaBackend::Type::MDBE_SOBJ, &bi_handler); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to create be handler: r=" << r << dendl; return r; } bi_be_handler = bi_handler; RGWSI_MetaBackend_Handler_SObj *bi_bh = static_cast<RGWSI_MetaBackend_Handler_SObj *>(bi_handler); auto bi_module = new RGWSI_BucketInstance_SObj_Module(svc); bi_be_module.reset(bi_module); bi_bh->set_module(bi_module); return 0; } int RGWSI_Bucket_SObj::read_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const string& key, RGWBucketEntryPoint *entry_point, RGWObjVersionTracker *objv_tracker, real_time *pmtime, map<string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info, boost::optional<obj_version> refresh_version) { bufferlist bl; auto params = RGWSI_MBSObj_GetParams(&bl, pattrs, pmtime).set_cache_info(cache_info) .set_refresh_version(refresh_version); int ret = svc.meta_be->get_entry(ctx.get(), key, params, objv_tracker, y, dpp); if (ret < 0) { return ret; } auto iter = bl.cbegin(); try { decode(*entry_point, iter); } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: could not decode buffer info, caught buffer::error" << dendl; return -EIO; } return 0; } int RGWSI_Bucket_SObj::store_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const string& key, RGWBucketEntryPoint& info, bool exclusive, real_time mtime, map<string, bufferlist> *pattrs, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { bufferlist bl; encode(info, bl); RGWSI_MBSObj_PutParams params(bl, pattrs, mtime, exclusive); int ret = svc.meta_be->put(ctx.get(), key, params, objv_tracker, y, dpp); if (ret < 0) { return ret; } return ret; } int RGWSI_Bucket_SObj::remove_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const string& key, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { RGWSI_MBSObj_RemoveParams params; return svc.meta_be->remove(ctx.get(), key, params, objv_tracker, y, dpp); } int RGWSI_Bucket_SObj::read_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const string& key, RGWBucketInfo *info, real_time *pmtime, map<string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info, boost::optional<obj_version> refresh_version) { string cache_key("bi/"); cache_key.append(key); if (auto e = binfo_cache->find(cache_key)) { if (refresh_version && e->info.objv_tracker.read_version.compare(&(*refresh_version))) { ldpp_dout(dpp, -1) << "WARNING: The bucket info cache is inconsistent. This is " << "a failure that should be debugged. I am a nice machine, " << "so I will try to recover." << dendl; binfo_cache->invalidate(key); } else { *info = e->info; if (pattrs) *pattrs = e->attrs; if (pmtime) *pmtime = e->mtime; return 0; } } bucket_info_cache_entry e; rgw_cache_entry_info ci; int ret = do_read_bucket_instance_info(ctx, key, &e.info, &e.mtime, &e.attrs, &ci, refresh_version, y, dpp); *info = e.info; if (ret < 0) { if (ret != -ENOENT) { ldpp_dout(dpp, -1) << "ERROR: do_read_bucket_instance_info failed: " << ret << dendl; } else { ldpp_dout(dpp, 20) << "do_read_bucket_instance_info, bucket instance not found (key=" << key << ")" << dendl; } return ret; } if (pmtime) { *pmtime = e.mtime; } if (pattrs) { *pattrs = e.attrs; } if (cache_info) { *cache_info = ci; } /* chain to only bucket instance and *not* bucket entrypoint */ if (!binfo_cache->put(dpp, svc.cache, cache_key, &e, {&ci})) { ldpp_dout(dpp, 20) << "couldn't put binfo cache entry, might have raced with data changes" << dendl; } if (refresh_version && refresh_version->compare(&info->objv_tracker.read_version)) { ldpp_dout(dpp, -1) << "WARNING: The OSD has the same version I have. Something may " << "have gone squirrelly. An administrator may have forced a " << "change; otherwise there is a problem somewhere." << dendl; } return 0; } int RGWSI_Bucket_SObj::do_read_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const string& key, RGWBucketInfo *info, real_time *pmtime, map<string, bufferlist> *pattrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version> refresh_version, optional_yield y, const DoutPrefixProvider *dpp) { bufferlist bl; RGWObjVersionTracker ot; auto params = RGWSI_MBSObj_GetParams(&bl, pattrs, pmtime).set_cache_info(cache_info) .set_refresh_version(refresh_version); int ret = svc.meta_be->get_entry(ctx.get(), key, params, &ot, y, dpp); if (ret < 0) { return ret; } auto iter = bl.cbegin(); try { decode(*info, iter); } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: could not decode buffer info, caught buffer::error" << dendl; return -EIO; } info->objv_tracker = ot; return 0; } int RGWSI_Bucket_SObj::read_bucket_info(RGWSI_Bucket_X_Ctx& ctx, const rgw_bucket& bucket, RGWBucketInfo *info, real_time *pmtime, map<string, bufferlist> *pattrs, boost::optional<obj_version> refresh_version, optional_yield y, const DoutPrefixProvider *dpp) { rgw_cache_entry_info cache_info; if (!bucket.bucket_id.empty()) { return read_bucket_instance_info(ctx.bi, get_bi_meta_key(bucket), info, pmtime, pattrs, y, dpp, &cache_info, refresh_version); } string bucket_entry = get_entrypoint_meta_key(bucket); string cache_key("b/"); cache_key.append(bucket_entry); if (auto e = binfo_cache->find(cache_key)) { bool found_version = (bucket.bucket_id.empty() || bucket.bucket_id == e->info.bucket.bucket_id); if (!found_version || (refresh_version && e->info.objv_tracker.read_version.compare(&(*refresh_version)))) { ldpp_dout(dpp, -1) << "WARNING: The bucket info cache is inconsistent. This is " << "a failure that should be debugged. I am a nice machine, " << "so I will try to recover." << dendl; binfo_cache->invalidate(cache_key); } else { *info = e->info; if (pattrs) *pattrs = e->attrs; if (pmtime) *pmtime = e->mtime; return 0; } } RGWBucketEntryPoint entry_point; real_time ep_mtime; RGWObjVersionTracker ot; rgw_cache_entry_info entry_cache_info; int ret = read_bucket_entrypoint_info(ctx.ep, bucket_entry, &entry_point, &ot, &ep_mtime, pattrs, y, dpp, &entry_cache_info, refresh_version); if (ret < 0) { /* only init these fields */ info->bucket = bucket; return ret; } if (entry_point.has_bucket_info) { *info = entry_point.old_bucket_info; info->bucket.tenant = bucket.tenant; ldpp_dout(dpp, 20) << "rgw_get_bucket_info: old bucket info, bucket=" << info->bucket << " owner " << info->owner << dendl; return 0; } /* data is in the bucket instance object, we need to get attributes from there, clear everything * that we got */ if (pattrs) { pattrs->clear(); } ldpp_dout(dpp, 20) << "rgw_get_bucket_info: bucket instance: " << entry_point.bucket << dendl; /* read bucket instance info */ bucket_info_cache_entry e; ret = read_bucket_instance_info(ctx.bi, get_bi_meta_key(entry_point.bucket), &e.info, &e.mtime, &e.attrs, y, dpp, &cache_info, refresh_version); *info = e.info; if (ret < 0) { ldpp_dout(dpp, -1) << "ERROR: read_bucket_instance_from_oid failed: " << ret << dendl; info->bucket = bucket; // XXX and why return anything in case of an error anyway? return ret; } if (pmtime) *pmtime = e.mtime; if (pattrs) *pattrs = e.attrs; /* chain to both bucket entry point and bucket instance */ if (!binfo_cache->put(dpp, svc.cache, cache_key, &e, {&entry_cache_info, &cache_info})) { ldpp_dout(dpp, 20) << "couldn't put binfo cache entry, might have raced with data changes" << dendl; } if (refresh_version && refresh_version->compare(&info->objv_tracker.read_version)) { ldpp_dout(dpp, -1) << "WARNING: The OSD has the same version I have. Something may " << "have gone squirrelly. An administrator may have forced a " << "change; otherwise there is a problem somewhere." << dendl; } return 0; } int RGWSI_Bucket_SObj::store_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const string& key, RGWBucketInfo& info, std::optional<RGWBucketInfo *> orig_info, bool exclusive, real_time mtime, map<string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp) { bufferlist bl; encode(info, bl); /* * we might need some special handling if overwriting */ RGWBucketInfo shared_bucket_info; if (!orig_info && !exclusive) { /* if exclusive, we're going to fail when try to overwrite, so the whole check here is moot */ /* * we're here because orig_info wasn't passed in * we don't have info about what was there before, so need to fetch first */ int r = read_bucket_instance_info(ctx, key, &shared_bucket_info, nullptr, nullptr, y, dpp, nullptr, boost::none); if (r < 0) { if (r != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << "(): read_bucket_instance_info() of key=" << key << " returned r=" << r << dendl; return r; } } else { orig_info = &shared_bucket_info; } } if (orig_info && *orig_info && !exclusive) { int r = svc.bi->handle_overwrite(dpp, info, *(orig_info.value()), y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << "(): svc.bi->handle_overwrite() of key=" << key << " returned r=" << r << dendl; return r; } } RGWSI_MBSObj_PutParams params(bl, pattrs, mtime, exclusive); int ret = svc.meta_be->put(ctx.get(), key, params, &info.objv_tracker, y, dpp); if (ret >= 0) { int r = svc.bucket_sync->handle_bi_update(dpp, info, orig_info.value_or(nullptr), y); if (r < 0) { return r; } } else if (ret == -EEXIST) { /* well, if it's exclusive we shouldn't overwrite it, because we might race with another * bucket operation on this specific bucket (e.g., being synced from the master), but * since bucket instance meta object is unique for this specific bucket instance, we don't * need to return an error. * A scenario where we'd get -EEXIST here, is in a multi-zone config, we're not on the * master, creating a bucket, sending bucket creation to the master, we create the bucket * locally, while in the sync thread we sync the new bucket. */ ret = 0; } if (ret < 0) { return ret; } return ret; } int RGWSI_Bucket_SObj::remove_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const string& key, const RGWBucketInfo& info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { RGWSI_MBSObj_RemoveParams params; int ret = svc.meta_be->remove_entry(dpp, ctx.get(), key, params, objv_tracker, y); if (ret < 0 && ret != -ENOENT) { return ret; } int r = svc.bucket_sync->handle_bi_removal(dpp, info, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update bucket instance sync index: r=" << r << dendl; /* returning success as index is just keeping hints, so will keep extra hints, * but bucket removal succeeded */ } return 0; } int RGWSI_Bucket_SObj::read_bucket_stats(const RGWBucketInfo& bucket_info, RGWBucketEnt *ent, optional_yield y, const DoutPrefixProvider *dpp) { ent->count = 0; ent->size = 0; ent->size_rounded = 0; vector<rgw_bucket_dir_header> headers; int r = svc.bi->read_stats(dpp, bucket_info, ent, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << "(): read_stats returned r=" << r << dendl; return r; } return 0; } int RGWSI_Bucket_SObj::read_bucket_stats(RGWSI_Bucket_X_Ctx& ctx, const rgw_bucket& bucket, RGWBucketEnt *ent, optional_yield y, const DoutPrefixProvider *dpp) { RGWBucketInfo bucket_info; int ret = read_bucket_info(ctx, bucket, &bucket_info, nullptr, nullptr, boost::none, y, dpp); if (ret < 0) { return ret; } return read_bucket_stats(bucket_info, ent, y, dpp); } int RGWSI_Bucket_SObj::read_buckets_stats(RGWSI_Bucket_X_Ctx& ctx, map<string, RGWBucketEnt>& m, optional_yield y, const DoutPrefixProvider *dpp) { map<string, RGWBucketEnt>::iterator iter; for (iter = m.begin(); iter != m.end(); ++iter) { RGWBucketEnt& ent = iter->second; int r = read_bucket_stats(ctx, ent.bucket, &ent, y, dpp); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << "(): read_bucket_stats returned r=" << r << dendl; return r; } } return m.size(); }
22,430
33.776744
135
cc
null
ceph-main/src/rgw/services/svc_bucket_sobj.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_meta_be.h" #include "svc_bucket_types.h" #include "svc_bucket.h" #include "svc_bucket_sync.h" class RGWSI_Zone; class RGWSI_SysObj; class RGWSI_SysObj_Cache; class RGWSI_Meta; class RGWSI_SyncModules; struct rgw_cache_entry_info; template <class T> class RGWChainedCacheImpl; class RGWSI_Bucket_SObj : public RGWSI_Bucket { struct bucket_info_cache_entry { RGWBucketInfo info; real_time mtime; std::map<std::string, bufferlist> attrs; }; using RGWChainedCacheImpl_bucket_info_cache_entry = RGWChainedCacheImpl<bucket_info_cache_entry>; std::unique_ptr<RGWChainedCacheImpl_bucket_info_cache_entry> binfo_cache; RGWSI_Bucket_BE_Handler ep_be_handler; std::unique_ptr<RGWSI_MetaBackend::Module> ep_be_module; RGWSI_BucketInstance_BE_Handler bi_be_handler; std::unique_ptr<RGWSI_MetaBackend::Module> bi_be_module; int do_start(optional_yield, const DoutPrefixProvider *dpp) override; int do_read_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version> refresh_version, optional_yield y, const DoutPrefixProvider *dpp); int read_bucket_stats(const RGWBucketInfo& bucket_info, RGWBucketEnt *ent, optional_yield y, const DoutPrefixProvider *dpp); public: struct Svc { RGWSI_Bucket_SObj *bucket{nullptr}; RGWSI_BucketIndex *bi{nullptr}; RGWSI_Zone *zone{nullptr}; RGWSI_SysObj *sysobj{nullptr}; RGWSI_SysObj_Cache *cache{nullptr}; RGWSI_Meta *meta{nullptr}; RGWSI_MetaBackend *meta_be{nullptr}; RGWSI_SyncModules *sync_modules{nullptr}; RGWSI_Bucket_Sync *bucket_sync{nullptr}; } svc; RGWSI_Bucket_SObj(CephContext *cct); ~RGWSI_Bucket_SObj(); RGWSI_Bucket_BE_Handler& get_ep_be_handler() override { return ep_be_handler; } RGWSI_BucketInstance_BE_Handler& get_bi_be_handler() override { return bi_be_handler; } void init(RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_SysObj_Cache *_cache_svc, RGWSI_BucketIndex *_bi, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc, RGWSI_SyncModules *_sync_modules_svc, RGWSI_Bucket_Sync *_bucket_sync_svc); int read_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWBucketEntryPoint *entry_point, RGWObjVersionTracker *objv_tracker, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none) override; int store_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWBucketEntryPoint& info, bool exclusive, real_time mtime, std::map<std::string, bufferlist> *pattrs, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) override; int remove_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) override; int read_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none) override; int read_bucket_info(RGWSI_Bucket_X_Ctx& ep_ctx, const rgw_bucket& bucket, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, boost::optional<obj_version> refresh_version, optional_yield y, const DoutPrefixProvider *dpp) override; int store_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo& info, std::optional<RGWBucketInfo *> orig_info, /* nullopt: orig_info was not fetched, nullptr: orig_info was not found (new bucket instance */ bool exclusive, real_time mtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp) override; int remove_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, const RGWBucketInfo& bucket_info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) override; int read_bucket_stats(RGWSI_Bucket_X_Ctx& ctx, const rgw_bucket& bucket, RGWBucketEnt *ent, optional_yield y, const DoutPrefixProvider *dpp) override; int read_buckets_stats(RGWSI_Bucket_X_Ctx& ctx, std::map<std::string, RGWBucketEnt>& m, optional_yield y, const DoutPrefixProvider *dpp) override; };
7,278
39.21547
134
h
null
ceph-main/src/rgw/services/svc_bucket_sync.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_bucket_types.h" class RGWBucketSyncPolicyHandler; using RGWBucketSyncPolicyHandlerRef = std::shared_ptr<RGWBucketSyncPolicyHandler>; class RGWSI_Bucket_Sync : public RGWServiceInstance { public: RGWSI_Bucket_Sync(CephContext *cct) : RGWServiceInstance(cct) {} virtual int get_policy_handler(RGWSI_Bucket_X_Ctx& ctx, std::optional<rgw_zone_id> zone, std::optional<rgw_bucket> bucket, RGWBucketSyncPolicyHandlerRef *handler, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int handle_bi_update(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, RGWBucketInfo *orig_bucket_info, optional_yield y) = 0; virtual int handle_bi_removal(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, optional_yield y) = 0; virtual int get_bucket_sync_hints(const DoutPrefixProvider *dpp, const rgw_bucket& bucket, std::set<rgw_bucket> *sources, std::set<rgw_bucket> *dests, optional_yield y) = 0; };
1,863
32.285714
82
h
null
ceph-main/src/rgw/services/svc_bucket_sync_sobj.cc
#include "svc_bucket_sync_sobj.h" #include "svc_zone.h" #include "svc_sys_obj_cache.h" #include "svc_bucket_sobj.h" #include "rgw_bucket_sync.h" #include "rgw_zone.h" #include "rgw_sync_policy.h" #define dout_subsys ceph_subsys_rgw using namespace std; static string bucket_sync_sources_oid_prefix = "bucket.sync-source-hints"; static string bucket_sync_targets_oid_prefix = "bucket.sync-target-hints"; class RGWSI_Bucket_Sync_SObj_HintIndexManager { CephContext *cct; struct { RGWSI_Zone *zone; RGWSI_SysObj *sysobj; } svc; public: RGWSI_Bucket_Sync_SObj_HintIndexManager(RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc) { svc.zone = _zone_svc; svc.sysobj = _sysobj_svc; cct = svc.zone->ctx(); } rgw_raw_obj get_sources_obj(const rgw_bucket& bucket) const; rgw_raw_obj get_dests_obj(const rgw_bucket& bucket) const; template <typename C1, typename C2> int update_hints(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, C1& added_dests, C2& removed_dests, C1& added_sources, C2& removed_sources, optional_yield y); }; RGWSI_Bucket_Sync_SObj::RGWSI_Bucket_Sync_SObj(CephContext *cct) : RGWSI_Bucket_Sync(cct) { } RGWSI_Bucket_Sync_SObj::~RGWSI_Bucket_Sync_SObj() { } void RGWSI_Bucket_Sync_SObj::init(RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_SysObj_Cache *_cache_svc, RGWSI_Bucket_SObj *bucket_sobj_svc) { svc.zone = _zone_svc; svc.sysobj = _sysobj_svc; svc.cache = _cache_svc; svc.bucket_sobj = bucket_sobj_svc; hint_index_mgr.reset(new RGWSI_Bucket_Sync_SObj_HintIndexManager(svc.zone, svc.sysobj)); } int RGWSI_Bucket_Sync_SObj::do_start(optional_yield, const DoutPrefixProvider *dpp) { sync_policy_cache.reset(new RGWChainedCacheImpl<bucket_sync_policy_cache_entry>); sync_policy_cache->init(svc.cache); return 0; } void RGWSI_Bucket_Sync_SObj::get_hint_entities(RGWSI_Bucket_X_Ctx& ctx, const std::set<rgw_zone_id>& zones, const std::set<rgw_bucket>& buckets, std::set<rgw_sync_bucket_entity> *hint_entities, optional_yield y, const DoutPrefixProvider *dpp) { vector<rgw_bucket> hint_buckets; hint_buckets.reserve(buckets.size()); for (auto& b : buckets) { RGWBucketInfo hint_bucket_info; int ret = svc.bucket_sobj->read_bucket_info(ctx, b, &hint_bucket_info, nullptr, nullptr, boost::none, y, dpp); if (ret < 0) { ldpp_dout(dpp, 20) << "could not init bucket info for hint bucket=" << b << " ... skipping" << dendl; continue; } hint_buckets.emplace_back(std::move(hint_bucket_info.bucket)); } for (auto& zone : zones) { for (auto& b : hint_buckets) { hint_entities->insert(rgw_sync_bucket_entity(zone, b)); } } } int RGWSI_Bucket_Sync_SObj::resolve_policy_hints(RGWSI_Bucket_X_Ctx& ctx, rgw_sync_bucket_entity& self_entity, RGWBucketSyncPolicyHandlerRef& handler, RGWBucketSyncPolicyHandlerRef& zone_policy_handler, std::map<optional_zone_bucket, RGWBucketSyncPolicyHandlerRef>& temp_map, optional_yield y, const DoutPrefixProvider *dpp) { 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(ctx, source_zones, handler->get_source_hints(), &hint_entities, y, dpp); get_hint_entities(ctx, target_zones, handler->get_target_hints(), &hint_entities, y, dpp); std::set<rgw_sync_bucket_pipe> resolved_sources; std::set<rgw_sync_bucket_pipe> resolved_dests; for (auto& hint_entity : hint_entities) { if (!hint_entity.zone || !hint_entity.bucket) { continue; /* shouldn't really happen */ } auto& zid = *hint_entity.zone; auto& hint_bucket = *hint_entity.bucket; RGWBucketSyncPolicyHandlerRef hint_bucket_handler; auto iter = temp_map.find(optional_zone_bucket(zid, hint_bucket)); if (iter != temp_map.end()) { hint_bucket_handler = iter->second; } else { int r = do_get_policy_handler(ctx, zid, hint_bucket, temp_map, &hint_bucket_handler, y, dpp); 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 */ } handler->set_resolved_hints(std::move(resolved_sources), std::move(resolved_dests)); return 0; } int RGWSI_Bucket_Sync_SObj::do_get_policy_handler(RGWSI_Bucket_X_Ctx& ctx, std::optional<rgw_zone_id> zone, std::optional<rgw_bucket> _bucket, std::map<optional_zone_bucket, RGWBucketSyncPolicyHandlerRef>& temp_map, RGWBucketSyncPolicyHandlerRef *handler, optional_yield y, const DoutPrefixProvider *dpp) { if (!_bucket) { *handler = svc.zone->get_sync_policy_handler(zone); return 0; } auto bucket = *_bucket; if (bucket.bucket_id.empty()) { RGWBucketEntryPoint ep_info; int ret = svc.bucket_sobj->read_bucket_entrypoint_info(ctx.ep, RGWSI_Bucket::get_entrypoint_meta_key(bucket), &ep_info, nullptr, /* objv_tracker */ nullptr, /* mtime */ nullptr, /* attrs */ y, dpp, nullptr, /* cache_info */ boost::none /* refresh_version */); if (ret < 0) { if (ret != -ENOENT) { ldout(cct, 0) << "ERROR: svc.bucket->read_bucket_info(bucket=" << bucket << ") returned r=" << ret << dendl; } return ret; } bucket = ep_info.bucket; } string zone_key; string bucket_key; if (zone && *zone != svc.zone->zone_id()) { zone_key = zone->id; } bucket_key = RGWSI_Bucket::get_bi_meta_key(bucket); string cache_key("bi/" + zone_key + "/" + bucket_key); if (auto e = sync_policy_cache->find(cache_key)) { *handler = e->handler; return 0; } bucket_sync_policy_cache_entry e; rgw_cache_entry_info cache_info; RGWBucketInfo bucket_info; map<string, bufferlist> attrs; int r = svc.bucket_sobj->read_bucket_instance_info(ctx.bi, bucket_key, &bucket_info, nullptr, &attrs, y, dpp, &cache_info); if (r < 0) { if (r != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: svc.bucket->read_bucket_instance_info(key=" << bucket_key << ") returned r=" << r << dendl; } return r; } auto zone_policy_handler = svc.zone->get_sync_policy_handler(zone); if (!zone_policy_handler) { ldpp_dout(dpp, 20) << "ERROR: could not find policy handler for zone=" << zone << dendl; return -ENOENT; } e.handler.reset(zone_policy_handler->alloc_child(bucket_info, std::move(attrs))); r = e.handler->init(dpp, y); if (r < 0) { ldpp_dout(dpp, 20) << "ERROR: failed to init bucket sync policy handler: r=" << r << dendl; return r; } temp_map.emplace(optional_zone_bucket{zone, bucket}, e.handler); rgw_sync_bucket_entity self_entity(zone.value_or(svc.zone->zone_id()), bucket); r = resolve_policy_hints(ctx, self_entity, e.handler, zone_policy_handler, temp_map, y, dpp); if (r < 0) { ldpp_dout(dpp, 20) << "ERROR: failed to resolve policy hints: bucket_key=" << bucket_key << ", r=" << r << dendl; return r; } if (!sync_policy_cache->put(dpp, svc.cache, cache_key, &e, {&cache_info})) { ldpp_dout(dpp, 20) << "couldn't put bucket_sync_policy cache entry, might have raced with data changes" << dendl; } *handler = e.handler; return 0; } int RGWSI_Bucket_Sync_SObj::get_policy_handler(RGWSI_Bucket_X_Ctx& ctx, std::optional<rgw_zone_id> zone, std::optional<rgw_bucket> _bucket, RGWBucketSyncPolicyHandlerRef *handler, optional_yield y, const DoutPrefixProvider *dpp) { std::map<optional_zone_bucket, RGWBucketSyncPolicyHandlerRef> temp_map; return do_get_policy_handler(ctx, zone, _bucket, temp_map, handler, y, dpp); } static bool diff_sets(std::set<rgw_bucket>& orig_set, std::set<rgw_bucket>& new_set, vector<rgw_bucket> *added, vector<rgw_bucket> *removed) { auto oiter = orig_set.begin(); auto niter = new_set.begin(); while (oiter != orig_set.end() && niter != new_set.end()) { if (*oiter == *niter) { ++oiter; ++niter; continue; } else if (*oiter < *niter) { removed->push_back(*oiter); ++oiter; } else { added->push_back(*niter); ++niter; } } for (; oiter != orig_set.end(); ++oiter) { removed->push_back(*oiter); } for (; niter != new_set.end(); ++niter) { added->push_back(*niter); } return !(removed->empty() && added->empty()); } class RGWSI_BS_SObj_HintIndexObj { friend class RGWSI_Bucket_Sync_SObj; CephContext *cct; struct { RGWSI_SysObj *sysobj; } svc; rgw_raw_obj obj; RGWSysObj sysobj; RGWObjVersionTracker ot; bool has_data{false}; public: struct bi_entry { rgw_bucket bucket; map<rgw_bucket /* info_source */, obj_version> sources; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(bucket, bl); encode(sources, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(bucket, bl); decode(sources, bl); DECODE_FINISH(bl); } bool add(const rgw_bucket& info_source, const obj_version& info_source_ver) { auto& ver = sources[info_source]; if (ver == info_source_ver) { /* already updated */ return false; } if (info_source_ver.tag == ver.tag && info_source_ver.ver < ver.ver) { return false; } ver = info_source_ver; return true; } bool remove(const rgw_bucket& info_source, const obj_version& info_source_ver) { auto iter = sources.find(info_source); if (iter == sources.end()) { return false; } auto& ver = iter->second; if (info_source_ver.tag == ver.tag && info_source_ver.ver < ver.ver) { return false; } sources.erase(info_source); return true; } bool empty() const { return sources.empty(); } }; struct single_instance_info { map<rgw_bucket, bi_entry> entries; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(entries, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(entries, bl); DECODE_FINISH(bl); } bool add_entry(const rgw_bucket& info_source, const obj_version& info_source_ver, const rgw_bucket& bucket) { auto& entry = entries[bucket]; if (!entry.add(info_source, info_source_ver)) { return false; } entry.bucket = bucket; return true; } bool remove_entry(const rgw_bucket& info_source, const obj_version& info_source_ver, const rgw_bucket& bucket) { auto iter = entries.find(bucket); if (iter == entries.end()) { return false; } if (!iter->second.remove(info_source, info_source_ver)) { return false; } if (iter->second.empty()) { entries.erase(iter); } return true; } void clear() { entries.clear(); } bool empty() const { return entries.empty(); } void get_entities(std::set<rgw_bucket> *result) const { for (auto& iter : entries) { result->insert(iter.first); } } }; struct info_map { map<rgw_bucket, single_instance_info> instances; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(instances, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(instances, bl); DECODE_FINISH(bl); } bool empty() const { return instances.empty(); } void clear() { instances.clear(); } void get_entities(const rgw_bucket& bucket, std::set<rgw_bucket> *result) const { auto iter = instances.find(bucket); if (iter == instances.end()) { return; } iter->second.get_entities(result); } } info; RGWSI_BS_SObj_HintIndexObj(RGWSI_SysObj *_sysobj_svc, const rgw_raw_obj& _obj) : cct(_sysobj_svc->ctx()), obj(_obj), sysobj(_sysobj_svc->get_obj(obj)) { svc.sysobj = _sysobj_svc; } template <typename C1, typename C2> int update(const DoutPrefixProvider *dpp, const rgw_bucket& entity, const RGWBucketInfo& info_source, C1 *add, C2 *remove, optional_yield y); private: template <typename C1, typename C2> void update_entries(const rgw_bucket& info_source, const obj_version& info_source_ver, C1 *add, C2 *remove, single_instance_info *instance); int read(const DoutPrefixProvider *dpp, optional_yield y); int flush(const DoutPrefixProvider *dpp, optional_yield y); void invalidate() { has_data = false; info.clear(); } void get_entities(const rgw_bucket& bucket, std::set<rgw_bucket> *result) const { info.get_entities(bucket, result); } }; WRITE_CLASS_ENCODER(RGWSI_BS_SObj_HintIndexObj::bi_entry) WRITE_CLASS_ENCODER(RGWSI_BS_SObj_HintIndexObj::single_instance_info) WRITE_CLASS_ENCODER(RGWSI_BS_SObj_HintIndexObj::info_map) template <typename C1, typename C2> int RGWSI_BS_SObj_HintIndexObj::update(const DoutPrefixProvider *dpp, const rgw_bucket& entity, const RGWBucketInfo& info_source, C1 *add, C2 *remove, optional_yield y) { int r = 0; auto& info_source_ver = info_source.objv_tracker.read_version; #define MAX_RETRIES 25 for (int i = 0; i < MAX_RETRIES; ++i) { if (!has_data) { r = read(dpp, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: cannot update hint index: failed to read: r=" << r << dendl; return r; } } auto& instance = info.instances[entity]; update_entries(info_source.bucket, info_source_ver, add, remove, &instance); if (instance.empty()) { info.instances.erase(entity); } r = flush(dpp, y); if (r >= 0) { return 0; } if (r != -ECANCELED) { ldpp_dout(dpp, 0) << "ERROR: failed to flush hint index: obj=" << obj << " r=" << r << dendl; return r; } invalidate(); } ldpp_dout(dpp, 0) << "ERROR: failed to flush hint index: too many retries (obj=" << obj << "), likely a bug" << dendl; return -EIO; } template <typename C1, typename C2> void RGWSI_BS_SObj_HintIndexObj::update_entries(const rgw_bucket& info_source, const obj_version& info_source_ver, C1 *add, C2 *remove, single_instance_info *instance) { if (remove) { for (auto& bucket : *remove) { instance->remove_entry(info_source, info_source_ver, bucket); } } if (add) { for (auto& bucket : *add) { instance->add_entry(info_source, info_source_ver, bucket); } } } int RGWSI_BS_SObj_HintIndexObj::read(const DoutPrefixProvider *dpp, optional_yield y) { RGWObjVersionTracker _ot; bufferlist bl; int r = sysobj.rop() .set_objv_tracker(&_ot) /* forcing read of current version */ .read(dpp, &bl, y); if (r < 0 && r != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: failed reading data (obj=" << obj << "), r=" << r << dendl; return r; } ot = _ot; if (r >= 0) { auto iter = bl.cbegin(); try { decode(info, iter); has_data = true; } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << "(): failed to decode entries, ignoring" << dendl; info.clear(); } } else { info.clear(); } return 0; } int RGWSI_BS_SObj_HintIndexObj::flush(const DoutPrefixProvider *dpp, optional_yield y) { int r; if (!info.empty()) { bufferlist bl; encode(info, bl); r = sysobj.wop() .set_objv_tracker(&ot) /* forcing read of current version */ .write(dpp, bl, y); } else { /* remove */ r = sysobj.wop() .set_objv_tracker(&ot) .remove(dpp, y); } if (r < 0) { return r; } return 0; } rgw_raw_obj RGWSI_Bucket_Sync_SObj_HintIndexManager::get_sources_obj(const rgw_bucket& bucket) const { rgw_bucket b = bucket; b.bucket_id.clear(); return rgw_raw_obj(svc.zone->get_zone_params().log_pool, bucket_sync_sources_oid_prefix + "." + b.get_key()); } rgw_raw_obj RGWSI_Bucket_Sync_SObj_HintIndexManager::get_dests_obj(const rgw_bucket& bucket) const { rgw_bucket b = bucket; b.bucket_id.clear(); return rgw_raw_obj(svc.zone->get_zone_params().log_pool, bucket_sync_targets_oid_prefix + "." + b.get_key()); } template <typename C1, typename C2> int RGWSI_Bucket_Sync_SObj_HintIndexManager::update_hints(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, C1& added_dests, C2& removed_dests, C1& added_sources, C2& removed_sources, optional_yield y) { C1 self_entity = { bucket_info.bucket }; if (!added_dests.empty() || !removed_dests.empty()) { /* update our dests */ RGWSI_BS_SObj_HintIndexObj index(svc.sysobj, get_dests_obj(bucket_info.bucket)); int r = index.update(dpp, bucket_info.bucket, bucket_info, &added_dests, &removed_dests, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update targets index for bucket=" << bucket_info.bucket << " r=" << r << dendl; return r; } /* update dest buckets */ for (auto& dest_bucket : added_dests) { RGWSI_BS_SObj_HintIndexObj dep_index(svc.sysobj, get_sources_obj(dest_bucket)); int r = dep_index.update(dpp, dest_bucket, bucket_info, &self_entity, static_cast<C2 *>(nullptr), y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update targets index for bucket=" << dest_bucket << " r=" << r << dendl; return r; } } /* update removed dest buckets */ for (auto& dest_bucket : removed_dests) { RGWSI_BS_SObj_HintIndexObj dep_index(svc.sysobj, get_sources_obj(dest_bucket)); int r = dep_index.update(dpp, dest_bucket, bucket_info, static_cast<C1 *>(nullptr), &self_entity, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update targets index for bucket=" << dest_bucket << " r=" << r << dendl; return r; } } } if (!added_sources.empty() || !removed_sources.empty()) { RGWSI_BS_SObj_HintIndexObj index(svc.sysobj, get_sources_obj(bucket_info.bucket)); /* update our sources */ int r = index.update(dpp, bucket_info.bucket, bucket_info, &added_sources, &removed_sources, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update targets index for bucket=" << bucket_info.bucket << " r=" << r << dendl; return r; } /* update added sources buckets */ for (auto& source_bucket : added_sources) { RGWSI_BS_SObj_HintIndexObj dep_index(svc.sysobj, get_dests_obj(source_bucket)); int r = dep_index.update(dpp, source_bucket, bucket_info, &self_entity, static_cast<C2 *>(nullptr), y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update targets index for bucket=" << source_bucket << " r=" << r << dendl; return r; } } /* update removed dest buckets */ for (auto& source_bucket : removed_sources) { RGWSI_BS_SObj_HintIndexObj dep_index(svc.sysobj, get_dests_obj(source_bucket)); int r = dep_index.update(dpp, source_bucket, bucket_info, static_cast<C1 *>(nullptr), &self_entity, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update targets index for bucket=" << source_bucket << " r=" << r << dendl; return r; } } } return 0; } int RGWSI_Bucket_Sync_SObj::handle_bi_removal(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, optional_yield y) { std::set<rgw_bucket> sources_set; std::set<rgw_bucket> dests_set; if (bucket_info.sync_policy) { bucket_info.sync_policy->get_potential_related_buckets(bucket_info.bucket, &sources_set, &dests_set); } std::vector<rgw_bucket> removed_sources; removed_sources.reserve(sources_set.size()); for (auto& e : sources_set) { removed_sources.push_back(e); } std::vector<rgw_bucket> removed_dests; removed_dests.reserve(dests_set.size()); for (auto& e : dests_set) { removed_dests.push_back(e); } std::vector<rgw_bucket> added_sources; std::vector<rgw_bucket> added_dests; return hint_index_mgr->update_hints(dpp, bucket_info, added_dests, removed_dests, added_sources, removed_sources, y); } int RGWSI_Bucket_Sync_SObj::handle_bi_update(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, RGWBucketInfo *orig_bucket_info, optional_yield y) { std::set<rgw_bucket> orig_sources; std::set<rgw_bucket> orig_dests; if (orig_bucket_info && orig_bucket_info->sync_policy) { orig_bucket_info->sync_policy->get_potential_related_buckets(bucket_info.bucket, &orig_sources, &orig_dests); } std::set<rgw_bucket> sources; std::set<rgw_bucket> dests; if (bucket_info.sync_policy) { bucket_info.sync_policy->get_potential_related_buckets(bucket_info.bucket, &sources, &dests); } std::vector<rgw_bucket> removed_sources; std::vector<rgw_bucket> added_sources; bool found = diff_sets(orig_sources, sources, &added_sources, &removed_sources); ldpp_dout(dpp, 20) << __func__ << "(): bucket=" << bucket_info.bucket << ": orig_sources=" << orig_sources << " new_sources=" << sources << dendl; ldpp_dout(dpp, 20) << __func__ << "(): bucket=" << bucket_info.bucket << ": potential sources added=" << added_sources << " removed=" << removed_sources << dendl; std::vector<rgw_bucket> removed_dests; std::vector<rgw_bucket> added_dests; found = found || diff_sets(orig_dests, dests, &added_dests, &removed_dests); ldpp_dout(dpp, 20) << __func__ << "(): bucket=" << bucket_info.bucket << ": orig_dests=" << orig_dests << " new_dests=" << dests << dendl; ldpp_dout(dpp, 20) << __func__ << "(): bucket=" << bucket_info.bucket << ": potential dests added=" << added_dests << " removed=" << removed_dests << dendl; if (!found) { return 0; } return hint_index_mgr->update_hints(dpp, bucket_info, dests, /* set all dests, not just the ones that were added */ removed_dests, sources, /* set all sources, not just that the ones that were added */ removed_sources, y); } int RGWSI_Bucket_Sync_SObj::get_bucket_sync_hints(const DoutPrefixProvider *dpp, const rgw_bucket& bucket, std::set<rgw_bucket> *sources, std::set<rgw_bucket> *dests, optional_yield y) { if (!sources && !dests) { return 0; } if (sources) { RGWSI_BS_SObj_HintIndexObj index(svc.sysobj, hint_index_mgr->get_sources_obj(bucket)); int r = index.read(dpp, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to update sources index for bucket=" << bucket << " r=" << r << dendl; return r; } index.get_entities(bucket, sources); if (!bucket.bucket_id.empty()) { rgw_bucket b = bucket; b.bucket_id.clear(); index.get_entities(b, sources); } } if (dests) { RGWSI_BS_SObj_HintIndexObj index(svc.sysobj, hint_index_mgr->get_dests_obj(bucket)); int r = index.read(dpp, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to read targets index for bucket=" << bucket << " r=" << r << dendl; return r; } index.get_entities(bucket, dests); if (!bucket.bucket_id.empty()) { rgw_bucket b = bucket; b.bucket_id.clear(); index.get_entities(b, dests); } } return 0; }
29,479
31.610619
165
cc
null
ceph-main/src/rgw/services/svc_bucket_sync_sobj.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_meta_be.h" #include "svc_bucket_sync.h" class RGWSI_Zone; class RGWSI_SysObj_Cache; class RGWSI_Bucket_SObj; template <class T> class RGWChainedCacheImpl; class RGWSI_Bucket_Sync_SObj_HintIndexManager; struct rgw_sync_bucket_entity; class RGWSI_Bucket_Sync_SObj : public RGWSI_Bucket_Sync { struct bucket_sync_policy_cache_entry { std::shared_ptr<RGWBucketSyncPolicyHandler> handler; }; std::unique_ptr<RGWChainedCacheImpl<bucket_sync_policy_cache_entry> > sync_policy_cache; std::unique_ptr<RGWSI_Bucket_Sync_SObj_HintIndexManager> hint_index_mgr; int do_start(optional_yield, const DoutPrefixProvider *dpp) override; struct optional_zone_bucket { std::optional<rgw_zone_id> zone; std::optional<rgw_bucket> bucket; optional_zone_bucket(const std::optional<rgw_zone_id>& _zone, const std::optional<rgw_bucket>& _bucket) : zone(_zone), bucket(_bucket) {} bool operator<(const optional_zone_bucket& ozb) const { if (zone < ozb.zone) { return true; } if (zone > ozb.zone) { return false; } return bucket < ozb.bucket; } }; void get_hint_entities(RGWSI_Bucket_X_Ctx& ctx, const std::set<rgw_zone_id>& zone_names, const std::set<rgw_bucket>& buckets, std::set<rgw_sync_bucket_entity> *hint_entities, optional_yield y, const DoutPrefixProvider *); int resolve_policy_hints(RGWSI_Bucket_X_Ctx& ctx, rgw_sync_bucket_entity& self_entity, RGWBucketSyncPolicyHandlerRef& handler, RGWBucketSyncPolicyHandlerRef& zone_policy_handler, std::map<optional_zone_bucket, RGWBucketSyncPolicyHandlerRef>& temp_map, optional_yield y, const DoutPrefixProvider *dpp); int do_get_policy_handler(RGWSI_Bucket_X_Ctx& ctx, std::optional<rgw_zone_id> zone, std::optional<rgw_bucket> _bucket, std::map<optional_zone_bucket, RGWBucketSyncPolicyHandlerRef>& temp_map, RGWBucketSyncPolicyHandlerRef *handler, optional_yield y, const DoutPrefixProvider *dpp); public: struct Svc { RGWSI_Zone *zone{nullptr}; RGWSI_SysObj *sysobj{nullptr}; RGWSI_SysObj_Cache *cache{nullptr}; RGWSI_Bucket_SObj *bucket_sobj{nullptr}; } svc; RGWSI_Bucket_Sync_SObj(CephContext *cct); ~RGWSI_Bucket_Sync_SObj(); void init(RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_SysObj_Cache *_cache_svc, RGWSI_Bucket_SObj *_bucket_sobj_svc); int get_policy_handler(RGWSI_Bucket_X_Ctx& ctx, std::optional<rgw_zone_id> zone, std::optional<rgw_bucket> bucket, RGWBucketSyncPolicyHandlerRef *handler, optional_yield y, const DoutPrefixProvider *dpp); int handle_bi_update(const DoutPrefixProvider *dpp, RGWBucketInfo& bucket_info, RGWBucketInfo *orig_bucket_info, optional_yield y) override; int handle_bi_removal(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, optional_yield y) override; int get_bucket_sync_hints(const DoutPrefixProvider *dpp, const rgw_bucket& bucket, std::set<rgw_bucket> *sources, std::set<rgw_bucket> *dests, optional_yield y) override; };
4,274
33.475806
100
h
null
ceph-main/src/rgw/services/svc_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. * */ #pragma once #include "common/ptr_wrapper.h" #include "svc_meta_be.h" #include "svc_meta_be_types.h" class RGWSI_MetaBackend_Handler; using RGWSI_Bucket_BE_Handler = ptr_wrapper<RGWSI_MetaBackend_Handler, RGWSI_META_BE_TYPES::BUCKET>; using RGWSI_BucketInstance_BE_Handler = ptr_wrapper<RGWSI_MetaBackend_Handler, RGWSI_META_BE_TYPES::BI>; using RGWSI_Bucket_EP_Ctx = ptr_wrapper<RGWSI_MetaBackend::Context, RGWSI_META_BE_TYPES::BUCKET>; using RGWSI_Bucket_BI_Ctx = ptr_wrapper<RGWSI_MetaBackend::Context, RGWSI_META_BE_TYPES::BI>; struct RGWSI_Bucket_X_Ctx { RGWSI_Bucket_EP_Ctx ep; RGWSI_Bucket_BI_Ctx bi; };
1,037
25.615385
104
h
null
ceph-main/src/rgw/services/svc_cls.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_cls.h" #include "svc_rados.h" #include "svc_zone.h" #include "rgw_zone.h" #include "cls/otp/cls_otp_client.h" #include "cls/log/cls_log_client.h" #include "cls/lock/cls_lock_client.h" #define dout_subsys ceph_subsys_rgw using namespace std; static string log_lock_name = "rgw_log_lock"; int RGWSI_Cls::do_start(optional_yield y, const DoutPrefixProvider *dpp) { int r = mfa.do_start(y, dpp); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to start mfa service" << dendl; return r; } return 0; } int RGWSI_Cls::MFA::get_mfa_obj(const DoutPrefixProvider *dpp, const rgw_user& user, std::optional<RGWSI_RADOS::Obj> *obj) { string oid = get_mfa_oid(user); rgw_raw_obj o(zone_svc->get_zone_params().otp_pool, oid); obj->emplace(rados_svc->obj(o)); int r = (*obj)->open(dpp); if (r < 0) { ldpp_dout(dpp, 4) << "failed to open rados context for " << o << dendl; return r; } return 0; } int RGWSI_Cls::MFA::get_mfa_ref(const DoutPrefixProvider *dpp, const rgw_user& user, rgw_rados_ref *ref) { std::optional<RGWSI_RADOS::Obj> obj; int r = get_mfa_obj(dpp, user, &obj); if (r < 0) { return r; } *ref = obj->get_ref(); return 0; } int RGWSI_Cls::MFA::check_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const string& otp_id, const string& pin, optional_yield y) { rgw_rados_ref ref; int r = get_mfa_ref(dpp, user, &ref); if (r < 0) { return r; } rados::cls::otp::otp_check_t result; r = rados::cls::otp::OTP::check(cct, ref.pool.ioctx(), ref.obj.oid, otp_id, pin, &result); if (r < 0) return r; ldpp_dout(dpp, 20) << "OTP check, otp_id=" << otp_id << " result=" << (int)result.result << dendl; return (result.result == rados::cls::otp::OTP_CHECK_SUCCESS ? 0 : -EACCES); } void RGWSI_Cls::MFA::prepare_mfa_write(librados::ObjectWriteOperation *op, RGWObjVersionTracker *objv_tracker, const ceph::real_time& mtime) { RGWObjVersionTracker ot; if (objv_tracker) { ot = *objv_tracker; } if (ot.write_version.tag.empty()) { if (ot.read_version.tag.empty()) { ot.generate_new_write_ver(cct); } else { ot.write_version = ot.read_version; ot.write_version.ver++; } } ot.prepare_op_for_write(op); struct timespec mtime_ts = real_clock::to_timespec(mtime); op->mtime2(&mtime_ts); } int RGWSI_Cls::MFA::create_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const rados::cls::otp::otp_info_t& config, RGWObjVersionTracker *objv_tracker, const ceph::real_time& mtime, optional_yield y) { std::optional<RGWSI_RADOS::Obj> obj; int r = get_mfa_obj(dpp, user, &obj); if (r < 0) { return r; } librados::ObjectWriteOperation op; prepare_mfa_write(&op, objv_tracker, mtime); rados::cls::otp::OTP::create(&op, config); r = obj->operate(dpp, &op, y); if (r < 0) { ldpp_dout(dpp, 20) << "OTP create, otp_id=" << config.id << " result=" << (int)r << dendl; return r; } return 0; } int RGWSI_Cls::MFA::remove_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const string& id, RGWObjVersionTracker *objv_tracker, const ceph::real_time& mtime, optional_yield y) { std::optional<RGWSI_RADOS::Obj> obj; int r = get_mfa_obj(dpp, user, &obj); if (r < 0) { return r; } librados::ObjectWriteOperation op; prepare_mfa_write(&op, objv_tracker, mtime); rados::cls::otp::OTP::remove(&op, id); r = obj->operate(dpp, &op, y); if (r < 0) { ldpp_dout(dpp, 20) << "OTP remove, otp_id=" << id << " result=" << (int)r << dendl; return r; } return 0; } int RGWSI_Cls::MFA::get_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const string& id, rados::cls::otp::otp_info_t *result, optional_yield y) { rgw_rados_ref ref; int r = get_mfa_ref(dpp, user, &ref); if (r < 0) { return r; } r = rados::cls::otp::OTP::get(nullptr, ref.pool.ioctx(), ref.obj.oid, id, result); if (r < 0) { return r; } return 0; } int RGWSI_Cls::MFA::list_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, list<rados::cls::otp::otp_info_t> *result, optional_yield y) { rgw_rados_ref ref; int r = get_mfa_ref(dpp, user, &ref); if (r < 0) { return r; } r = rados::cls::otp::OTP::get_all(nullptr, ref.pool.ioctx(), ref.obj.oid, result); if (r < 0) { return r; } return 0; } int RGWSI_Cls::MFA::otp_get_current_time(const DoutPrefixProvider *dpp, const rgw_user& user, ceph::real_time *result, optional_yield y) { rgw_rados_ref ref; int r = get_mfa_ref(dpp, user, &ref); if (r < 0) { return r; } r = rados::cls::otp::OTP::get_current_time(ref.pool.ioctx(), ref.obj.oid, result); if (r < 0) { return r; } return 0; } int RGWSI_Cls::MFA::set_mfa(const DoutPrefixProvider *dpp, const string& oid, const list<rados::cls::otp::otp_info_t>& entries, bool reset_obj, RGWObjVersionTracker *objv_tracker, const real_time& mtime, optional_yield y) { rgw_raw_obj o(zone_svc->get_zone_params().otp_pool, oid); auto obj = rados_svc->obj(o); int r = obj.open(dpp); if (r < 0) { ldpp_dout(dpp, 4) << "failed to open rados context for " << o << dendl; return r; } librados::ObjectWriteOperation op; if (reset_obj) { op.remove(); op.set_op_flags2(LIBRADOS_OP_FLAG_FAILOK); op.create(false); } prepare_mfa_write(&op, objv_tracker, mtime); rados::cls::otp::OTP::set(&op, entries); r = obj.operate(dpp, &op, y); if (r < 0) { ldpp_dout(dpp, 20) << "OTP set entries.size()=" << entries.size() << " result=" << (int)r << dendl; return r; } return 0; } int RGWSI_Cls::MFA::list_mfa(const DoutPrefixProvider *dpp, const string& oid, list<rados::cls::otp::otp_info_t> *result, RGWObjVersionTracker *objv_tracker, ceph::real_time *pmtime, optional_yield y) { rgw_raw_obj o(zone_svc->get_zone_params().otp_pool, oid); auto obj = rados_svc->obj(o); int r = obj.open(dpp); if (r < 0) { ldpp_dout(dpp, 4) << "failed to open rados context for " << o << dendl; return r; } auto& ref = obj.get_ref(); librados::ObjectReadOperation op; struct timespec mtime_ts; if (pmtime) { op.stat2(nullptr, &mtime_ts, nullptr); } objv_tracker->prepare_op_for_read(&op); r = rados::cls::otp::OTP::get_all(&op, ref.pool.ioctx(), ref.obj.oid, result); if (r < 0) { return r; } if (pmtime) { *pmtime = ceph::real_clock::from_timespec(mtime_ts); } return 0; } void RGWSI_Cls::TimeLog::prepare_entry(cls_log_entry& entry, const real_time& ut, const string& section, const string& key, bufferlist& bl) { cls_log_add_prepare_entry(entry, utime_t(ut), section, key, bl); } int RGWSI_Cls::TimeLog::init_obj(const DoutPrefixProvider *dpp, const string& oid, RGWSI_RADOS::Obj& obj) { rgw_raw_obj o(zone_svc->get_zone_params().log_pool, oid); obj = rados_svc->obj(o); return obj.open(dpp); } int RGWSI_Cls::TimeLog::add(const DoutPrefixProvider *dpp, const string& oid, const real_time& ut, const string& section, const string& key, bufferlist& bl, optional_yield y) { RGWSI_RADOS::Obj obj; int r = init_obj(dpp, oid, obj); if (r < 0) { return r; } librados::ObjectWriteOperation op; utime_t t(ut); cls_log_add(op, t, section, key, bl); return obj.operate(dpp, &op, y); } int RGWSI_Cls::TimeLog::add(const DoutPrefixProvider *dpp, const string& oid, std::list<cls_log_entry>& entries, librados::AioCompletion *completion, bool monotonic_inc, optional_yield y) { RGWSI_RADOS::Obj obj; int r = init_obj(dpp, oid, obj); if (r < 0) { return r; } librados::ObjectWriteOperation op; cls_log_add(op, entries, monotonic_inc); if (!completion) { r = obj.operate(dpp, &op, y); } else { r = obj.aio_operate(completion, &op); } return r; } int RGWSI_Cls::TimeLog::list(const DoutPrefixProvider *dpp, const string& oid, const real_time& start_time, const real_time& end_time, int max_entries, std::list<cls_log_entry>& entries, const string& marker, string *out_marker, bool *truncated, optional_yield y) { RGWSI_RADOS::Obj obj; int r = init_obj(dpp, oid, obj); if (r < 0) { return r; } librados::ObjectReadOperation op; utime_t st(start_time); utime_t et(end_time); cls_log_list(op, st, et, marker, max_entries, entries, out_marker, truncated); bufferlist obl; int ret = obj.operate(dpp, &op, &obl, y); if (ret < 0) return ret; return 0; } int RGWSI_Cls::TimeLog::info(const DoutPrefixProvider *dpp, const string& oid, cls_log_header *header, optional_yield y) { RGWSI_RADOS::Obj obj; int r = init_obj(dpp, oid, obj); if (r < 0) { return r; } librados::ObjectReadOperation op; cls_log_info(op, header); bufferlist obl; int ret = obj.operate(dpp, &op, &obl, y); if (ret < 0) return ret; return 0; } int RGWSI_Cls::TimeLog::info_async(const DoutPrefixProvider *dpp, RGWSI_RADOS::Obj& obj, const string& oid, cls_log_header *header, librados::AioCompletion *completion) { int r = init_obj(dpp, oid, obj); if (r < 0) { return r; } librados::ObjectReadOperation op; cls_log_info(op, header); int ret = obj.aio_operate(completion, &op, nullptr); if (ret < 0) return ret; return 0; } int RGWSI_Cls::TimeLog::trim(const DoutPrefixProvider *dpp, const string& oid, const real_time& start_time, const real_time& end_time, const string& from_marker, const string& to_marker, librados::AioCompletion *completion, optional_yield y) { RGWSI_RADOS::Obj obj; int r = init_obj(dpp, oid, obj); if (r < 0) { return r; } utime_t st(start_time); utime_t et(end_time); librados::ObjectWriteOperation op; cls_log_trim(op, st, et, from_marker, to_marker); if (!completion) { r = obj.operate(dpp, &op, y); } else { r = obj.aio_operate(completion, &op); } return r; } int RGWSI_Cls::Lock::lock_exclusive(const DoutPrefixProvider *dpp, const rgw_pool& pool, const string& oid, timespan& duration, string& zone_id, string& owner_id, std::optional<string> lock_name) { auto p = rados_svc->pool(pool); int r = p.open(dpp); if (r < 0) { return r; } uint64_t msec = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); utime_t ut(msec / 1000, msec % 1000); rados::cls::lock::Lock l(lock_name.value_or(log_lock_name)); l.set_duration(ut); l.set_cookie(owner_id); l.set_tag(zone_id); l.set_may_renew(true); return l.lock_exclusive(&p.ioctx(), oid); } int RGWSI_Cls::Lock::unlock(const DoutPrefixProvider *dpp, const rgw_pool& pool, const string& oid, string& zone_id, string& owner_id, std::optional<string> lock_name) { auto p = rados_svc->pool(pool); int r = p.open(dpp); if (r < 0) { return r; } rados::cls::lock::Lock l(lock_name.value_or(log_lock_name)); l.set_tag(zone_id); l.set_cookie(owner_id); return l.unlock(&p.ioctx(), oid); }
12,658
25.427975
141
cc
null
ceph-main/src/rgw/services/svc_cls.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 "cls/otp/cls_otp_types.h" #include "cls/log/cls_log_types.h" #include "rgw_service.h" #include "svc_rados.h" class RGWSI_Cls : public RGWServiceInstance { RGWSI_Zone *zone_svc{nullptr}; RGWSI_RADOS *rados_svc{nullptr}; class ClsSubService : public RGWServiceInstance { friend class RGWSI_Cls; RGWSI_Cls *cls_svc{nullptr}; RGWSI_Zone *zone_svc{nullptr}; RGWSI_RADOS *rados_svc{nullptr}; void init(RGWSI_Cls *_cls_svc, RGWSI_Zone *_zone_svc, RGWSI_RADOS *_rados_svc) { cls_svc = _cls_svc; zone_svc = _cls_svc->zone_svc; rados_svc = _cls_svc->rados_svc; } public: ClsSubService(CephContext *cct) : RGWServiceInstance(cct) {} }; public: class MFA : public ClsSubService { int get_mfa_obj(const DoutPrefixProvider *dpp, const rgw_user& user, std::optional<RGWSI_RADOS::Obj> *obj); int get_mfa_ref(const DoutPrefixProvider *dpp, const rgw_user& user, rgw_rados_ref *ref); void prepare_mfa_write(librados::ObjectWriteOperation *op, RGWObjVersionTracker *objv_tracker, const ceph::real_time& mtime); public: MFA(CephContext *cct): ClsSubService(cct) {} std::string get_mfa_oid(const rgw_user& user) { return std::string("user:") + user.to_str(); } int check_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const std::string& otp_id, const std::string& pin, optional_yield y); int create_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const rados::cls::otp::otp_info_t& config, RGWObjVersionTracker *objv_tracker, const ceph::real_time& mtime, optional_yield y); int remove_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const std::string& id, RGWObjVersionTracker *objv_tracker, const ceph::real_time& mtime, optional_yield y); int get_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, const std::string& id, rados::cls::otp::otp_info_t *result, optional_yield y); int list_mfa(const DoutPrefixProvider *dpp, const rgw_user& user, std::list<rados::cls::otp::otp_info_t> *result, optional_yield y); int otp_get_current_time(const DoutPrefixProvider *dpp, const rgw_user& user, ceph::real_time *result, optional_yield y); int set_mfa(const DoutPrefixProvider *dpp, const std::string& oid, const std::list<rados::cls::otp::otp_info_t>& entries, bool reset_obj, RGWObjVersionTracker *objv_tracker, const real_time& mtime, optional_yield y); int list_mfa(const DoutPrefixProvider *dpp, const std::string& oid, std::list<rados::cls::otp::otp_info_t> *result, RGWObjVersionTracker *objv_tracker, ceph::real_time *pmtime, optional_yield y); } mfa; class TimeLog : public ClsSubService { int init_obj(const DoutPrefixProvider *dpp, const std::string& oid, RGWSI_RADOS::Obj& obj); public: TimeLog(CephContext *cct): ClsSubService(cct) {} void prepare_entry(cls_log_entry& entry, const real_time& ut, const std::string& section, const std::string& key, bufferlist& bl); int add(const DoutPrefixProvider *dpp, const std::string& oid, const real_time& ut, const std::string& section, const std::string& key, bufferlist& bl, optional_yield y); int add(const DoutPrefixProvider *dpp, const std::string& oid, std::list<cls_log_entry>& entries, librados::AioCompletion *completion, bool monotonic_inc, optional_yield y); int list(const DoutPrefixProvider *dpp, const std::string& oid, const real_time& start_time, const real_time& end_time, int max_entries, std::list<cls_log_entry>& entries, const std::string& marker, std::string *out_marker, bool *truncated, optional_yield y); int info(const DoutPrefixProvider *dpp, const std::string& oid, cls_log_header *header, optional_yield y); int info_async(const DoutPrefixProvider *dpp, RGWSI_RADOS::Obj& obj, const std::string& oid, cls_log_header *header, librados::AioCompletion *completion); int trim(const DoutPrefixProvider *dpp, const std::string& oid, const real_time& start_time, const real_time& end_time, const std::string& from_marker, const std::string& to_marker, librados::AioCompletion *completion, optional_yield y); } timelog; class Lock : public ClsSubService { int init_obj(const std::string& oid, RGWSI_RADOS::Obj& obj); public: Lock(CephContext *cct): ClsSubService(cct) {} int lock_exclusive(const DoutPrefixProvider *dpp, const rgw_pool& pool, const std::string& oid, timespan& duration, std::string& zone_id, std::string& owner_id, std::optional<std::string> lock_name = std::nullopt); int unlock(const DoutPrefixProvider *dpp, const rgw_pool& pool, const std::string& oid, std::string& zone_id, std::string& owner_id, std::optional<std::string> lock_name = std::nullopt); } lock; RGWSI_Cls(CephContext *cct): RGWServiceInstance(cct), mfa(cct), timelog(cct), lock(cct) {} void init(RGWSI_Zone *_zone_svc, RGWSI_RADOS *_rados_svc) { rados_svc = _rados_svc; zone_svc = _zone_svc; mfa.init(this, zone_svc, rados_svc); timelog.init(this, zone_svc, rados_svc); lock.init(this, zone_svc, rados_svc); } int do_start(optional_yield, const DoutPrefixProvider *dpp) override; };
6,338
36.958084
147
h
null
ceph-main/src/rgw/services/svc_config_key.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" class RGWSI_ConfigKey : public RGWServiceInstance { public: RGWSI_ConfigKey(CephContext *cct) : RGWServiceInstance(cct) {} virtual ~RGWSI_ConfigKey() {} virtual int get(const std::string& key, bool secure, bufferlist *result) = 0; };
697
20.8125
79
h
null
ceph-main/src/rgw/services/svc_config_key_rados.cc
#include "svc_rados.h" #include "svc_config_key_rados.h" using namespace std; RGWSI_ConfigKey_RADOS::~RGWSI_ConfigKey_RADOS(){} int RGWSI_ConfigKey_RADOS::do_start(optional_yield, const DoutPrefixProvider *dpp) { maybe_insecure_mon_conn = !svc.rados->check_secure_mon_conn(dpp); return 0; } void RGWSI_ConfigKey_RADOS::warn_if_insecure() { if (!maybe_insecure_mon_conn || warned_insecure.test_and_set()) { return; } string s = "rgw is configured to optionally allow insecure connections to the monitors (auth_supported, ms_mon_client_mode), ssl certificates stored at the monitor configuration could leak"; svc.rados->clog_warn(s); lderr(ctx()) << __func__ << "(): WARNING: " << s << dendl; } int RGWSI_ConfigKey_RADOS::get(const string& key, bool secure, bufferlist *result) { string cmd = "{" "\"prefix\": \"config-key get\", " "\"key\": \"" + key + "\"" "}"; bufferlist inbl; auto handle = svc.rados->handle(); int ret = handle.mon_command(cmd, inbl, result, nullptr); if (ret < 0) { return ret; } if (secure) { warn_if_insecure(); } return 0; }
1,132
21.215686
192
cc
null
ceph-main/src/rgw/services/svc_config_key_rados.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <atomic> #include "rgw_service.h" #include "svc_config_key.h" class RGWSI_RADOS; class RGWSI_ConfigKey_RADOS : public RGWSI_ConfigKey { bool maybe_insecure_mon_conn{false}; std::atomic_flag warned_insecure = ATOMIC_FLAG_INIT; int do_start(optional_yield, const DoutPrefixProvider *dpp) override; void warn_if_insecure(); public: struct Svc { RGWSI_RADOS *rados{nullptr}; } svc; void init(RGWSI_RADOS *rados_svc) { svc.rados = rados_svc; } RGWSI_ConfigKey_RADOS(CephContext *cct) : RGWSI_ConfigKey(cct) {} virtual ~RGWSI_ConfigKey_RADOS() override; int get(const std::string& key, bool secure, bufferlist *result) override; };
1,107
19.145455
76
h
null
ceph-main/src/rgw/services/svc_finisher.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "common/Finisher.h" #include "svc_finisher.h" using namespace std; int RGWSI_Finisher::do_start(optional_yield, const DoutPrefixProvider *dpp) { finisher = new Finisher(cct); finisher->start(); return 0; } void RGWSI_Finisher::shutdown() { if (finalized) { return; } if (finisher) { finisher->stop(); map<int, ShutdownCB *> cbs; cbs.swap(shutdown_cbs); /* move cbs out, in case caller unregisters */ for (auto& iter : cbs) { iter.second->call(); } delete finisher; } finalized = true; } RGWSI_Finisher::~RGWSI_Finisher() { shutdown(); } void RGWSI_Finisher::register_caller(ShutdownCB *cb, int *phandle) { *phandle = ++handles_counter; shutdown_cbs[*phandle] = cb; } void RGWSI_Finisher::unregister_caller(int handle) { shutdown_cbs.erase(handle); } void RGWSI_Finisher::schedule_context(Context *c) { finisher->queue(c); }
1,012
16.169492
75
cc
null
ceph-main/src/rgw/services/svc_finisher.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_service.h" class Context; class Finisher; class RGWSI_Finisher : public RGWServiceInstance { friend struct RGWServices_Def; public: class ShutdownCB; private: Finisher *finisher{nullptr}; bool finalized{false}; void shutdown() override; std::map<int, ShutdownCB *> shutdown_cbs; std::atomic<int> handles_counter{0}; protected: void init() {} int do_start(optional_yield y, const DoutPrefixProvider *dpp) override; public: RGWSI_Finisher(CephContext *cct): RGWServiceInstance(cct) {} ~RGWSI_Finisher(); class ShutdownCB { public: virtual ~ShutdownCB() {} virtual void call() = 0; }; void register_caller(ShutdownCB *cb, int *phandle); void unregister_caller(int handle); void schedule_context(Context *c); };
898
18.977778
73
h
null
ceph-main/src/rgw/services/svc_mdlog.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_mdlog.h" #include "svc_rados.h" #include "svc_zone.h" #include "svc_sys_obj.h" #include "rgw_tools.h" #include "rgw_mdlog.h" #include "rgw_coroutine.h" #include "rgw_cr_rados.h" #include "rgw_zone.h" #include "common/errno.h" #include <boost/asio/yield.hpp> #define dout_subsys ceph_subsys_rgw using namespace std; using Svc = RGWSI_MDLog::Svc; using Cursor = RGWPeriodHistory::Cursor; RGWSI_MDLog::RGWSI_MDLog(CephContext *cct, bool _run_sync) : RGWServiceInstance(cct), run_sync(_run_sync) { } RGWSI_MDLog::~RGWSI_MDLog() { } int RGWSI_MDLog::init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_Cls *_cls_svc) { svc.zone = _zone_svc; svc.sysobj = _sysobj_svc; svc.mdlog = this; svc.rados = _rados_svc; svc.cls = _cls_svc; return 0; } int RGWSI_MDLog::do_start(optional_yield y, const DoutPrefixProvider *dpp) { auto& current_period = svc.zone->get_current_period(); current_log = get_log(current_period.get_id()); period_puller.reset(new RGWPeriodPuller(svc.zone, svc.sysobj)); period_history.reset(new RGWPeriodHistory(cct, period_puller.get(), current_period)); if (run_sync && svc.zone->need_to_sync()) { // initialize the log period history svc.mdlog->init_oldest_log_period(y, dpp); } return 0; } int RGWSI_MDLog::read_history(RGWMetadataLogHistory *state, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) const { auto& pool = svc.zone->get_zone_params().log_pool; const auto& oid = RGWMetadataLogHistory::oid; bufferlist bl; int ret = rgw_get_system_obj(svc.sysobj, pool, oid, bl, objv_tracker, nullptr, y, dpp); if (ret < 0) { return ret; } if (bl.length() == 0) { /* bad history object, remove it */ rgw_raw_obj obj(pool, oid); auto sysobj = svc.sysobj->get_obj(obj); ret = sysobj.wop().remove(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: meta history is empty, but cannot remove it (" << cpp_strerror(-ret) << ")" << dendl; return ret; } return -ENOENT; } try { auto p = bl.cbegin(); state->decode(p); } catch (buffer::error& e) { ldpp_dout(dpp, 1) << "failed to decode the mdlog history: " << e.what() << dendl; return -EIO; } return 0; } int RGWSI_MDLog::write_history(const DoutPrefixProvider *dpp, const RGWMetadataLogHistory& state, RGWObjVersionTracker *objv_tracker, optional_yield y, bool exclusive) { bufferlist bl; state.encode(bl); auto& pool = svc.zone->get_zone_params().log_pool; const auto& oid = RGWMetadataLogHistory::oid; return rgw_put_system_obj(dpp, svc.sysobj, pool, oid, bl, exclusive, objv_tracker, real_time{}, y); } namespace mdlog { using Cursor = RGWPeriodHistory::Cursor; namespace { template <class T> class SysObjReadCR : public RGWSimpleCoroutine { const DoutPrefixProvider *dpp; RGWAsyncRadosProcessor *async_rados; RGWSI_SysObj *svc; rgw_raw_obj obj; T *result; /// on ENOENT, call handle_data() with an empty object instead of failing const bool empty_on_enoent; RGWObjVersionTracker *objv_tracker; RGWAsyncGetSystemObj *req{nullptr}; public: SysObjReadCR(const DoutPrefixProvider *_dpp, RGWAsyncRadosProcessor *_async_rados, RGWSI_SysObj *_svc, const rgw_raw_obj& _obj, T *_result, bool empty_on_enoent = true, RGWObjVersionTracker *objv_tracker = nullptr) : RGWSimpleCoroutine(_svc->ctx()), dpp(_dpp), async_rados(_async_rados), svc(_svc), obj(_obj), result(_result), empty_on_enoent(empty_on_enoent), objv_tracker(objv_tracker) {} ~SysObjReadCR() override { try { request_cleanup(); } catch (const boost::container::length_error_t& e) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << ": reference counted object mismatched, \"" << e.what() << "\"" << dendl; } } void request_cleanup() override { if (req) { req->finish(); req = NULL; } } int send_request(const DoutPrefixProvider *dpp) { req = new RGWAsyncGetSystemObj(dpp, this, stack->create_completion_notifier(), svc, objv_tracker, obj, false, false); async_rados->queue(req); return 0; } int request_complete() { int ret = req->get_ret_status(); retcode = ret; if (ret == -ENOENT && empty_on_enoent) { *result = T(); } else { if (ret < 0) { return ret; } if (objv_tracker) { // copy the updated version *objv_tracker = req->objv_tracker; } try { auto iter = req->bl.cbegin(); if (iter.end()) { // allow successful reads with empty buffers. ReadSyncStatus // coroutines depend on this to be able to read without // locking, because the cls lock from InitSyncStatus will // create an empty object if it didn't exist *result = T(); } else { decode(*result, iter); } } catch (buffer::error& err) { return -EIO; } } return handle_data(*result); } virtual int handle_data(T& data) { return 0; } }; template <class T> class SysObjWriteCR : public RGWSimpleCoroutine { const DoutPrefixProvider *dpp; RGWAsyncRadosProcessor *async_rados; RGWSI_SysObj *svc; bufferlist bl; rgw_raw_obj obj; RGWObjVersionTracker *objv_tracker; bool exclusive; RGWAsyncPutSystemObj *req{nullptr}; public: SysObjWriteCR(const DoutPrefixProvider *_dpp, RGWAsyncRadosProcessor *_async_rados, RGWSI_SysObj *_svc, const rgw_raw_obj& _obj, const T& _data, RGWObjVersionTracker *objv_tracker = nullptr, bool exclusive = false) : RGWSimpleCoroutine(_svc->ctx()), dpp(_dpp), async_rados(_async_rados), svc(_svc), obj(_obj), objv_tracker(objv_tracker), exclusive(exclusive) { encode(_data, bl); } ~SysObjWriteCR() override { try { request_cleanup(); } catch (const boost::container::length_error_t& e) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << ": reference counted object mismatched, \"" << e.what() << "\"" << dendl; } } void request_cleanup() override { if (req) { req->finish(); req = NULL; } } int send_request(const DoutPrefixProvider *dpp) override { req = new RGWAsyncPutSystemObj(dpp, this, stack->create_completion_notifier(), svc, objv_tracker, obj, exclusive, std::move(bl)); async_rados->queue(req); return 0; } int request_complete() override { if (objv_tracker) { // copy the updated version *objv_tracker = req->objv_tracker; } return req->get_ret_status(); } }; } /// read the mdlog history and use it to initialize the given cursor class ReadHistoryCR : public RGWCoroutine { const DoutPrefixProvider *dpp; Svc svc; Cursor *cursor; RGWObjVersionTracker *objv_tracker; RGWMetadataLogHistory state; RGWAsyncRadosProcessor *async_processor; public: ReadHistoryCR(const DoutPrefixProvider *dpp, const Svc& svc, Cursor *cursor, RGWObjVersionTracker *objv_tracker) : RGWCoroutine(svc.zone->ctx()), dpp(dpp), svc(svc), cursor(cursor), objv_tracker(objv_tracker), async_processor(svc.rados->get_async_processor()) {} int operate(const DoutPrefixProvider *dpp) { reenter(this) { yield { rgw_raw_obj obj{svc.zone->get_zone_params().log_pool, RGWMetadataLogHistory::oid}; constexpr bool empty_on_enoent = false; using ReadCR = SysObjReadCR<RGWMetadataLogHistory>; call(new ReadCR(dpp, async_processor, svc.sysobj, obj, &state, empty_on_enoent, objv_tracker)); } if (retcode < 0) { ldpp_dout(dpp, 1) << "failed to read mdlog history: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } *cursor = svc.mdlog->period_history->lookup(state.oldest_realm_epoch); if (!*cursor) { return set_cr_error(cursor->get_error()); } ldpp_dout(dpp, 10) << "read mdlog history with oldest period id=" << state.oldest_period_id << " realm_epoch=" << state.oldest_realm_epoch << dendl; return set_cr_done(); } return 0; } }; /// write the given cursor to the mdlog history class WriteHistoryCR : public RGWCoroutine { const DoutPrefixProvider *dpp; Svc svc; Cursor cursor; RGWObjVersionTracker *objv; RGWMetadataLogHistory state; RGWAsyncRadosProcessor *async_processor; public: WriteHistoryCR(const DoutPrefixProvider *dpp, Svc& svc, const Cursor& cursor, RGWObjVersionTracker *objv) : RGWCoroutine(svc.zone->ctx()), dpp(dpp), svc(svc), cursor(cursor), objv(objv), async_processor(svc.rados->get_async_processor()) {} int operate(const DoutPrefixProvider *dpp) { reenter(this) { state.oldest_period_id = cursor.get_period().get_id(); state.oldest_realm_epoch = cursor.get_epoch(); yield { rgw_raw_obj obj{svc.zone->get_zone_params().log_pool, RGWMetadataLogHistory::oid}; using WriteCR = SysObjWriteCR<RGWMetadataLogHistory>; call(new WriteCR(dpp, async_processor, svc.sysobj, obj, state, objv)); } if (retcode < 0) { ldpp_dout(dpp, 1) << "failed to write mdlog history: " << cpp_strerror(retcode) << dendl; return set_cr_error(retcode); } ldpp_dout(dpp, 10) << "wrote mdlog history with oldest period id=" << state.oldest_period_id << " realm_epoch=" << state.oldest_realm_epoch << dendl; return set_cr_done(); } return 0; } }; /// update the mdlog history to reflect trimmed logs class TrimHistoryCR : public RGWCoroutine { const DoutPrefixProvider *dpp; Svc svc; const Cursor cursor; //< cursor to trimmed period RGWObjVersionTracker *objv; //< to prevent racing updates Cursor next; //< target cursor for oldest log period Cursor existing; //< existing cursor read from disk public: TrimHistoryCR(const DoutPrefixProvider *dpp, const Svc& svc, Cursor cursor, RGWObjVersionTracker *objv) : RGWCoroutine(svc.zone->ctx()), dpp(dpp), svc(svc), cursor(cursor), objv(objv), next(cursor) { next.next(); // advance past cursor } int operate(const DoutPrefixProvider *dpp) { reenter(this) { // read an existing history, and write the new history if it's newer yield call(new ReadHistoryCR(dpp, svc, &existing, objv)); if (retcode < 0) { return set_cr_error(retcode); } // reject older trims with ECANCELED if (cursor.get_epoch() < existing.get_epoch()) { ldpp_dout(dpp, 4) << "found oldest log epoch=" << existing.get_epoch() << ", rejecting trim at epoch=" << cursor.get_epoch() << dendl; return set_cr_error(-ECANCELED); } // overwrite with updated history yield call(new WriteHistoryCR(dpp, svc, next, objv)); if (retcode < 0) { return set_cr_error(retcode); } return set_cr_done(); } return 0; } }; } // mdlog namespace // traverse all the way back to the beginning of the period history, and // return a cursor to the first period in a fully attached history Cursor RGWSI_MDLog::find_oldest_period(const DoutPrefixProvider *dpp, optional_yield y) { auto cursor = period_history->get_current(); while (cursor) { // advance to the period's predecessor if (!cursor.has_prev()) { auto& predecessor = cursor.get_period().get_predecessor(); if (predecessor.empty()) { // this is the first period, so our logs must start here ldpp_dout(dpp, 10) << "find_oldest_period returning first " "period " << cursor.get_period().get_id() << dendl; return cursor; } // pull the predecessor and add it to our history RGWPeriod period; int r = period_puller->pull(dpp, predecessor, period, y); if (r < 0) { return cursor; } auto prev = period_history->insert(std::move(period)); if (!prev) { return prev; } ldpp_dout(dpp, 20) << "find_oldest_period advancing to " "predecessor period " << predecessor << dendl; ceph_assert(cursor.has_prev()); } cursor.prev(); } ldpp_dout(dpp, 10) << "find_oldest_period returning empty cursor" << dendl; return cursor; } Cursor RGWSI_MDLog::init_oldest_log_period(optional_yield y, const DoutPrefixProvider *dpp) { // read the mdlog history RGWMetadataLogHistory state; RGWObjVersionTracker objv; int ret = read_history(&state, &objv, y, dpp); if (ret == -ENOENT) { // initialize the mdlog history and write it ldpp_dout(dpp, 10) << "initializing mdlog history" << dendl; auto cursor = find_oldest_period(dpp, y); if (!cursor) { return cursor; } // write the initial history state.oldest_realm_epoch = cursor.get_epoch(); state.oldest_period_id = cursor.get_period().get_id(); constexpr bool exclusive = true; // don't overwrite int ret = write_history(dpp, state, &objv, y, exclusive); if (ret < 0 && ret != -EEXIST) { ldpp_dout(dpp, 1) << "failed to write mdlog history: " << cpp_strerror(ret) << dendl; return Cursor{ret}; } return cursor; } else if (ret < 0) { ldpp_dout(dpp, 1) << "failed to read mdlog history: " << cpp_strerror(ret) << dendl; return Cursor{ret}; } // if it's already in the history, return it auto cursor = period_history->lookup(state.oldest_realm_epoch); if (cursor) { return cursor; } else { cursor = find_oldest_period(dpp, y); state.oldest_realm_epoch = cursor.get_epoch(); state.oldest_period_id = cursor.get_period().get_id(); ldpp_dout(dpp, 10) << "rewriting mdlog history" << dendl; ret = write_history(dpp, state, &objv, y); if (ret < 0 && ret != -ECANCELED) { ldpp_dout(dpp, 1) << "failed to write mdlog history: " << cpp_strerror(ret) << dendl; return Cursor{ret}; } return cursor; } // pull the oldest period by id RGWPeriod period; ret = period_puller->pull(dpp, state.oldest_period_id, period, y); if (ret < 0) { ldpp_dout(dpp, 1) << "failed to read period id=" << state.oldest_period_id << " for mdlog history: " << cpp_strerror(ret) << dendl; return Cursor{ret}; } // verify its realm_epoch if (period.get_realm_epoch() != state.oldest_realm_epoch) { ldpp_dout(dpp, 1) << "inconsistent mdlog history: read period id=" << period.get_id() << " with realm_epoch=" << period.get_realm_epoch() << ", expected realm_epoch=" << state.oldest_realm_epoch << dendl; return Cursor{-EINVAL}; } // attach the period to our history return period_history->attach(dpp, std::move(period), y); } Cursor RGWSI_MDLog::read_oldest_log_period(optional_yield y, const DoutPrefixProvider *dpp) const { RGWMetadataLogHistory state; int ret = read_history(&state, nullptr, y, dpp); if (ret < 0) { ldpp_dout(dpp, 1) << "failed to read mdlog history: " << cpp_strerror(ret) << dendl; return Cursor{ret}; } ldpp_dout(dpp, 10) << "read mdlog history with oldest period id=" << state.oldest_period_id << " realm_epoch=" << state.oldest_realm_epoch << dendl; return period_history->lookup(state.oldest_realm_epoch); } RGWCoroutine* RGWSI_MDLog::read_oldest_log_period_cr(const DoutPrefixProvider *dpp, Cursor *period, RGWObjVersionTracker *objv) const { return new mdlog::ReadHistoryCR(dpp, svc, period, objv); } RGWCoroutine* RGWSI_MDLog::trim_log_period_cr(const DoutPrefixProvider *dpp, Cursor period, RGWObjVersionTracker *objv) const { return new mdlog::TrimHistoryCR(dpp, svc, period, objv); } RGWMetadataLog* RGWSI_MDLog::get_log(const std::string& period) { // construct the period's log in place if it doesn't exist auto insert = md_logs.emplace(std::piecewise_construct, std::forward_as_tuple(period), std::forward_as_tuple(cct, svc.zone, svc.cls, period)); return &insert.first->second; } int RGWSI_MDLog::add_entry(const DoutPrefixProvider *dpp, const string& hash_key, const string& section, const string& key, bufferlist& bl) { ceph_assert(current_log); // must have called init() return current_log->add_entry(dpp, hash_key, section, key, bl); } int RGWSI_MDLog::get_shard_id(const string& hash_key, int *shard_id) { ceph_assert(current_log); // must have called init() return current_log->get_shard_id(hash_key, shard_id); } int RGWSI_MDLog::pull_period(const DoutPrefixProvider *dpp, const std::string& period_id, RGWPeriod& period, optional_yield y) { return period_puller->pull(dpp, period_id, period, y); }
17,119
30.127273
139
cc
null
ceph-main/src/rgw/services/svc_mdlog.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "rgw_period_history.h" #include "rgw_period_puller.h" #include "svc_meta_be.h" class RGWMetadataLog; class RGWMetadataLogHistory; class RGWCoroutine; class RGWSI_Zone; class RGWSI_SysObj; class RGWSI_RADOS; namespace mdlog { class ReadHistoryCR; class WriteHistoryCR; } class RGWSI_MDLog : public RGWServiceInstance { friend class mdlog::ReadHistoryCR; friend class mdlog::WriteHistoryCR; // maintain a separate metadata log for each period std::map<std::string, RGWMetadataLog> md_logs; // use the current period's log for mutating operations RGWMetadataLog* current_log{nullptr}; bool run_sync; // pulls missing periods for period_history std::unique_ptr<RGWPeriodPuller> period_puller; // maintains a connected history of periods std::unique_ptr<RGWPeriodHistory> period_history; public: RGWSI_MDLog(CephContext *cct, bool run_sync); virtual ~RGWSI_MDLog(); struct Svc { RGWSI_RADOS *rados{nullptr}; RGWSI_Zone *zone{nullptr}; RGWSI_SysObj *sysobj{nullptr}; RGWSI_MDLog *mdlog{nullptr}; RGWSI_Cls *cls{nullptr}; } svc; int init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_Cls *_cls_svc); int do_start(optional_yield y, const DoutPrefixProvider *dpp) override; // traverse all the way back to the beginning of the period history, and // return a cursor to the first period in a fully attached history RGWPeriodHistory::Cursor find_oldest_period(const DoutPrefixProvider *dpp, optional_yield y); /// initialize the oldest log period if it doesn't exist, and attach it to /// our current history RGWPeriodHistory::Cursor init_oldest_log_period(optional_yield y, const DoutPrefixProvider *dpp); /// read the oldest log period, and return a cursor to it in our existing /// period history RGWPeriodHistory::Cursor read_oldest_log_period(optional_yield y, const DoutPrefixProvider *dpp) const; /// read the oldest log period asynchronously and write its result to the /// given cursor pointer RGWCoroutine* read_oldest_log_period_cr(const DoutPrefixProvider *dpp, RGWPeriodHistory::Cursor *period, RGWObjVersionTracker *objv) const; /// try to advance the oldest log period when the given period is trimmed, /// using a rados lock to provide atomicity RGWCoroutine* trim_log_period_cr(const DoutPrefixProvider *dpp, RGWPeriodHistory::Cursor period, RGWObjVersionTracker *objv) const; int read_history(RGWMetadataLogHistory *state, RGWObjVersionTracker *objv_tracker,optional_yield y, const DoutPrefixProvider *dpp) const; int write_history(const DoutPrefixProvider *dpp, const RGWMetadataLogHistory& state, RGWObjVersionTracker *objv_tracker, optional_yield y, bool exclusive = false); int add_entry(const DoutPrefixProvider *dpp, const std::string& hash_key, const std::string& section, const std::string& key, bufferlist& bl); int get_shard_id(const std::string& hash_key, int *shard_id); RGWPeriodHistory *get_period_history() { return period_history.get(); } int pull_period(const DoutPrefixProvider *dpp, const std::string& period_id, RGWPeriod& period, optional_yield y); /// find or create the metadata log for the given period RGWMetadataLog* get_log(const std::string& period); };
3,956
32.252101
144
h
null
ceph-main/src/rgw/services/svc_meta.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_meta.h" #include "rgw_metadata.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_Meta::RGWSI_Meta(CephContext *cct) : RGWServiceInstance(cct) { } RGWSI_Meta::~RGWSI_Meta() {} void RGWSI_Meta::init(RGWSI_SysObj *_sysobj_svc, RGWSI_MDLog *_mdlog_svc, vector<RGWSI_MetaBackend *>& _be_svc) { sysobj_svc = _sysobj_svc; mdlog_svc = _mdlog_svc; for (auto& be : _be_svc) { be_svc[be->get_type()] = be; } } int RGWSI_Meta::create_be_handler(RGWSI_MetaBackend::Type be_type, RGWSI_MetaBackend_Handler **phandler) { auto iter = be_svc.find(be_type); if (iter == be_svc.end()) { ldout(cct, 0) << __func__ << "(): ERROR: backend type not found" << dendl; return -EINVAL; } auto handler = iter->second->alloc_be_handler(); be_handlers.emplace_back(handler); *phandler = handler; return 0; }
1,039
21.12766
78
cc
null
ceph-main/src/rgw/services/svc_meta.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 "svc_meta_be.h" #include "rgw_service.h" class RGWMetadataLog; class RGWCoroutine; class RGWSI_Meta : public RGWServiceInstance { RGWSI_SysObj *sysobj_svc{nullptr}; RGWSI_MDLog *mdlog_svc{nullptr}; std::map<RGWSI_MetaBackend::Type, RGWSI_MetaBackend *> be_svc; std::vector<std::unique_ptr<RGWSI_MetaBackend_Handler> > be_handlers; public: RGWSI_Meta(CephContext *cct); ~RGWSI_Meta(); void init(RGWSI_SysObj *_sysobj_svc, RGWSI_MDLog *_mdlog_svc, std::vector<RGWSI_MetaBackend *>& _be_svc); int create_be_handler(RGWSI_MetaBackend::Type be_type, RGWSI_MetaBackend_Handler **phandler); };
1,098
21.428571
71
h
null
ceph-main/src/rgw/services/svc_meta_be.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_meta_be.h" #include "rgw_mdlog.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_MetaBackend::Context::~Context() {} // needed, even though destructor is pure virtual RGWSI_MetaBackend::Module::~Module() {} // ditto RGWSI_MetaBackend::PutParams::~PutParams() {} // ... RGWSI_MetaBackend::GetParams::~GetParams() {} // ... RGWSI_MetaBackend::RemoveParams::~RemoveParams() {} // ... int RGWSI_MetaBackend::pre_modify(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, RGWMDLogStatus op_type, optional_yield y) { /* if write version has not been set, and there's a read version, set it so that we can * log it */ if (objv_tracker && objv_tracker->read_version.ver && !objv_tracker->write_version.ver) { objv_tracker->write_version = objv_tracker->read_version; objv_tracker->write_version.ver++; } return 0; } int RGWSI_MetaBackend::post_modify(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, int ret, optional_yield y) { return ret; } int RGWSI_MetaBackend::prepare_mutate(RGWSI_MetaBackend::Context *ctx, const string& key, const real_time& mtime, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { real_time orig_mtime; int ret = call_with_get_params(&orig_mtime, [&](GetParams& params) { return get_entry(ctx, key, params, objv_tracker, y, dpp); }); if (ret < 0 && ret != -ENOENT) { return ret; } if (objv_tracker->write_version.tag.empty()) { if (objv_tracker->read_version.tag.empty()) { objv_tracker->generate_new_write_ver(cct); } else { objv_tracker->write_version = objv_tracker->read_version; objv_tracker->write_version.ver++; } } return 0; } int RGWSI_MetaBackend::do_mutate(RGWSI_MetaBackend::Context *ctx, const string& key, const ceph::real_time& mtime, RGWObjVersionTracker *objv_tracker, RGWMDLogStatus op_type, optional_yield y, std::function<int()> f, bool generic_prepare, const DoutPrefixProvider *dpp) { int ret; if (generic_prepare) { ret = prepare_mutate(ctx, key, mtime, objv_tracker, y, dpp); if (ret < 0 || ret == STATUS_NO_APPLY) { return ret; } } RGWMetadataLogData log_data; ret = pre_modify(dpp, ctx, key, log_data, objv_tracker, op_type, y); if (ret < 0) { return ret; } ret = f(); /* cascading ret into post_modify() */ ret = post_modify(dpp, ctx, key, log_data, objv_tracker, ret, y); if (ret < 0) return ret; return 0; } int RGWSI_MetaBackend::get(Context *ctx, const string& key, GetParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs) { return get_entry(ctx, key, params, objv_tracker, y, dpp, get_raw_attrs); } int RGWSI_MetaBackend::put(Context *ctx, const string& key, PutParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { std::function<int()> f = [&]() { return put_entry(dpp, ctx, key, params, objv_tracker, y); }; return do_mutate(ctx, key, params.mtime, objv_tracker, MDLOG_STATUS_WRITE, y, f, false, dpp); } int RGWSI_MetaBackend::remove(Context *ctx, const string& key, RemoveParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { std::function<int()> f = [&]() { return remove_entry(dpp, ctx, key, params, objv_tracker, y); }; return do_mutate(ctx, key, params.mtime, objv_tracker, MDLOG_STATUS_REMOVE, y, f, false, dpp); } int RGWSI_MetaBackend::mutate(Context *ctx, const std::string& key, MutateParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, std::function<int()> f, const DoutPrefixProvider *dpp) { return do_mutate(ctx, key, params.mtime, objv_tracker, params.op_type, y, f, false, dpp); } int RGWSI_MetaBackend_Handler::call(std::optional<RGWSI_MetaBackend_CtxParams> bectx_params, std::function<int(Op *)> f) { return be->call(bectx_params, [&](RGWSI_MetaBackend::Context *ctx) { ctx->init(this); Op op(be, ctx); return f(&op); }); } RGWSI_MetaBackend_Handler::Op_ManagedCtx::Op_ManagedCtx(RGWSI_MetaBackend_Handler *handler) : Op(handler->be, handler->be->alloc_ctx()) { auto c = ctx(); c->init(handler); pctx.reset(c); }
5,858
29.201031
135
cc
null
ceph-main/src/rgw/services/svc_meta_be.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 "svc_meta_be_params.h" #include "rgw_service.h" #include "rgw_mdlog_types.h" class RGWMetadataLogData; class RGWSI_MDLog; class RGWSI_Meta; class RGWObjVersionTracker; class RGWSI_MetaBackend_Handler; class RGWSI_MetaBackend : public RGWServiceInstance { friend class RGWSI_Meta; public: class Module; class Context; protected: RGWSI_MDLog *mdlog_svc{nullptr}; void base_init(RGWSI_MDLog *_mdlog_svc) { mdlog_svc = _mdlog_svc; } int prepare_mutate(RGWSI_MetaBackend::Context *ctx, const std::string& key, const ceph::real_time& mtime, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); virtual int do_mutate(Context *ctx, const std::string& key, const ceph::real_time& mtime, RGWObjVersionTracker *objv_tracker, RGWMDLogStatus op_type, optional_yield y, std::function<int()> f, bool generic_prepare, const DoutPrefixProvider *dpp); virtual int pre_modify(const DoutPrefixProvider *dpp, Context *ctx, const std::string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, RGWMDLogStatus op_type, optional_yield y); virtual int post_modify(const DoutPrefixProvider *dpp, Context *ctx, const std::string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, int ret, optional_yield y); public: class Module { /* * Backend specialization module */ public: virtual ~Module() = 0; }; using ModuleRef = std::shared_ptr<Module>; struct Context { /* * A single metadata operation context. Will be holding info about * backend and operation itself; operation might span multiple backend * calls. */ virtual ~Context() = 0; virtual void init(RGWSI_MetaBackend_Handler *h) = 0; }; virtual Context *alloc_ctx() = 0; struct PutParams { ceph::real_time mtime; PutParams() {} PutParams(const ceph::real_time& _mtime) : mtime(_mtime) {} virtual ~PutParams() = 0; }; struct GetParams { GetParams() {} GetParams(ceph::real_time *_pmtime) : pmtime(_pmtime) {} virtual ~GetParams(); ceph::real_time *pmtime{nullptr}; }; struct RemoveParams { virtual ~RemoveParams() = 0; ceph::real_time mtime; }; struct MutateParams { ceph::real_time mtime; RGWMDLogStatus op_type; MutateParams() {} MutateParams(const ceph::real_time& _mtime, RGWMDLogStatus _op_type) : mtime(_mtime), op_type(_op_type) {} virtual ~MutateParams() {} }; enum Type { MDBE_SOBJ = 0, MDBE_OTP = 1, }; RGWSI_MetaBackend(CephContext *cct) : RGWServiceInstance(cct) {} virtual ~RGWSI_MetaBackend() {} virtual Type get_type() = 0; virtual RGWSI_MetaBackend_Handler *alloc_be_handler() = 0; virtual int call_with_get_params(ceph::real_time *pmtime, std::function<int(RGWSI_MetaBackend::GetParams&)>) = 0; /* these should be implemented by backends */ virtual int get_entry(RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::GetParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs=false) = 0; virtual int put_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::PutParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y) = 0; virtual int remove_entry(const DoutPrefixProvider *dpp, Context *ctx, const std::string& key, RGWSI_MetaBackend::RemoveParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y) = 0; virtual int list_init(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& marker) = 0; virtual int list_next(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, int max, std::list<std::string> *keys, bool *truncated) = 0; virtual int list_get_marker(RGWSI_MetaBackend::Context *ctx, std::string *marker) = 0; int call(std::function<int(RGWSI_MetaBackend::Context *)> f) { return call(std::nullopt, f); } virtual int call(std::optional<RGWSI_MetaBackend_CtxParams> opt, std::function<int(RGWSI_MetaBackend::Context *)> f) = 0; virtual int get_shard_id(RGWSI_MetaBackend::Context *ctx, const std::string& key, int *shard_id) = 0; /* higher level */ virtual int get(Context *ctx, const std::string& key, GetParams &params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs=false); virtual int put(Context *ctx, const std::string& key, PutParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); virtual int remove(Context *ctx, const std::string& key, RemoveParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); virtual int mutate(Context *ctx, const std::string& key, MutateParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, std::function<int()> f, const DoutPrefixProvider *dpp); }; class RGWSI_MetaBackend_Handler { RGWSI_MetaBackend *be{nullptr}; public: class Op { friend class RGWSI_MetaBackend_Handler; RGWSI_MetaBackend *be; RGWSI_MetaBackend::Context *be_ctx; Op(RGWSI_MetaBackend *_be, RGWSI_MetaBackend::Context *_ctx) : be(_be), be_ctx(_ctx) {} public: RGWSI_MetaBackend::Context *ctx() { return be_ctx; } int get(const std::string& key, RGWSI_MetaBackend::GetParams &params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { return be->get(be_ctx, key, params, objv_tracker, y, dpp); } int put(const std::string& key, RGWSI_MetaBackend::PutParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { return be->put(be_ctx, key, params, objv_tracker, y, dpp); } int remove(const std::string& key, RGWSI_MetaBackend::RemoveParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { return be->remove(be_ctx, key, params, objv_tracker, y, dpp); } int mutate(const std::string& key, RGWSI_MetaBackend::MutateParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, std::function<int()> f, const DoutPrefixProvider *dpp) { return be->mutate(be_ctx, key, params, objv_tracker, y, f, dpp); } int list_init(const DoutPrefixProvider *dpp, const std::string& marker) { return be->list_init(dpp, be_ctx, marker); } int list_next(const DoutPrefixProvider *dpp, int max, std::list<std::string> *keys, bool *truncated) { return be->list_next(dpp, be_ctx, max, keys, truncated); } int list_get_marker(std::string *marker) { return be->list_get_marker(be_ctx, marker); } int get_shard_id(const std::string& key, int *shard_id) { return be->get_shard_id(be_ctx, key, shard_id); } }; class Op_ManagedCtx : public Op { std::unique_ptr<RGWSI_MetaBackend::Context> pctx; public: Op_ManagedCtx(RGWSI_MetaBackend_Handler *handler); }; RGWSI_MetaBackend_Handler(RGWSI_MetaBackend *_be) : be(_be) {} virtual ~RGWSI_MetaBackend_Handler() {} int call(std::function<int(Op *)> f) { return call(std::nullopt, f); } virtual int call(std::optional<RGWSI_MetaBackend_CtxParams> bectx_params, std::function<int(Op *)> f); };
9,488
31.166102
119
h
null
ceph-main/src/rgw/services/svc_meta_be_otp.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_meta_be_otp.h" #include "rgw_tools.h" #include "rgw_metadata.h" #include "rgw_mdlog.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_MetaBackend_OTP::RGWSI_MetaBackend_OTP(CephContext *cct) : RGWSI_MetaBackend_SObj(cct) { } RGWSI_MetaBackend_OTP::~RGWSI_MetaBackend_OTP() { } string RGWSI_MetaBackend_OTP::get_meta_key(const rgw_user& user) { return string("otp:user:") + user.to_str(); } RGWSI_MetaBackend_Handler *RGWSI_MetaBackend_OTP::alloc_be_handler() { return new RGWSI_MetaBackend_Handler_OTP(this); } RGWSI_MetaBackend::Context *RGWSI_MetaBackend_OTP::alloc_ctx() { return new Context_OTP; } int RGWSI_MetaBackend_OTP::call_with_get_params(ceph::real_time *pmtime, std::function<int(RGWSI_MetaBackend::GetParams&)> cb) { otp_devices_list_t devices; RGWSI_MBOTP_GetParams params; params.pdevices = &devices; params.pmtime = pmtime; return cb(params); } int RGWSI_MetaBackend_OTP::get_entry(RGWSI_MetaBackend::Context *_ctx, const string& key, RGWSI_MetaBackend::GetParams& _params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs) { RGWSI_MBOTP_GetParams& params = static_cast<RGWSI_MBOTP_GetParams&>(_params); int r = cls_svc->mfa.list_mfa(dpp, key, params.pdevices, objv_tracker, params.pmtime, y); if (r < 0) { return r; } return 0; } int RGWSI_MetaBackend_OTP::put_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const string& key, RGWSI_MetaBackend::PutParams& _params, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_MBOTP_PutParams& params = static_cast<RGWSI_MBOTP_PutParams&>(_params); return cls_svc->mfa.set_mfa(dpp, key, params.devices, true, objv_tracker, params.mtime, y); }
2,284
29.878378
126
cc
null
ceph-main/src/rgw/services/svc_meta_be_otp.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_cls.h" #include "svc_meta_be.h" #include "svc_meta_be_sobj.h" #include "svc_sys_obj.h" using RGWSI_MBOTP_Handler_Module = RGWSI_MBSObj_Handler_Module; using RGWSI_MetaBackend_Handler_OTP = RGWSI_MetaBackend_Handler_SObj; using otp_devices_list_t = std::list<rados::cls::otp::otp_info_t>; struct RGWSI_MBOTP_GetParams : public RGWSI_MetaBackend::GetParams { otp_devices_list_t *pdevices{nullptr}; }; struct RGWSI_MBOTP_PutParams : public RGWSI_MetaBackend::PutParams { otp_devices_list_t devices; }; using RGWSI_MBOTP_RemoveParams = RGWSI_MBSObj_RemoveParams; class RGWSI_MetaBackend_OTP : public RGWSI_MetaBackend_SObj { RGWSI_Cls *cls_svc{nullptr}; public: struct Context_OTP : public RGWSI_MetaBackend_SObj::Context_SObj { otp_devices_list_t devices; }; RGWSI_MetaBackend_OTP(CephContext *cct); virtual ~RGWSI_MetaBackend_OTP(); RGWSI_MetaBackend::Type get_type() { return MDBE_OTP; } static std::string get_meta_key(const rgw_user& user); void init(RGWSI_SysObj *_sysobj_svc, RGWSI_MDLog *_mdlog_svc, RGWSI_Cls *_cls_svc) { RGWSI_MetaBackend_SObj::init(_sysobj_svc, _mdlog_svc); cls_svc = _cls_svc; } RGWSI_MetaBackend_Handler *alloc_be_handler() override; RGWSI_MetaBackend::Context *alloc_ctx() override; int call_with_get_params(ceph::real_time *pmtime, std::function<int(RGWSI_MetaBackend::GetParams&)> cb) override; int get_entry(RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::GetParams& _params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs=false); int put_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::PutParams& _params, RGWObjVersionTracker *objv_tracker, optional_yield y); };
2,477
26.533333
115
h
null
ceph-main/src/rgw/services/svc_meta_be_params.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 <variant> struct RGWSI_MetaBackend_CtxParams_SObj {}; using RGWSI_MetaBackend_CtxParams = std::variant<RGWSI_MetaBackend_CtxParams_SObj>;
578
21.269231
83
h
null
ceph-main/src/rgw/services/svc_meta_be_sobj.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_meta_be_sobj.h" #include "svc_meta_be_params.h" #include "svc_mdlog.h" #include "rgw_tools.h" #include "rgw_metadata.h" #include "rgw_mdlog.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_MetaBackend_SObj::RGWSI_MetaBackend_SObj(CephContext *cct) : RGWSI_MetaBackend(cct) { } RGWSI_MetaBackend_SObj::~RGWSI_MetaBackend_SObj() { } RGWSI_MetaBackend_Handler *RGWSI_MetaBackend_SObj::alloc_be_handler() { return new RGWSI_MetaBackend_Handler_SObj(this); } RGWSI_MetaBackend::Context *RGWSI_MetaBackend_SObj::alloc_ctx() { return new Context_SObj; } int RGWSI_MetaBackend_SObj::pre_modify(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, RGWMDLogStatus op_type, optional_yield y) { auto ctx = static_cast<Context_SObj *>(_ctx); int ret = RGWSI_MetaBackend::pre_modify(dpp, ctx, key, log_data, objv_tracker, op_type, y); if (ret < 0) { return ret; } /* if write version has not been set, and there's a read version, set it so that we can * log it */ if (objv_tracker) { log_data.read_version = objv_tracker->read_version; log_data.write_version = objv_tracker->write_version; } log_data.status = op_type; bufferlist logbl; encode(log_data, logbl); ret = mdlog_svc->add_entry(dpp, ctx->module->get_hash_key(key), ctx->module->get_section(), key, logbl); if (ret < 0) return ret; return 0; } int RGWSI_MetaBackend_SObj::post_modify(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, int ret, optional_yield y) { auto ctx = static_cast<Context_SObj *>(_ctx); if (ret >= 0) log_data.status = MDLOG_STATUS_COMPLETE; else log_data.status = MDLOG_STATUS_ABORT; bufferlist logbl; encode(log_data, logbl); int r = mdlog_svc->add_entry(dpp, ctx->module->get_hash_key(key), ctx->module->get_section(), key, logbl); if (ret < 0) return ret; if (r < 0) return r; return RGWSI_MetaBackend::post_modify(dpp, ctx, key, log_data, objv_tracker, ret, y); } int RGWSI_MetaBackend_SObj::get_shard_id(RGWSI_MetaBackend::Context *_ctx, const std::string& key, int *shard_id) { auto ctx = static_cast<Context_SObj *>(_ctx); *shard_id = mdlog_svc->get_shard_id(ctx->module->get_hash_key(key), shard_id); return 0; } int RGWSI_MetaBackend_SObj::call(std::optional<RGWSI_MetaBackend_CtxParams> opt, std::function<int(RGWSI_MetaBackend::Context *)> f) { RGWSI_MetaBackend_SObj::Context_SObj ctx; return f(&ctx); } void RGWSI_MetaBackend_SObj::Context_SObj::init(RGWSI_MetaBackend_Handler *h) { RGWSI_MetaBackend_Handler_SObj *handler = static_cast<RGWSI_MetaBackend_Handler_SObj *>(h); module = handler->module; } int RGWSI_MetaBackend_SObj::call_with_get_params(ceph::real_time *pmtime, std::function<int(RGWSI_MetaBackend::GetParams&)> cb) { bufferlist bl; RGWSI_MBSObj_GetParams params; params.pmtime = pmtime; params.pbl = &bl; return cb(params); } int RGWSI_MetaBackend_SObj::get_entry(RGWSI_MetaBackend::Context *_ctx, const string& key, GetParams& _params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs) { RGWSI_MetaBackend_SObj::Context_SObj *ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); RGWSI_MBSObj_GetParams& params = static_cast<RGWSI_MBSObj_GetParams&>(_params); rgw_pool pool; string oid; ctx->module->get_pool_and_oid(key, &pool, &oid); int ret = 0; ret = rgw_get_system_obj(sysobj_svc, pool, oid, *params.pbl, objv_tracker, params.pmtime, y, dpp, params.pattrs, params.cache_info, params.refresh_version, get_raw_attrs); return ret; } int RGWSI_MetaBackend_SObj::put_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const string& key, PutParams& _params, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_MetaBackend_SObj::Context_SObj *ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); RGWSI_MBSObj_PutParams& params = static_cast<RGWSI_MBSObj_PutParams&>(_params); rgw_pool pool; string oid; ctx->module->get_pool_and_oid(key, &pool, &oid); return rgw_put_system_obj(dpp, sysobj_svc, pool, oid, params.bl, params.exclusive, objv_tracker, params.mtime, y, params.pattrs); } int RGWSI_MetaBackend_SObj::remove_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const string& key, RemoveParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_MetaBackend_SObj::Context_SObj *ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); rgw_pool pool; string oid; ctx->module->get_pool_and_oid(key, &pool, &oid); rgw_raw_obj k(pool, oid); auto sysobj = sysobj_svc->get_obj(k); return sysobj.wop() .set_objv_tracker(objv_tracker) .remove(dpp, y); } int RGWSI_MetaBackend_SObj::list_init(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const string& marker) { RGWSI_MetaBackend_SObj::Context_SObj *ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); rgw_pool pool; string no_key; ctx->module->get_pool_and_oid(no_key, &pool, nullptr); ctx->list.pool = sysobj_svc->get_pool(pool); ctx->list.op.emplace(ctx->list.pool->op()); string prefix = ctx->module->get_oid_prefix(); ctx->list.op->init(dpp, marker, prefix); return 0; } int RGWSI_MetaBackend_SObj::list_next(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, int max, list<string> *keys, bool *truncated) { RGWSI_MetaBackend_SObj::Context_SObj *ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); vector<string> oids; keys->clear(); int ret = ctx->list.op->get_next(dpp, max, &oids, truncated); if (ret < 0 && ret != -ENOENT) return ret; if (ret == -ENOENT) { if (truncated) *truncated = false; return 0; } auto module = ctx->module; for (auto& o : oids) { if (!module->is_valid_oid(o)) { continue; } keys->emplace_back(module->oid_to_key(o)); } return 0; } int RGWSI_MetaBackend_SObj::list_get_marker(RGWSI_MetaBackend::Context *_ctx, string *marker) { RGWSI_MetaBackend_SObj::Context_SObj *ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); return ctx->list.op->get_marker(marker); }
8,036
31.538462
127
cc
null
ceph-main/src/rgw/services/svc_meta_be_sobj.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_meta_be.h" #include "svc_sys_obj.h" class RGWSI_MBSObj_Handler_Module : public RGWSI_MetaBackend::Module { protected: std::string section; public: RGWSI_MBSObj_Handler_Module(const std::string& _section) : section(_section) {} virtual void get_pool_and_oid(const std::string& key, rgw_pool *pool, std::string *oid) = 0; virtual const std::string& get_oid_prefix() = 0; virtual std::string key_to_oid(const std::string& key) = 0; virtual bool is_valid_oid(const std::string& oid) = 0; virtual std::string oid_to_key(const std::string& oid) = 0; const std::string& get_section() { return section; } /* key to use for hashing entries for log shard placement */ virtual std::string get_hash_key(const std::string& key) { return section + ":" + key; } }; struct RGWSI_MBSObj_GetParams : public RGWSI_MetaBackend::GetParams { bufferlist *pbl{nullptr}; std::map<std::string, bufferlist> *pattrs{nullptr}; rgw_cache_entry_info *cache_info{nullptr}; boost::optional<obj_version> refresh_version; RGWSI_MBSObj_GetParams() {} RGWSI_MBSObj_GetParams(bufferlist *_pbl, std::map<std::string, bufferlist> *_pattrs, ceph::real_time *_pmtime) : RGWSI_MetaBackend::GetParams(_pmtime), pbl(_pbl), pattrs(_pattrs) {} RGWSI_MBSObj_GetParams& set_cache_info(rgw_cache_entry_info *_cache_info) { cache_info = _cache_info; return *this; } RGWSI_MBSObj_GetParams& set_refresh_version(boost::optional<obj_version>& _refresh_version) { refresh_version = _refresh_version; return *this; } }; struct RGWSI_MBSObj_PutParams : public RGWSI_MetaBackend::PutParams { bufferlist bl; std::map<std::string, bufferlist> *pattrs{nullptr}; bool exclusive{false}; RGWSI_MBSObj_PutParams() {} RGWSI_MBSObj_PutParams(std::map<std::string, bufferlist> *_pattrs, const ceph::real_time& _mtime) : RGWSI_MetaBackend::PutParams(_mtime), pattrs(_pattrs) {} RGWSI_MBSObj_PutParams(bufferlist& _bl, std::map<std::string, bufferlist> *_pattrs, const ceph::real_time& _mtime, bool _exclusive) : RGWSI_MetaBackend::PutParams(_mtime), bl(_bl), pattrs(_pattrs), exclusive(_exclusive) {} }; struct RGWSI_MBSObj_RemoveParams : public RGWSI_MetaBackend::RemoveParams { }; class RGWSI_MetaBackend_SObj : public RGWSI_MetaBackend { protected: RGWSI_SysObj *sysobj_svc{nullptr}; public: struct Context_SObj : public RGWSI_MetaBackend::Context { RGWSI_MBSObj_Handler_Module *module{nullptr}; struct _list { std::optional<RGWSI_SysObj::Pool> pool; std::optional<RGWSI_SysObj::Pool::Op> op; } list; void init(RGWSI_MetaBackend_Handler *h) override; }; RGWSI_MetaBackend_SObj(CephContext *cct); virtual ~RGWSI_MetaBackend_SObj(); RGWSI_MetaBackend::Type get_type() { return MDBE_SOBJ; } void init(RGWSI_SysObj *_sysobj_svc, RGWSI_MDLog *_mdlog_svc) { base_init(_mdlog_svc); sysobj_svc = _sysobj_svc; } RGWSI_MetaBackend_Handler *alloc_be_handler() override; RGWSI_MetaBackend::Context *alloc_ctx() override; int call_with_get_params(ceph::real_time *pmtime, std::function<int(RGWSI_MetaBackend::GetParams&)> cb) override; int pre_modify(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, RGWMDLogStatus op_type, optional_yield y); int post_modify(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWMetadataLogData& log_data, RGWObjVersionTracker *objv_tracker, int ret, optional_yield y); int get_entry(RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::GetParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp, bool get_raw_attrs=false) override; int put_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::PutParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y) override; int remove_entry(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const std::string& key, RGWSI_MetaBackend::RemoveParams& params, RGWObjVersionTracker *objv_tracker, optional_yield y) override; int list_init(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, const std::string& marker) override; int list_next(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *_ctx, int max, std::list<std::string> *keys, bool *truncated) override; int list_get_marker(RGWSI_MetaBackend::Context *ctx, std::string *marker) override; int get_shard_id(RGWSI_MetaBackend::Context *ctx, const std::string& key, int *shard_id) override; int call(std::optional<RGWSI_MetaBackend_CtxParams> opt, std::function<int(RGWSI_MetaBackend::Context *)> f) override; }; class RGWSI_MetaBackend_Handler_SObj : public RGWSI_MetaBackend_Handler { friend class RGWSI_MetaBackend_SObj::Context_SObj; RGWSI_MBSObj_Handler_Module *module{nullptr}; public: RGWSI_MetaBackend_Handler_SObj(RGWSI_MetaBackend *be) : RGWSI_MetaBackend_Handler(be) {} void set_module(RGWSI_MBSObj_Handler_Module *_module) { module = _module; } RGWSI_MBSObj_Handler_Module *get_module() { return module; } };
6,733
33.533333
117
h
null
ceph-main/src/rgw/services/svc_meta_be_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once enum RGWSI_META_BE_TYPES { SOBJ = 1, OTP = 2, BUCKET = 3, BI = 4, USER = 5, };
528
18.592593
70
h
null
ceph-main/src/rgw/services/svc_notify.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "include/random.h" #include "include/Context.h" #include "common/errno.h" #include "rgw_cache.h" #include "svc_notify.h" #include "svc_finisher.h" #include "svc_zone.h" #include "svc_rados.h" #include "rgw_zone.h" #define dout_subsys ceph_subsys_rgw using namespace std; static string notify_oid_prefix = "notify"; RGWSI_Notify::~RGWSI_Notify() { shutdown(); } class RGWWatcher : public DoutPrefixProvider , public librados::WatchCtx2 { CephContext *cct; RGWSI_Notify *svc; int index; RGWSI_RADOS::Obj obj; uint64_t watch_handle; int register_ret{0}; bool unregister_done{false}; librados::AioCompletion *register_completion{nullptr}; class C_ReinitWatch : public Context { RGWWatcher *watcher; public: explicit C_ReinitWatch(RGWWatcher *_watcher) : watcher(_watcher) {} void finish(int r) override { watcher->reinit(); } }; CephContext *get_cct() const override { return cct; } unsigned get_subsys() const override { return dout_subsys; } std::ostream& gen_prefix(std::ostream& out) const override { return out << "rgw watcher librados: "; } public: RGWWatcher(CephContext *_cct, RGWSI_Notify *s, int i, RGWSI_RADOS::Obj& o) : cct(_cct), svc(s), index(i), obj(o), watch_handle(0) {} void handle_notify(uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) override { ldpp_dout(this, 10) << "RGWWatcher::handle_notify() " << " notify_id " << notify_id << " cookie " << cookie << " notifier " << notifier_id << " bl.length()=" << bl.length() << dendl; if (unlikely(svc->inject_notify_timeout_probability == 1) || (svc->inject_notify_timeout_probability > 0 && (svc->inject_notify_timeout_probability > ceph::util::generate_random_number(0.0, 1.0)))) { ldpp_dout(this, 0) << "RGWWatcher::handle_notify() dropping notification! " << "If this isn't what you want, set " << "rgw_inject_notify_timeout_probability to zero!" << dendl; return; } svc->watch_cb(this, notify_id, cookie, notifier_id, bl); bufferlist reply_bl; // empty reply payload obj.notify_ack(notify_id, cookie, reply_bl); } void handle_error(uint64_t cookie, int err) override { ldpp_dout(this, -1) << "RGWWatcher::handle_error cookie " << cookie << " err " << cpp_strerror(err) << dendl; svc->remove_watcher(index); svc->schedule_context(new C_ReinitWatch(this)); } void reinit() { if(!unregister_done) { int ret = unregister_watch(); if (ret < 0) { ldout(cct, 0) << "ERROR: unregister_watch() returned ret=" << ret << dendl; } } int ret = register_watch(); if (ret < 0) { ldout(cct, 0) << "ERROR: register_watch() returned ret=" << ret << dendl; svc->schedule_context(new C_ReinitWatch(this)); return; } } int unregister_watch() { int r = svc->unwatch(obj, watch_handle); unregister_done = true; if (r < 0) { return r; } svc->remove_watcher(index); return 0; } int register_watch_async() { if (register_completion) { register_completion->release(); register_completion = nullptr; } register_completion = librados::Rados::aio_create_completion(nullptr, nullptr); register_ret = obj.aio_watch(register_completion, &watch_handle, this); if (register_ret < 0) { register_completion->release(); return register_ret; } return 0; } int register_watch_finish() { if (register_ret < 0) { return register_ret; } if (!register_completion) { return -EINVAL; } register_completion->wait_for_complete(); int r = register_completion->get_return_value(); register_completion->release(); register_completion = nullptr; if (r < 0) { return r; } svc->add_watcher(index); unregister_done = false; return 0; } int register_watch() { int r = obj.watch(&watch_handle, this); if (r < 0) { return r; } svc->add_watcher(index); unregister_done = false; return 0; } }; class RGWSI_Notify_ShutdownCB : public RGWSI_Finisher::ShutdownCB { RGWSI_Notify *svc; public: RGWSI_Notify_ShutdownCB(RGWSI_Notify *_svc) : svc(_svc) {} void call() override { svc->shutdown(); } }; string RGWSI_Notify::get_control_oid(int i) { char buf[notify_oid_prefix.size() + 16]; snprintf(buf, sizeof(buf), "%s.%d", notify_oid_prefix.c_str(), i); return string(buf); } // do not call pick_obj_control before init_watch RGWSI_RADOS::Obj RGWSI_Notify::pick_control_obj(const string& key) { uint32_t r = ceph_str_hash_linux(key.c_str(), key.size()); int i = r % num_watchers; return notify_objs[i]; } int RGWSI_Notify::init_watch(const DoutPrefixProvider *dpp, optional_yield y) { num_watchers = cct->_conf->rgw_num_control_oids; bool compat_oid = (num_watchers == 0); if (num_watchers <= 0) num_watchers = 1; watchers = new RGWWatcher *[num_watchers]; int error = 0; notify_objs.resize(num_watchers); for (int i=0; i < num_watchers; i++) { string notify_oid; if (!compat_oid) { notify_oid = get_control_oid(i); } else { notify_oid = notify_oid_prefix; } notify_objs[i] = rados_svc->handle().obj({control_pool, notify_oid}); auto& notify_obj = notify_objs[i]; int r = notify_obj.open(dpp); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: notify_obj.open() returned r=" << r << dendl; return r; } librados::ObjectWriteOperation op; op.create(false); r = notify_obj.operate(dpp, &op, y); if (r < 0 && r != -EEXIST) { ldpp_dout(dpp, 0) << "ERROR: notify_obj.operate() returned r=" << r << dendl; return r; } RGWWatcher *watcher = new RGWWatcher(cct, this, i, notify_obj); watchers[i] = watcher; r = watcher->register_watch_async(); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: register_watch_aio() returned " << r << dendl; error = r; continue; } } for (int i = 0; i < num_watchers; ++i) { int r = watchers[i]->register_watch_finish(); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: async watch returned " << r << dendl; error = r; } } if (error < 0) { return error; } return 0; } void RGWSI_Notify::finalize_watch() { for (int i = 0; i < num_watchers; i++) { RGWWatcher *watcher = watchers[i]; watcher->unregister_watch(); delete watcher; } delete[] watchers; } int RGWSI_Notify::do_start(optional_yield y, const DoutPrefixProvider *dpp) { int r = zone_svc->start(y, dpp); if (r < 0) { return r; } assert(zone_svc->is_started()); /* otherwise there's an ordering problem */ r = rados_svc->start(y, dpp); if (r < 0) { return r; } r = finisher_svc->start(y, dpp); if (r < 0) { return r; } control_pool = zone_svc->get_zone_params().control_pool; int ret = init_watch(dpp, y); if (ret < 0) { ldpp_dout(dpp, -1) << "ERROR: failed to initialize watch: " << cpp_strerror(-ret) << dendl; return ret; } shutdown_cb = new RGWSI_Notify_ShutdownCB(this); int handle; finisher_svc->register_caller(shutdown_cb, &handle); finisher_handle = handle; return 0; } void RGWSI_Notify::shutdown() { if (finalized) { return; } if (finisher_handle) { finisher_svc->unregister_caller(*finisher_handle); } finalize_watch(); delete shutdown_cb; finalized = true; } int RGWSI_Notify::unwatch(RGWSI_RADOS::Obj& obj, uint64_t watch_handle) { int r = obj.unwatch(watch_handle); if (r < 0) { ldout(cct, 0) << "ERROR: rados->unwatch2() returned r=" << r << dendl; return r; } r = rados_svc->handle().watch_flush(); if (r < 0) { ldout(cct, 0) << "ERROR: rados->watch_flush() returned r=" << r << dendl; return r; } return 0; } void RGWSI_Notify::add_watcher(int i) { ldout(cct, 20) << "add_watcher() i=" << i << dendl; std::unique_lock l{watchers_lock}; watchers_set.insert(i); if (watchers_set.size() == (size_t)num_watchers) { ldout(cct, 2) << "all " << num_watchers << " watchers are set, enabling cache" << dendl; _set_enabled(true); } } void RGWSI_Notify::remove_watcher(int i) { ldout(cct, 20) << "remove_watcher() i=" << i << dendl; std::unique_lock l{watchers_lock}; size_t orig_size = watchers_set.size(); watchers_set.erase(i); if (orig_size == (size_t)num_watchers && watchers_set.size() < orig_size) { /* actually removed */ ldout(cct, 2) << "removed watcher, disabling cache" << dendl; _set_enabled(false); } } int RGWSI_Notify::watch_cb(const DoutPrefixProvider *dpp, uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) { std::shared_lock l{watchers_lock}; if (cb) { return cb->watch_cb(dpp, notify_id, cookie, notifier_id, bl); } return 0; } void RGWSI_Notify::set_enabled(bool status) { std::unique_lock l{watchers_lock}; _set_enabled(status); } void RGWSI_Notify::_set_enabled(bool status) { enabled = status; if (cb) { cb->set_enabled(status); } } int RGWSI_Notify::distribute(const DoutPrefixProvider *dpp, const string& key, const RGWCacheNotifyInfo& cni, optional_yield y) { /* The RGW uses the control pool to store the watch notify objects. The precedence in RGWSI_Notify::do_start is to call to zone_svc->start and later to init_watch(). The first time, RGW starts in the cluster, the RGW will try to create zone and zonegroup system object. In that case RGW will try to distribute the cache before it ran init_watch, which will lead to division by 0 in pick_obj_control (num_watchers is 0). */ if (num_watchers > 0) { RGWSI_RADOS::Obj notify_obj = pick_control_obj(key); ldpp_dout(dpp, 10) << "distributing notification oid=" << notify_obj.get_ref().obj << " cni=" << cni << dendl; return robust_notify(dpp, notify_obj, cni, y); } return 0; } int RGWSI_Notify::robust_notify(const DoutPrefixProvider *dpp, RGWSI_RADOS::Obj& notify_obj, const RGWCacheNotifyInfo& cni, optional_yield y) { bufferlist bl; encode(cni, bl); // First, try to send, without being fancy about it. auto r = notify_obj.notify(dpp, bl, 0, nullptr, y); if (r < 0) { ldpp_dout(dpp, 1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " Notify failed on object " << cni.obj << ": " << cpp_strerror(-r) << dendl; } // If we timed out, get serious. if (r == -ETIMEDOUT) { RGWCacheNotifyInfo info; info.op = INVALIDATE_OBJ; info.obj = cni.obj; bufferlist retrybl; encode(info, retrybl); for (auto tries = 0u; r == -ETIMEDOUT && tries < max_notify_retries; ++tries) { ldpp_dout(dpp, 1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " Invalidating obj=" << info.obj << " tries=" << tries << dendl; r = notify_obj.notify(dpp, bl, 0, nullptr, y); if (r < 0) { ldpp_dout(dpp, 1) << __PRETTY_FUNCTION__ << ":" << __LINE__ << " invalidation attempt " << tries << " failed: " << cpp_strerror(-r) << dendl; } } } return r; } void RGWSI_Notify::register_watch_cb(CB *_cb) { std::unique_lock l{watchers_lock}; cb = _cb; _set_enabled(enabled); } void RGWSI_Notify::schedule_context(Context *c) { finisher_svc->schedule_context(c); }
11,700
24.887168
134
cc
null
ceph-main/src/rgw/services/svc_notify.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_service.h" #include "svc_rados.h" class Context; class RGWSI_Zone; class RGWSI_Finisher; class RGWWatcher; class RGWSI_Notify_ShutdownCB; struct RGWCacheNotifyInfo; class RGWSI_Notify : public RGWServiceInstance { friend class RGWWatcher; friend class RGWSI_Notify_ShutdownCB; friend class RGWServices_Def; public: class CB; private: RGWSI_Zone *zone_svc{nullptr}; RGWSI_RADOS *rados_svc{nullptr}; RGWSI_Finisher *finisher_svc{nullptr}; ceph::shared_mutex watchers_lock = ceph::make_shared_mutex("watchers_lock"); rgw_pool control_pool; int num_watchers{0}; RGWWatcher **watchers{nullptr}; std::set<int> watchers_set; std::vector<RGWSI_RADOS::Obj> notify_objs; bool enabled{false}; double inject_notify_timeout_probability{0}; static constexpr unsigned max_notify_retries = 10; std::string get_control_oid(int i); RGWSI_RADOS::Obj pick_control_obj(const std::string& key); CB *cb{nullptr}; std::optional<int> finisher_handle; RGWSI_Notify_ShutdownCB *shutdown_cb{nullptr}; bool finalized{false}; int init_watch(const DoutPrefixProvider *dpp, optional_yield y); void finalize_watch(); void init(RGWSI_Zone *_zone_svc, RGWSI_RADOS *_rados_svc, RGWSI_Finisher *_finisher_svc) { zone_svc = _zone_svc; rados_svc = _rados_svc; finisher_svc = _finisher_svc; } int do_start(optional_yield, const DoutPrefixProvider *dpp) override; void shutdown() override; int unwatch(RGWSI_RADOS::Obj& obj, uint64_t watch_handle); void add_watcher(int i); void remove_watcher(int i); int watch_cb(const DoutPrefixProvider *dpp, uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl); void _set_enabled(bool status); void set_enabled(bool status); int robust_notify(const DoutPrefixProvider *dpp, RGWSI_RADOS::Obj& notify_obj, const RGWCacheNotifyInfo& bl, optional_yield y); void schedule_context(Context *c); public: RGWSI_Notify(CephContext *cct): RGWServiceInstance(cct) {} virtual ~RGWSI_Notify() override; class CB { public: virtual ~CB() {} virtual int watch_cb(const DoutPrefixProvider *dpp, uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) = 0; virtual void set_enabled(bool status) = 0; }; int distribute(const DoutPrefixProvider *dpp, const std::string& key, const RGWCacheNotifyInfo& bl, optional_yield y); void register_watch_cb(CB *cb); };
2,755
24.757009
101
h
null
ceph-main/src/rgw/services/svc_otp.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_otp.h" #include "svc_zone.h" #include "svc_meta.h" #include "svc_meta_be_sobj.h" #include "rgw_zone.h" #define dout_subsys ceph_subsys_rgw using namespace std; class RGW_MB_Handler_Module_OTP : public RGWSI_MBSObj_Handler_Module { RGWSI_Zone *zone_svc; string prefix; public: RGW_MB_Handler_Module_OTP(RGWSI_Zone *_zone_svc) : RGWSI_MBSObj_Handler_Module("otp"), zone_svc(_zone_svc) {} void get_pool_and_oid(const string& key, rgw_pool *pool, string *oid) override { if (pool) { *pool = zone_svc->get_zone_params().otp_pool; } if (oid) { *oid = key; } } const string& get_oid_prefix() override { return prefix; } bool is_valid_oid(const string& oid) override { return true; } string key_to_oid(const string& key) override { return key; } string oid_to_key(const string& oid) override { return oid; } }; RGWSI_OTP::RGWSI_OTP(CephContext *cct): RGWServiceInstance(cct) { } RGWSI_OTP::~RGWSI_OTP() { } void RGWSI_OTP::init(RGWSI_Zone *_zone_svc, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc) { svc.otp = this; svc.zone = _zone_svc; svc.meta = _meta_svc; svc.meta_be = _meta_be_svc; } int RGWSI_OTP::do_start(optional_yield, const DoutPrefixProvider *dpp) { /* create first backend handler for bucket entrypoints */ RGWSI_MetaBackend_Handler *_otp_be_handler; int r = svc.meta->create_be_handler(RGWSI_MetaBackend::Type::MDBE_OTP, &_otp_be_handler); if (r < 0) { ldout(ctx(), 0) << "ERROR: failed to create be handler: r=" << r << dendl; return r; } be_handler = _otp_be_handler; RGWSI_MetaBackend_Handler_OTP *otp_be_handler = static_cast<RGWSI_MetaBackend_Handler_OTP *>(_otp_be_handler); auto otp_be_module = new RGW_MB_Handler_Module_OTP(svc.zone); be_module.reset(otp_be_module); otp_be_handler->set_module(otp_be_module); return 0; } int RGWSI_OTP::read_all(RGWSI_OTP_BE_Ctx& ctx, const string& key, otp_devices_list_t *devices, real_time *pmtime, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { RGWSI_MBOTP_GetParams params; params.pdevices = devices; params.pmtime = pmtime; int ret = svc.meta_be->get_entry(ctx.get(), key, params, objv_tracker, y, dpp); if (ret < 0) { return ret; } return 0; } int RGWSI_OTP::read_all(RGWSI_OTP_BE_Ctx& ctx, const rgw_user& uid, otp_devices_list_t *devices, real_time *pmtime, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { return read_all(ctx, uid.to_str(), devices, pmtime, objv_tracker, y, dpp); } int RGWSI_OTP::store_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const string& key, const otp_devices_list_t& devices, real_time mtime, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_MBOTP_PutParams params; params.mtime = mtime; params.devices = devices; int ret = svc.meta_be->put_entry(dpp, ctx.get(), key, params, objv_tracker, y); if (ret < 0) { return ret; } return 0; } int RGWSI_OTP::store_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const rgw_user& uid, const otp_devices_list_t& devices, real_time mtime, RGWObjVersionTracker *objv_tracker, optional_yield y) { return store_all(dpp, ctx, uid.to_str(), devices, mtime, objv_tracker, y); } int RGWSI_OTP::remove_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const string& key, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_MBOTP_RemoveParams params; int ret = svc.meta_be->remove_entry(dpp, ctx.get(), key, params, objv_tracker, y); if (ret < 0) { return ret; } return 0; } int RGWSI_OTP::remove_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const rgw_user& uid, RGWObjVersionTracker *objv_tracker, optional_yield y) { return remove_all(dpp,ctx, uid.to_str(), objv_tracker, y); }
5,105
26.304813
112
cc
null
ceph-main/src/rgw/services/svc_otp.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 "cls/otp/cls_otp_types.h" #include "rgw_service.h" #include "svc_otp_types.h" #include "svc_meta_be_otp.h" class RGWSI_Zone; class RGWSI_OTP : public RGWServiceInstance { RGWSI_OTP_BE_Handler be_handler; std::unique_ptr<RGWSI_MetaBackend::Module> be_module; int do_start(optional_yield, const DoutPrefixProvider *dpp) override; public: struct Svc { RGWSI_OTP *otp{nullptr}; RGWSI_Zone *zone{nullptr}; RGWSI_Meta *meta{nullptr}; RGWSI_MetaBackend *meta_be{nullptr}; } svc; RGWSI_OTP(CephContext *cct); ~RGWSI_OTP(); RGWSI_OTP_BE_Handler& get_be_handler() { return be_handler; } void init(RGWSI_Zone *_zone_svc, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc); int read_all(RGWSI_OTP_BE_Ctx& ctx, const std::string& key, otp_devices_list_t *devices, real_time *pmtime, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); int read_all(RGWSI_OTP_BE_Ctx& ctx, const rgw_user& uid, otp_devices_list_t *devices, real_time *pmtime, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); int store_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const std::string& key, const otp_devices_list_t& devices, real_time mtime, RGWObjVersionTracker *objv_tracker, optional_yield y); int store_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const rgw_user& uid, const otp_devices_list_t& devices, real_time mtime, RGWObjVersionTracker *objv_tracker, optional_yield y); int remove_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const std::string& key, RGWObjVersionTracker *objv_tracker, optional_yield y); int remove_all(const DoutPrefixProvider *dpp, RGWSI_OTP_BE_Ctx& ctx, const rgw_user& uid, RGWObjVersionTracker *objv_tracker, optional_yield y); };
2,780
27.96875
71
h
null
ceph-main/src/rgw/services/svc_otp_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 "common/ptr_wrapper.h" #include "svc_meta_be.h" #include "svc_meta_be_types.h" class RGWSI_MetaBackend_Handler; using RGWSI_OTP_BE_Handler = ptr_wrapper<RGWSI_MetaBackend_Handler, RGWSI_META_BE_TYPES::OTP>; using RGWSI_OTP_BE_Ctx = ptr_wrapper<RGWSI_MetaBackend::Context, RGWSI_META_BE_TYPES::OTP>;
740
23.7
94
h
null
ceph-main/src/rgw/services/svc_quota.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_quota.h" #include "svc_zone.h" #include "rgw_zone.h" const RGWQuotaInfo& RGWSI_Quota::get_bucket_quota() const { return zone_svc->get_current_period().get_config().quota.bucket_quota; } const RGWQuotaInfo& RGWSI_Quota::get_user_quota() const { return zone_svc->get_current_period().get_config().quota.user_quota; }
443
22.368421
72
cc
null
ceph-main/src/rgw/services/svc_quota.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_service.h" class RGWSI_Quota : public RGWServiceInstance { RGWSI_Zone *zone_svc{nullptr}; public: RGWSI_Quota(CephContext *cct): RGWServiceInstance(cct) {} void init(RGWSI_Zone *_zone_svc) { zone_svc = _zone_svc; } const RGWQuotaInfo& get_bucket_quota() const; const RGWQuotaInfo& get_user_quota() const; };
463
19.173913
70
h
null
ceph-main/src/rgw/services/svc_rados.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_rados.h" #include "include/rados/librados.hpp" #include "common/errno.h" #include "osd/osd_types.h" #include "rgw_tools.h" #include "rgw_cr_rados.h" #include "auth/AuthRegistry.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_RADOS::RGWSI_RADOS(CephContext *cct) : RGWServiceInstance(cct) { } RGWSI_RADOS::~RGWSI_RADOS() { } int RGWSI_RADOS::do_start(optional_yield, const DoutPrefixProvider *dpp) { int ret = rados.init_with_context(cct); if (ret < 0) { return ret; } ret = rados.connect(); if (ret < 0) { return ret; } async_processor.reset(new RGWAsyncRadosProcessor(cct, cct->_conf->rgw_num_async_rados_threads)); async_processor->start(); return 0; } void RGWSI_RADOS::shutdown() { if (async_processor) { async_processor->stop(); } rados.shutdown(); } void RGWSI_RADOS::stop_processor() { if (async_processor) { async_processor->stop(); } } librados::Rados* RGWSI_RADOS::get_rados_handle() { return &rados; } std::string RGWSI_RADOS::cluster_fsid() { std::string fsid; (void) get_rados_handle()->cluster_fsid(&fsid); return fsid; } uint64_t RGWSI_RADOS::instance_id() { return get_rados_handle()->get_instance_id(); } int RGWSI_RADOS::open_pool_ctx(const DoutPrefixProvider *dpp, const rgw_pool& pool, librados::IoCtx& io_ctx, const OpenParams& params) { return rgw_init_ioctx(dpp, get_rados_handle(), pool, io_ctx, params.create, params.mostly_omap); } int RGWSI_RADOS::pool_iterate(const DoutPrefixProvider *dpp, librados::IoCtx& io_ctx, librados::NObjectIterator& iter, uint32_t num, vector<rgw_bucket_dir_entry>& objs, RGWAccessListFilter *filter, bool *is_truncated) { if (iter == io_ctx.nobjects_end()) return -ENOENT; uint32_t i; for (i = 0; i < num && iter != io_ctx.nobjects_end(); ++i, ++iter) { rgw_bucket_dir_entry e; string oid = iter->get_oid(); ldpp_dout(dpp, 20) << "RGWRados::pool_iterate: got " << oid << dendl; // fill it in with initial values; we may correct later if (filter && !filter->filter(oid, oid)) continue; e.key = oid; objs.push_back(e); } if (is_truncated) *is_truncated = (iter != io_ctx.nobjects_end()); return objs.size(); } RGWSI_RADOS::Obj::Obj(Pool& pool, const string& oid) : rados_svc(pool.rados_svc) { ref.pool = pool; ref.obj = rgw_raw_obj(pool.get_pool(), oid); } void RGWSI_RADOS::Obj::init(const rgw_raw_obj& obj) { ref.pool = RGWSI_RADOS::Pool(rados_svc, obj.pool); ref.obj = obj; } int RGWSI_RADOS::Obj::open(const DoutPrefixProvider *dpp) { int r = ref.pool.open(dpp); if (r < 0) { return r; } ref.pool.ioctx().locator_set_key(ref.obj.loc); return 0; } int RGWSI_RADOS::Obj::operate(const DoutPrefixProvider *dpp, librados::ObjectWriteOperation *op, optional_yield y, int flags) { return rgw_rados_operate(dpp, ref.pool.ioctx(), ref.obj.oid, op, y, flags); } int RGWSI_RADOS::Obj::operate(const DoutPrefixProvider *dpp, librados::ObjectReadOperation *op, bufferlist *pbl, optional_yield y, int flags) { return rgw_rados_operate(dpp, ref.pool.ioctx(), ref.obj.oid, op, pbl, y, flags); } int RGWSI_RADOS::Obj::aio_operate(librados::AioCompletion *c, librados::ObjectWriteOperation *op) { return ref.pool.ioctx().aio_operate(ref.obj.oid, c, op); } int RGWSI_RADOS::Obj::aio_operate(librados::AioCompletion *c, librados::ObjectReadOperation *op, bufferlist *pbl) { return ref.pool.ioctx().aio_operate(ref.obj.oid, c, op, pbl); } int RGWSI_RADOS::Obj::watch(uint64_t *handle, librados::WatchCtx2 *ctx) { return ref.pool.ioctx().watch2(ref.obj.oid, handle, ctx); } int RGWSI_RADOS::Obj::aio_watch(librados::AioCompletion *c, uint64_t *handle, librados::WatchCtx2 *ctx) { return ref.pool.ioctx().aio_watch(ref.obj.oid, c, handle, ctx); } int RGWSI_RADOS::Obj::unwatch(uint64_t handle) { return ref.pool.ioctx().unwatch2(handle); } int RGWSI_RADOS::Obj::notify(const DoutPrefixProvider *dpp, bufferlist& bl, uint64_t timeout_ms, bufferlist *pbl, optional_yield y) { return rgw_rados_notify(dpp, ref.pool.ioctx(), ref.obj.oid, bl, timeout_ms, pbl, y); } void RGWSI_RADOS::Obj::notify_ack(uint64_t notify_id, uint64_t cookie, bufferlist& bl) { ref.pool.ioctx().notify_ack(ref.obj.oid, notify_id, cookie, bl); } uint64_t RGWSI_RADOS::Obj::get_last_version() { return ref.pool.ioctx().get_last_version(); } int RGWSI_RADOS::Pool::create(const DoutPrefixProvider *dpp) { librados::Rados *rad = rados_svc->get_rados_handle(); int r = rad->pool_create(pool.name.c_str()); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: pool_create returned " << r << dendl; return r; } librados::IoCtx io_ctx; r = rad->ioctx_create(pool.name.c_str(), io_ctx); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: ioctx_create returned " << r << dendl; return r; } r = io_ctx.application_enable(pg_pool_t::APPLICATION_NAME_RGW, false); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: application_enable returned " << r << dendl; return r; } return 0; } int RGWSI_RADOS::Pool::create(const DoutPrefixProvider *dpp, const vector<rgw_pool>& pools, vector<int> *retcodes) { vector<librados::PoolAsyncCompletion *> completions; vector<int> rets; librados::Rados *rad = rados_svc->get_rados_handle(); for (auto iter = pools.begin(); iter != pools.end(); ++iter) { librados::PoolAsyncCompletion *c = librados::Rados::pool_async_create_completion(); completions.push_back(c); auto& pool = *iter; int ret = rad->pool_create_async(pool.name.c_str(), c); rets.push_back(ret); } vector<int>::iterator riter; vector<librados::PoolAsyncCompletion *>::iterator citer; bool error = false; ceph_assert(rets.size() == completions.size()); for (riter = rets.begin(), citer = completions.begin(); riter != rets.end(); ++riter, ++citer) { int r = *riter; librados::PoolAsyncCompletion *c = *citer; if (r == 0) { c->wait(); r = c->get_return_value(); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: async pool_create returned " << r << dendl; error = true; } } c->release(); retcodes->push_back(r); } if (error) { return 0; } std::vector<librados::IoCtx> io_ctxs; retcodes->clear(); for (auto pool : pools) { io_ctxs.emplace_back(); int ret = rad->ioctx_create(pool.name.c_str(), io_ctxs.back()); if (ret < 0) { ldpp_dout(dpp, 0) << "WARNING: ioctx_create returned " << ret << dendl; error = true; } retcodes->push_back(ret); } if (error) { return 0; } completions.clear(); for (auto &io_ctx : io_ctxs) { librados::PoolAsyncCompletion *c = librados::Rados::pool_async_create_completion(); completions.push_back(c); int ret = io_ctx.application_enable_async(pg_pool_t::APPLICATION_NAME_RGW, false, c); ceph_assert(ret == 0); } retcodes->clear(); for (auto c : completions) { c->wait(); int ret = c->get_return_value(); if (ret == -EOPNOTSUPP) { ret = 0; } else if (ret < 0) { ldpp_dout(dpp, 0) << "WARNING: async application_enable returned " << ret << dendl; error = true; } c->release(); retcodes->push_back(ret); } return 0; } int RGWSI_RADOS::Pool::lookup() { librados::Rados *rad = rados_svc->get_rados_handle(); int ret = rad->pool_lookup(pool.name.c_str()); if (ret < 0) { return ret; } return 0; } int RGWSI_RADOS::Pool::open(const DoutPrefixProvider *dpp, const OpenParams& params) { return rados_svc->open_pool_ctx(dpp, pool, state.ioctx, params); } int RGWSI_RADOS::Pool::List::init(const DoutPrefixProvider *dpp, const string& marker, RGWAccessListFilter *filter) { if (ctx.initialized) { return -EINVAL; } if (!pool) { return -EINVAL; } int r = pool->rados_svc->open_pool_ctx(dpp, pool->pool, ctx.ioctx); if (r < 0) { return r; } librados::ObjectCursor oc; if (!oc.from_str(marker)) { ldpp_dout(dpp, 10) << "failed to parse cursor: " << marker << dendl; return -EINVAL; } try { ctx.iter = ctx.ioctx.nobjects_begin(oc); ctx.filter = filter; ctx.initialized = true; return 0; } catch (const std::system_error& e) { r = -e.code().value(); ldpp_dout(dpp, 10) << "nobjects_begin threw " << e.what() << ", returning " << r << dendl; return r; } catch (const std::exception& e) { ldpp_dout(dpp, 10) << "nobjects_begin threw " << e.what() << ", returning -5" << dendl; return -EIO; } } int RGWSI_RADOS::Pool::List::get_next(const DoutPrefixProvider *dpp, int max, std::vector<string> *oids, bool *is_truncated) { if (!ctx.initialized) { return -EINVAL; } vector<rgw_bucket_dir_entry> objs; int r = pool->rados_svc->pool_iterate(dpp, ctx.ioctx, ctx.iter, max, objs, ctx.filter, is_truncated); if (r < 0) { if(r != -ENOENT) { ldpp_dout(dpp, 10) << "failed to list objects pool_iterate returned r=" << r << dendl; } return r; } for (auto& o : objs) { oids->push_back(o.key.name); } return oids->size(); } RGWSI_RADOS::Obj RGWSI_RADOS::Handle::obj(const rgw_raw_obj& o) { return RGWSI_RADOS::Obj(rados_svc, o); } int RGWSI_RADOS::Handle::watch_flush() { librados::Rados *rad = rados_svc->get_rados_handle(); return rad->watch_flush(); } int RGWSI_RADOS::Handle::mon_command(std::string cmd, const bufferlist& inbl, bufferlist *outbl, std::string *outs) { librados::Rados *rad = rados_svc->get_rados_handle(); return rad->mon_command(cmd, inbl, outbl, outs); } int RGWSI_RADOS::Pool::List::get_marker(string *marker) { if (!ctx.initialized) { return -EINVAL; } *marker = ctx.iter.get_cursor().to_str(); return 0; } int RGWSI_RADOS::clog_warn(const string& msg) { string cmd = "{" "\"prefix\": \"log\", " "\"level\": \"warn\", " "\"logtext\": [\"" + msg + "\"]" "}"; bufferlist inbl; auto h = handle(); return h.mon_command(cmd, inbl, nullptr, nullptr); } bool RGWSI_RADOS::check_secure_mon_conn(const DoutPrefixProvider *dpp) const { AuthRegistry reg(cct); reg.refresh_config(); std::vector<uint32_t> methods; std::vector<uint32_t> modes; reg.get_supported_methods(CEPH_ENTITY_TYPE_MON, &methods, &modes); ldpp_dout(dpp, 20) << __func__ << "(): auth registy supported: methods=" << methods << " modes=" << modes << dendl; for (auto method : methods) { if (!reg.is_secure_method(method)) { ldpp_dout(dpp, 20) << __func__ << "(): method " << method << " is insecure" << dendl; return false; } } for (auto mode : modes) { if (!reg.is_secure_mode(mode)) { ldpp_dout(dpp, 20) << __func__ << "(): mode " << mode << " is insecure" << dendl; return false; } } return true; }
11,560
24.921525
117
cc
null
ceph-main/src/rgw/services/svc_rados.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_service.h" #include "include/rados/librados.hpp" #include "common/async/yield_context.h" class RGWAsyncRadosProcessor; class RGWAccessListFilter { public: virtual ~RGWAccessListFilter() {} virtual bool filter(const std::string& name, std::string& key) = 0; }; struct RGWAccessListFilterPrefix : public RGWAccessListFilter { std::string prefix; explicit RGWAccessListFilterPrefix(const std::string& _prefix) : prefix(_prefix) {} bool filter(const std::string& name, std::string& key) override { return (prefix.compare(key.substr(0, prefix.size())) == 0); } }; class RGWSI_RADOS : public RGWServiceInstance { librados::Rados rados; std::unique_ptr<RGWAsyncRadosProcessor> async_processor; int do_start(optional_yield, const DoutPrefixProvider *dpp) override; public: struct OpenParams { bool create{true}; bool mostly_omap{false}; OpenParams() {} OpenParams& set_create(bool _create) { create = _create; return *this; } OpenParams& set_mostly_omap(bool _mostly_omap) { mostly_omap = _mostly_omap; return *this; } }; private: int open_pool_ctx(const DoutPrefixProvider *dpp, const rgw_pool& pool, librados::IoCtx& io_ctx, const OpenParams& params = {}); int pool_iterate(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, librados::NObjectIterator& iter, uint32_t num, std::vector<rgw_bucket_dir_entry>& objs, RGWAccessListFilter *filter, bool *is_truncated); public: RGWSI_RADOS(CephContext *cct); ~RGWSI_RADOS(); librados::Rados* get_rados_handle(); void init() {} void shutdown() override; void stop_processor(); std::string cluster_fsid(); uint64_t instance_id(); bool check_secure_mon_conn(const DoutPrefixProvider *dpp) const; RGWAsyncRadosProcessor *get_async_processor() { return async_processor.get(); } int clog_warn(const std::string& msg); class Handle; class Pool { friend class RGWSI_RADOS; friend Handle; friend class Obj; RGWSI_RADOS *rados_svc{nullptr}; rgw_pool pool; struct State { librados::IoCtx ioctx; } state; Pool(RGWSI_RADOS *_rados_svc, const rgw_pool& _pool) : rados_svc(_rados_svc), pool(_pool) {} Pool(RGWSI_RADOS *_rados_svc) : rados_svc(_rados_svc) {} public: Pool() {} int create(const DoutPrefixProvider *dpp); int create(const DoutPrefixProvider *dpp, const std::vector<rgw_pool>& pools, std::vector<int> *retcodes); int lookup(); int open(const DoutPrefixProvider *dpp, const OpenParams& params = {}); const rgw_pool& get_pool() { return pool; } librados::IoCtx& ioctx() & { return state.ioctx; } librados::IoCtx&& ioctx() && { return std::move(state.ioctx); } struct List { Pool *pool{nullptr}; struct Ctx { bool initialized{false}; librados::IoCtx ioctx; librados::NObjectIterator iter; RGWAccessListFilter *filter{nullptr}; } ctx; List() {} List(Pool *_pool) : pool(_pool) {} int init(const DoutPrefixProvider *dpp, const std::string& marker, RGWAccessListFilter *filter = nullptr); int get_next(const DoutPrefixProvider *dpp, int max, std::vector<std::string> *oids, bool *is_truncated); int get_marker(std::string *marker); }; List op() { return List(this); } friend List; }; struct rados_ref { RGWSI_RADOS::Pool pool; rgw_raw_obj obj; }; class Obj { friend class RGWSI_RADOS; friend class Handle; RGWSI_RADOS *rados_svc{nullptr}; rados_ref ref; void init(const rgw_raw_obj& obj); Obj(RGWSI_RADOS *_rados_svc, const rgw_raw_obj& _obj) : rados_svc(_rados_svc) { init(_obj); } Obj(Pool& pool, const std::string& oid); public: Obj() {} int open(const DoutPrefixProvider *dpp); int operate(const DoutPrefixProvider *dpp, librados::ObjectWriteOperation *op, optional_yield y, int flags = 0); int operate(const DoutPrefixProvider *dpp, librados::ObjectReadOperation *op, bufferlist *pbl, optional_yield y, int flags = 0); int aio_operate(librados::AioCompletion *c, librados::ObjectWriteOperation *op); int aio_operate(librados::AioCompletion *c, librados::ObjectReadOperation *op, bufferlist *pbl); int watch(uint64_t *handle, librados::WatchCtx2 *ctx); int aio_watch(librados::AioCompletion *c, uint64_t *handle, librados::WatchCtx2 *ctx); int unwatch(uint64_t handle); int notify(const DoutPrefixProvider *dpp, bufferlist& bl, uint64_t timeout_ms, bufferlist *pbl, optional_yield y); void notify_ack(uint64_t notify_id, uint64_t cookie, bufferlist& bl); uint64_t get_last_version(); rados_ref& get_ref() { return ref; } const rados_ref& get_ref() const { return ref; } const rgw_raw_obj& get_raw_obj() const { return ref.obj; } }; class Handle { friend class RGWSI_RADOS; RGWSI_RADOS *rados_svc{nullptr}; Handle(RGWSI_RADOS *_rados_svc) : rados_svc(_rados_svc) {} public: Obj obj(const rgw_raw_obj& o); Pool pool(const rgw_pool& p) { return Pool(rados_svc, p); } int watch_flush(); int mon_command(std::string cmd, const bufferlist& inbl, bufferlist *outbl, std::string *outs); }; Handle handle() { return Handle(this); } Obj obj(const rgw_raw_obj& o) { return Obj(this, o); } Obj obj(Pool& pool, const std::string& oid) { return Obj(pool, oid); } Pool pool() { return Pool(this); } Pool pool(const rgw_pool& p) { return Pool(this, p); } friend Obj; friend Pool; friend Pool::List; }; using rgw_rados_ref = RGWSI_RADOS::rados_ref; inline std::ostream& operator<<(std::ostream& out, const RGWSI_RADOS::Obj& obj) { return out << obj.get_raw_obj(); }
6,282
23.833992
112
h
null
ceph-main/src/rgw/services/svc_role_rados.cc
#include "svc_role_rados.h" #include "svc_meta_be_sobj.h" #include "svc_meta.h" #include "rgw_role.h" #include "rgw_zone.h" #include "svc_zone.h" #include "rgw_tools.h" #define dout_subsys ceph_subsys_rgw class RGWSI_Role_Module : public RGWSI_MBSObj_Handler_Module { RGWSI_Role_RADOS::Svc& svc; const std::string prefix; public: RGWSI_Role_Module(RGWSI_Role_RADOS::Svc& _svc): RGWSI_MBSObj_Handler_Module("roles"), svc(_svc), prefix(role_oid_prefix) {} void get_pool_and_oid(const std::string& key, rgw_pool *pool, std::string *oid) override { if (pool) { *pool = svc.zone->get_zone_params().roles_pool; } if (oid) { *oid = key_to_oid(key); } } bool is_valid_oid(const std::string& oid) override { return boost::algorithm::starts_with(oid, prefix); } std::string key_to_oid(const std::string& key) override { return prefix + key; } // This is called after `is_valid_oid` and is assumed to be a valid oid std::string oid_to_key(const std::string& oid) override { return oid.substr(prefix.size()); } const std::string& get_oid_prefix() { return prefix; } }; RGWSI_MetaBackend_Handler* RGWSI_Role_RADOS::get_be_handler() { return be_handler; } void RGWSI_Role_RADOS::init(RGWSI_Zone *_zone_svc, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc, RGWSI_SysObj *_sysobj_svc) { svc.zone = _zone_svc; svc.meta = _meta_svc; svc.meta_be = _meta_be_svc; svc.sysobj = _sysobj_svc; } int RGWSI_Role_RADOS::do_start(optional_yield y, const DoutPrefixProvider *dpp) { int r = svc.meta->create_be_handler(RGWSI_MetaBackend::Type::MDBE_SOBJ, &be_handler); if (r < 0) { ldout(ctx(), 0) << "ERROR: failed to create be_handler for Roles: r=" << r <<dendl; return r; } auto module = new RGWSI_Role_Module(svc); RGWSI_MetaBackend_Handler_SObj* bh= static_cast<RGWSI_MetaBackend_Handler_SObj *>(be_handler); be_module.reset(module); bh->set_module(module); return 0; }
2,264
26.289157
96
cc
null
ceph-main/src/rgw/services/svc_role_rados.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 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 "rgw_service.h" #include "rgw_role.h" #include "svc_meta_be.h" class RGWSI_Role_RADOS: public RGWServiceInstance { public: struct Svc { RGWSI_Zone *zone{nullptr}; RGWSI_Meta *meta{nullptr}; RGWSI_MetaBackend *meta_be{nullptr}; RGWSI_SysObj *sysobj{nullptr}; } svc; RGWSI_Role_RADOS(CephContext *cct) : RGWServiceInstance(cct) {} ~RGWSI_Role_RADOS() {} void init(RGWSI_Zone *_zone_svc, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc, RGWSI_SysObj *_sysobj_svc); RGWSI_MetaBackend_Handler * get_be_handler(); int do_start(optional_yield y, const DoutPrefixProvider *dpp) override; private: RGWSI_MetaBackend_Handler *be_handler; std::unique_ptr<RGWSI_MetaBackend::Module> be_module; }; static const std::string role_name_oid_prefix = "role_names."; static const std::string role_oid_prefix = "roles."; static const std::string role_path_oid_prefix = "role_paths.";
1,357
25.627451
73
h
null
ceph-main/src/rgw/services/svc_sync_modules.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_sync_modules.h" #include "svc_zone.h" #include "rgw_sync_module.h" #include "rgw_zone.h" #define dout_subsys ceph_subsys_rgw void RGWSI_SyncModules::init(RGWSI_Zone *zone_svc) { svc.zone = zone_svc; sync_modules_manager = new RGWSyncModulesManager(); rgw_register_sync_modules(sync_modules_manager); } int RGWSI_SyncModules::do_start(optional_yield, const DoutPrefixProvider *dpp) { auto& zone_public_config = svc.zone->get_zone(); int ret = sync_modules_manager->create_instance(dpp, cct, zone_public_config.tier_type, svc.zone->get_zone_params().tier_config, &sync_module); if (ret < 0) { ldpp_dout(dpp, -1) << "ERROR: failed to start sync module instance, ret=" << ret << dendl; if (ret == -ENOENT) { ldpp_dout(dpp, -1) << "ERROR: " << zone_public_config.tier_type << " sync module does not exist. valid sync modules: " << sync_modules_manager->get_registered_module_names() << dendl; } return ret; } ldpp_dout(dpp, 20) << "started sync module instance, tier type = " << zone_public_config.tier_type << dendl; return 0; } RGWSI_SyncModules::~RGWSI_SyncModules() { delete sync_modules_manager; }
1,295
27.8
145
cc
null
ceph-main/src/rgw/services/svc_sync_modules.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_service.h" #include "rgw_sync_module.h" class RGWSI_Zone; class RGWSyncModulesManager; class RGWSI_SyncModules : public RGWServiceInstance { RGWSyncModulesManager *sync_modules_manager{nullptr}; RGWSyncModuleInstanceRef sync_module; struct Svc { RGWSI_Zone *zone{nullptr}; } svc; public: RGWSI_SyncModules(CephContext *cct): RGWServiceInstance(cct) {} ~RGWSI_SyncModules(); RGWSyncModulesManager *get_manager() { return sync_modules_manager; } void init(RGWSI_Zone *zone_svc); int do_start(optional_yield, const DoutPrefixProvider *dpp) override; RGWSyncModuleInstanceRef& get_sync_module() { return sync_module; } };
790
21.6
71
h
null
ceph-main/src/rgw/services/svc_sys_obj.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_sys_obj.h" #include "svc_sys_obj_core.h" #include "svc_rados.h" #include "svc_zone.h" #include "rgw_zone.h" #define dout_subsys ceph_subsys_rgw using namespace std; RGWSI_SysObj::Obj RGWSI_SysObj::get_obj(const rgw_raw_obj& obj) { return Obj(core_svc, obj); } RGWSI_SysObj::Obj::ROp::ROp(Obj& _source) : source(_source) { state.emplace<RGWSI_SysObj_Core::GetObjState>(); } int RGWSI_SysObj::Obj::ROp::stat(optional_yield y, const DoutPrefixProvider *dpp) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->stat(*state, obj, attrs, raw_attrs, lastmod, obj_size, objv_tracker, y, dpp); } int RGWSI_SysObj::Obj::ROp::read(const DoutPrefixProvider *dpp, int64_t ofs, int64_t end, bufferlist *bl, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); return svc->read(dpp, *state, objv_tracker, obj, bl, ofs, end, lastmod, obj_size, attrs, raw_attrs, cache_info, refresh_version, y); } int RGWSI_SysObj::Obj::ROp::get_attr(const DoutPrefixProvider *dpp, const char *name, bufferlist *dest, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); return svc->get_attr(dpp, obj, name, dest, y); } int RGWSI_SysObj::Obj::WOp::remove(const DoutPrefixProvider *dpp, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); return svc->remove(dpp, objv_tracker, obj, y); } int RGWSI_SysObj::Obj::WOp::write(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); return svc->write(dpp, obj, pmtime, attrs, exclusive, bl, objv_tracker, mtime, y); } int RGWSI_SysObj::Obj::WOp::write_data(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); return svc->write_data(dpp, obj, bl, exclusive, objv_tracker, y); } int RGWSI_SysObj::Obj::WOp::write_attrs(const DoutPrefixProvider *dpp, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); return svc->set_attrs(dpp, obj, attrs, nullptr, objv_tracker, exclusive, y); } int RGWSI_SysObj::Obj::WOp::write_attr(const DoutPrefixProvider *dpp, const char *name, bufferlist& bl, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.get_obj(); map<string, bufferlist> m; m[name] = bl; return svc->set_attrs(dpp, obj, m, nullptr, objv_tracker, exclusive, y); } int RGWSI_SysObj::Pool::list_prefixed_objs(const DoutPrefixProvider *dpp, const string& prefix, std::function<void(const string&)> cb) { return core_svc->pool_list_prefixed_objs(dpp, pool, prefix, cb); } int RGWSI_SysObj::Pool::Op::init(const DoutPrefixProvider *dpp, const string& marker, const string& prefix) { return source.core_svc->pool_list_objects_init(dpp, source.pool, marker, prefix, &ctx); } int RGWSI_SysObj::Pool::Op::get_next(const DoutPrefixProvider *dpp, int max, vector<string> *oids, bool *is_truncated) { return source.core_svc->pool_list_objects_next(dpp, ctx, max, oids, is_truncated); } int RGWSI_SysObj::Pool::Op::get_marker(string *marker) { return source.core_svc->pool_list_objects_get_marker(ctx, marker); } int RGWSI_SysObj::Obj::OmapOp::get_all(const DoutPrefixProvider *dpp, std::map<string, bufferlist> *m, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->omap_get_all(dpp, obj, m, y); } int RGWSI_SysObj::Obj::OmapOp::get_vals(const DoutPrefixProvider *dpp, const string& marker, uint64_t count, std::map<string, bufferlist> *m, bool *pmore, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->omap_get_vals(dpp, obj, marker, count, m, pmore, y); } int RGWSI_SysObj::Obj::OmapOp::set(const DoutPrefixProvider *dpp, const std::string& key, bufferlist& bl, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->omap_set(dpp, obj, key, bl, must_exist, y); } int RGWSI_SysObj::Obj::OmapOp::set(const DoutPrefixProvider *dpp, const map<std::string, bufferlist>& m, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->omap_set(dpp, obj, m, must_exist, y); } int RGWSI_SysObj::Obj::OmapOp::del(const DoutPrefixProvider *dpp, const std::string& key, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->omap_del(dpp, obj, key, y); } int RGWSI_SysObj::Obj::WNOp::notify(const DoutPrefixProvider *dpp, bufferlist& bl, uint64_t timeout_ms, bufferlist *pbl, optional_yield y) { RGWSI_SysObj_Core *svc = source.core_svc; rgw_raw_obj& obj = source.obj; return svc->notify(dpp, obj, bl, timeout_ms, pbl, y); } RGWSI_Zone *RGWSI_SysObj::get_zone_svc() { return core_svc->get_zone_svc(); }
5,749
30.25
134
cc
null
ceph-main/src/rgw/services/svc_sys_obj.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/static_ptr.h" #include "rgw_service.h" #include "svc_rados.h" #include "svc_sys_obj_types.h" #include "svc_sys_obj_core_types.h" class RGWSI_Zone; class RGWSI_SysObj; struct rgw_cache_entry_info; class RGWSI_SysObj : public RGWServiceInstance { friend struct RGWServices_Def; public: class Obj { friend class ROp; RGWSI_SysObj_Core *core_svc; rgw_raw_obj obj; public: Obj(RGWSI_SysObj_Core *_core_svc, const rgw_raw_obj& _obj) : core_svc(_core_svc), obj(_obj) {} rgw_raw_obj& get_obj() { return obj; } struct ROp { Obj& source; ceph::static_ptr<RGWSI_SysObj_Obj_GetObjState, sizeof(RGWSI_SysObj_Core_GetObjState)> state; RGWObjVersionTracker *objv_tracker{nullptr}; std::map<std::string, bufferlist> *attrs{nullptr}; bool raw_attrs{false}; boost::optional<obj_version> refresh_version{boost::none}; ceph::real_time *lastmod{nullptr}; uint64_t *obj_size{nullptr}; rgw_cache_entry_info *cache_info{nullptr}; ROp& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } ROp& set_last_mod(ceph::real_time *_lastmod) { lastmod = _lastmod; return *this; } ROp& set_obj_size(uint64_t *_obj_size) { obj_size = _obj_size; return *this; } ROp& set_attrs(std::map<std::string, bufferlist> *_attrs) { attrs = _attrs; return *this; } ROp& set_raw_attrs(bool ra) { raw_attrs = ra; return *this; } ROp& set_refresh_version(boost::optional<obj_version>& rf) { refresh_version = rf; return *this; } ROp& set_cache_info(rgw_cache_entry_info *ci) { cache_info = ci; return *this; } ROp(Obj& _source); int stat(optional_yield y, const DoutPrefixProvider *dpp); int read(const DoutPrefixProvider *dpp, int64_t ofs, int64_t end, bufferlist *pbl, optional_yield y); int read(const DoutPrefixProvider *dpp, bufferlist *pbl, optional_yield y) { return read(dpp, 0, -1, pbl, y); } int get_attr(const DoutPrefixProvider *dpp, const char *name, bufferlist *dest, optional_yield y); }; struct WOp { Obj& source; RGWObjVersionTracker *objv_tracker{nullptr}; std::map<std::string, bufferlist> attrs; ceph::real_time mtime; ceph::real_time *pmtime{nullptr}; bool exclusive{false}; WOp& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } WOp& set_attrs(std::map<std::string, bufferlist>& _attrs) { attrs = _attrs; return *this; } WOp& set_attrs(std::map<std::string, bufferlist>&& _attrs) { attrs = _attrs; return *this; } WOp& set_mtime(const ceph::real_time& _mtime) { mtime = _mtime; return *this; } WOp& set_pmtime(ceph::real_time *_pmtime) { pmtime = _pmtime; return *this; } WOp& set_exclusive(bool _exclusive = true) { exclusive = _exclusive; return *this; } WOp(Obj& _source) : source(_source) {} int remove(const DoutPrefixProvider *dpp, optional_yield y); int write(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y); int write_data(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y); /* write data only */ int write_attrs(const DoutPrefixProvider *dpp, optional_yield y); /* write attrs only */ int write_attr(const DoutPrefixProvider *dpp, const char *name, bufferlist& bl, optional_yield y); /* write attrs only */ }; struct OmapOp { Obj& source; bool must_exist{false}; OmapOp& set_must_exist(bool _must_exist = true) { must_exist = _must_exist; return *this; } OmapOp(Obj& _source) : source(_source) {} int get_all(const DoutPrefixProvider *dpp, std::map<std::string, bufferlist> *m, optional_yield y); int get_vals(const DoutPrefixProvider *dpp, const std::string& marker, uint64_t count, std::map<std::string, bufferlist> *m, bool *pmore, optional_yield y); int set(const DoutPrefixProvider *dpp, const std::string& key, bufferlist& bl, optional_yield y); int set(const DoutPrefixProvider *dpp, const std::map<std::string, bufferlist>& m, optional_yield y); int del(const DoutPrefixProvider *dpp, const std::string& key, optional_yield y); }; struct WNOp { Obj& source; WNOp(Obj& _source) : source(_source) {} int notify(const DoutPrefixProvider *dpp, bufferlist& bl, uint64_t timeout_ms, bufferlist *pbl, optional_yield y); }; ROp rop() { return ROp(*this); } WOp wop() { return WOp(*this); } OmapOp omap() { return OmapOp(*this); } WNOp wn() { return WNOp(*this); } }; class Pool { friend class Op; friend class RGWSI_SysObj_Core; RGWSI_SysObj_Core *core_svc; rgw_pool pool; protected: using ListImplInfo = RGWSI_SysObj_Pool_ListInfo; struct ListCtx { ceph::static_ptr<ListImplInfo, sizeof(RGWSI_SysObj_Core_PoolListImplInfo)> impl; /* update this if creating new backend types */ }; public: Pool(RGWSI_SysObj_Core *_core_svc, const rgw_pool& _pool) : core_svc(_core_svc), pool(_pool) {} rgw_pool& get_pool() { return pool; } struct Op { Pool& source; ListCtx ctx; Op(Pool& _source) : source(_source) {} int init(const DoutPrefixProvider *dpp, const std::string& marker, const std::string& prefix); int get_next(const DoutPrefixProvider *dpp, int max, std::vector<std::string> *oids, bool *is_truncated); int get_marker(std::string *marker); }; int list_prefixed_objs(const DoutPrefixProvider *dpp, const std::string& prefix, std::function<void(const std::string&)> cb); template <typename Container> int list_prefixed_objs(const DoutPrefixProvider *dpp, const std::string& prefix, Container *result) { return list_prefixed_objs(dpp, prefix, [&](const std::string& val) { result->push_back(val); }); } Op op() { return Op(*this); } }; friend class Obj; friend class Obj::ROp; friend class Obj::WOp; friend class Pool; friend class Pool::Op; protected: RGWSI_RADOS *rados_svc{nullptr}; RGWSI_SysObj_Core *core_svc{nullptr}; void init(RGWSI_RADOS *_rados_svc, RGWSI_SysObj_Core *_core_svc) { rados_svc = _rados_svc; core_svc = _core_svc; } public: RGWSI_SysObj(CephContext *cct): RGWServiceInstance(cct) {} Obj get_obj(const rgw_raw_obj& obj); Pool get_pool(const rgw_pool& pool) { return Pool(core_svc, pool); } RGWSI_Zone *get_zone_svc(); }; using RGWSysObj = RGWSI_SysObj::Obj;
7,197
25.560886
134
h
null
ceph-main/src/rgw/services/svc_sys_obj_cache.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "common/admin_socket.h" #include "svc_sys_obj_cache.h" #include "svc_zone.h" #include "svc_notify.h" #include "rgw_zone.h" #include "rgw_tools.h" #define dout_subsys ceph_subsys_rgw using namespace std; class RGWSI_SysObj_Cache_CB : public RGWSI_Notify::CB { RGWSI_SysObj_Cache *svc; public: RGWSI_SysObj_Cache_CB(RGWSI_SysObj_Cache *_svc) : svc(_svc) {} int watch_cb(const DoutPrefixProvider *dpp, uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) { return svc->watch_cb(dpp, notify_id, cookie, notifier_id, bl); } void set_enabled(bool status) { svc->set_enabled(status); } }; int RGWSI_SysObj_Cache::do_start(optional_yield y, const DoutPrefixProvider *dpp) { int r = asocket.start(); if (r < 0) { return r; } r = RGWSI_SysObj_Core::do_start(y, dpp); if (r < 0) { return r; } r = notify_svc->start(y, dpp); if (r < 0) { return r; } assert(notify_svc->is_started()); cb.reset(new RGWSI_SysObj_Cache_CB(this)); notify_svc->register_watch_cb(cb.get()); return 0; } void RGWSI_SysObj_Cache::shutdown() { asocket.shutdown(); RGWSI_SysObj_Core::shutdown(); } static string normal_name(rgw_pool& pool, const std::string& oid) { std::string buf; buf.reserve(pool.name.size() + pool.ns.size() + oid.size() + 2); buf.append(pool.name).append("+").append(pool.ns).append("+").append(oid); return buf; } void RGWSI_SysObj_Cache::normalize_pool_and_obj(const rgw_pool& src_pool, const string& src_obj, rgw_pool& dst_pool, string& dst_obj) { if (src_obj.size()) { dst_pool = src_pool; dst_obj = src_obj; } else { dst_pool = zone_svc->get_zone_params().domain_root; dst_obj = src_pool.name; } } int RGWSI_SysObj_Cache::remove(const DoutPrefixProvider *dpp, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, optional_yield y) { rgw_pool pool; string oid; normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); string name = normal_name(pool, oid); cache.invalidate_remove(dpp, name); ObjectCacheInfo info; int r = distribute_cache(dpp, name, obj, info, INVALIDATE_OBJ, y); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: " << __func__ << "(): failed to distribute cache: r=" << r << dendl; } return RGWSI_SysObj_Core::remove(dpp, objv_tracker, obj, y); } int RGWSI_SysObj_Cache::read(const DoutPrefixProvider *dpp, RGWSI_SysObj_Obj_GetObjState& read_state, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, bufferlist *obl, off_t ofs, off_t end, ceph::real_time* pmtime, uint64_t* psize, map<string, bufferlist> *attrs, bool raw_attrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version> refresh_version, optional_yield y) { rgw_pool pool; string oid; if (ofs != 0) { return RGWSI_SysObj_Core::read(dpp, read_state, objv_tracker, obj, obl, ofs, end, pmtime, psize, attrs, raw_attrs, cache_info, refresh_version, y); } normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); string name = normal_name(pool, oid); ObjectCacheInfo info; uint32_t flags = (end != 0 ? CACHE_FLAG_DATA : 0); if (objv_tracker) flags |= CACHE_FLAG_OBJV; if (pmtime || psize) flags |= CACHE_FLAG_META; if (attrs) flags |= CACHE_FLAG_XATTRS; int r = cache.get(dpp, name, info, flags, cache_info); if (r == 0 && (!refresh_version || !info.version.compare(&(*refresh_version)))) { if (info.status < 0) return info.status; bufferlist& bl = info.data; bufferlist::iterator i = bl.begin(); obl->clear(); i.copy_all(*obl); if (objv_tracker) objv_tracker->read_version = info.version; if (pmtime) { *pmtime = info.meta.mtime; } if (psize) { *psize = info.meta.size; } if (attrs) { if (raw_attrs) { *attrs = info.xattrs; } else { rgw_filter_attrset(info.xattrs, RGW_ATTR_PREFIX, attrs); } } return obl->length(); } if(r == -ENODATA) return -ENOENT; // if we only ask for one of mtime or size, ask for the other too so we can // satisfy CACHE_FLAG_META uint64_t size = 0; real_time mtime; if (pmtime) { if (!psize) { psize = &size; } } else if (psize) { if (!pmtime) { pmtime = &mtime; } } map<string, bufferlist> unfiltered_attrset; r = RGWSI_SysObj_Core::read(dpp, read_state, objv_tracker, obj, obl, ofs, end, pmtime, psize, (attrs ? &unfiltered_attrset : nullptr), true, /* cache unfiltered attrs */ cache_info, refresh_version, y); if (r < 0) { if (r == -ENOENT) { // only update ENOENT, we'd rather retry other errors info.status = r; cache.put(dpp, name, info, cache_info); } return r; } if (obl->length() == end + 1) { /* in this case, most likely object contains more data, we can't cache it */ flags &= ~CACHE_FLAG_DATA; } else { bufferptr p(r); bufferlist& bl = info.data; bl.clear(); bufferlist::iterator o = obl->begin(); o.copy_all(bl); } info.status = 0; info.flags = flags; if (objv_tracker) { info.version = objv_tracker->read_version; } if (pmtime) { info.meta.mtime = *pmtime; } if (psize) { info.meta.size = *psize; } if (attrs) { info.xattrs = std::move(unfiltered_attrset); if (raw_attrs) { *attrs = info.xattrs; } else { rgw_filter_attrset(info.xattrs, RGW_ATTR_PREFIX, attrs); } } cache.put(dpp, name, info, cache_info); return r; } int RGWSI_SysObj_Cache::get_attr(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const char *attr_name, bufferlist *dest, optional_yield y) { rgw_pool pool; string oid; normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); string name = normal_name(pool, oid); ObjectCacheInfo info; uint32_t flags = CACHE_FLAG_XATTRS; int r = cache.get(dpp, name, info, flags, nullptr); if (r == 0) { if (info.status < 0) return info.status; auto iter = info.xattrs.find(attr_name); if (iter == info.xattrs.end()) { return -ENODATA; } *dest = iter->second; return dest->length(); } else if (r == -ENODATA) { return -ENOENT; } /* don't try to cache this one */ return RGWSI_SysObj_Core::get_attr(dpp, obj, attr_name, dest, y); } int RGWSI_SysObj_Cache::set_attrs(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, map<string, bufferlist>& attrs, map<string, bufferlist> *rmattrs, RGWObjVersionTracker *objv_tracker, bool exclusive, optional_yield y) { rgw_pool pool; string oid; normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); ObjectCacheInfo info; info.xattrs = attrs; if (rmattrs) { info.rm_xattrs = *rmattrs; } info.status = 0; info.flags = CACHE_FLAG_MODIFY_XATTRS; int ret = RGWSI_SysObj_Core::set_attrs(dpp, obj, attrs, rmattrs, objv_tracker, exclusive, y); string name = normal_name(pool, oid); if (ret >= 0) { if (objv_tracker && objv_tracker->read_version.ver) { info.version = objv_tracker->read_version; info.flags |= CACHE_FLAG_OBJV; } cache.put(dpp, name, info, NULL); int r = distribute_cache(dpp, name, obj, info, UPDATE_OBJ, y); if (r < 0) ldpp_dout(dpp, 0) << "ERROR: failed to distribute cache for " << obj << dendl; } else { cache.invalidate_remove(dpp, name); } return ret; } int RGWSI_SysObj_Cache::write(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, real_time *pmtime, map<std::string, bufferlist>& attrs, bool exclusive, const bufferlist& data, RGWObjVersionTracker *objv_tracker, real_time set_mtime, optional_yield y) { rgw_pool pool; string oid; normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); ObjectCacheInfo info; info.xattrs = attrs; info.status = 0; info.data = data; info.flags = CACHE_FLAG_XATTRS | CACHE_FLAG_DATA | CACHE_FLAG_META; ceph::real_time result_mtime; int ret = RGWSI_SysObj_Core::write(dpp, obj, &result_mtime, attrs, exclusive, data, objv_tracker, set_mtime, y); if (pmtime) { *pmtime = result_mtime; } if (objv_tracker && objv_tracker->read_version.ver) { info.version = objv_tracker->read_version; info.flags |= CACHE_FLAG_OBJV; } info.meta.mtime = result_mtime; info.meta.size = data.length(); string name = normal_name(pool, oid); if (ret >= 0) { cache.put(dpp, name, info, NULL); int r = distribute_cache(dpp, name, obj, info, UPDATE_OBJ, y); if (r < 0) ldpp_dout(dpp, 0) << "ERROR: failed to distribute cache for " << obj << dendl; } else { cache.invalidate_remove(dpp, name); } return ret; } int RGWSI_SysObj_Cache::write_data(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const bufferlist& data, bool exclusive, RGWObjVersionTracker *objv_tracker, optional_yield y) { rgw_pool pool; string oid; normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); ObjectCacheInfo info; info.data = data; info.meta.size = data.length(); info.status = 0; info.flags = CACHE_FLAG_DATA; int ret = RGWSI_SysObj_Core::write_data(dpp, obj, data, exclusive, objv_tracker, y); string name = normal_name(pool, oid); if (ret >= 0) { if (objv_tracker && objv_tracker->read_version.ver) { info.version = objv_tracker->read_version; info.flags |= CACHE_FLAG_OBJV; } cache.put(dpp, name, info, NULL); int r = distribute_cache(dpp, name, obj, info, UPDATE_OBJ, y); if (r < 0) ldpp_dout(dpp, 0) << "ERROR: failed to distribute cache for " << obj << dendl; } else { cache.invalidate_remove(dpp, name); } return ret; } int RGWSI_SysObj_Cache::raw_stat(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, uint64_t *psize, real_time *pmtime, map<string, bufferlist> *attrs, RGWObjVersionTracker *objv_tracker, optional_yield y) { rgw_pool pool; string oid; normalize_pool_and_obj(obj.pool, obj.oid, pool, oid); string name = normal_name(pool, oid); uint64_t size; real_time mtime; ObjectCacheInfo info; uint32_t flags = CACHE_FLAG_META | CACHE_FLAG_XATTRS; if (objv_tracker) flags |= CACHE_FLAG_OBJV; int r = cache.get(dpp, name, info, flags, NULL); if (r == 0) { if (info.status < 0) return info.status; size = info.meta.size; mtime = info.meta.mtime; if (objv_tracker) objv_tracker->read_version = info.version; goto done; } if (r == -ENODATA) { return -ENOENT; } r = RGWSI_SysObj_Core::raw_stat(dpp, obj, &size, &mtime, &info.xattrs, objv_tracker, y); if (r < 0) { if (r == -ENOENT) { info.status = r; cache.put(dpp, name, info, NULL); } return r; } info.status = 0; info.meta.mtime = mtime; info.meta.size = size; info.flags = CACHE_FLAG_META | CACHE_FLAG_XATTRS; if (objv_tracker) { info.flags |= CACHE_FLAG_OBJV; info.version = objv_tracker->read_version; } cache.put(dpp, name, info, NULL); done: if (psize) *psize = size; if (pmtime) *pmtime = mtime; if (attrs) *attrs = info.xattrs; return 0; } int RGWSI_SysObj_Cache::distribute_cache(const DoutPrefixProvider *dpp, const string& normal_name, const rgw_raw_obj& obj, ObjectCacheInfo& obj_info, int op, optional_yield y) { RGWCacheNotifyInfo info; info.op = op; info.obj_info = obj_info; info.obj = obj; return notify_svc->distribute(dpp, normal_name, info, y); } int RGWSI_SysObj_Cache::watch_cb(const DoutPrefixProvider *dpp, uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) { RGWCacheNotifyInfo info; try { auto iter = bl.cbegin(); decode(info, iter); } catch (buffer::end_of_buffer& err) { ldpp_dout(dpp, 0) << "ERROR: got bad notification" << dendl; return -EIO; } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: buffer::error" << dendl; return -EIO; } rgw_pool pool; string oid; normalize_pool_and_obj(info.obj.pool, info.obj.oid, pool, oid); string name = normal_name(pool, oid); switch (info.op) { case UPDATE_OBJ: cache.put(dpp, name, info.obj_info, NULL); break; case INVALIDATE_OBJ: cache.invalidate_remove(dpp, name); break; default: ldpp_dout(dpp, 0) << "WARNING: got unknown notification op: " << info.op << dendl; return -EINVAL; } return 0; } void RGWSI_SysObj_Cache::set_enabled(bool status) { cache.set_enabled(status); } bool RGWSI_SysObj_Cache::chain_cache_entry(const DoutPrefixProvider *dpp, std::initializer_list<rgw_cache_entry_info *> cache_info_entries, RGWChainedCache::Entry *chained_entry) { return cache.chain_cache_entry(dpp, cache_info_entries, chained_entry); } void RGWSI_SysObj_Cache::register_chained_cache(RGWChainedCache *cc) { cache.chain_cache(cc); } void RGWSI_SysObj_Cache::unregister_chained_cache(RGWChainedCache *cc) { cache.unchain_cache(cc); } static void cache_list_dump_helper(Formatter* f, const std::string& name, const ceph::real_time mtime, const std::uint64_t size) { f->dump_string("name", name); f->dump_string("mtime", ceph::to_iso_8601(mtime)); f->dump_unsigned("size", size); } class RGWSI_SysObj_Cache_ASocketHook : public AdminSocketHook { RGWSI_SysObj_Cache *svc; static constexpr std::string_view admin_commands[][2] = { { "cache list name=filter,type=CephString,req=false", "cache list [filter_str]: list object cache, possibly matching substrings" }, { "cache inspect name=target,type=CephString,req=true", "cache inspect target: print cache element" }, { "cache erase name=target,type=CephString,req=true", "cache erase target: erase element from cache" }, { "cache zap", "cache zap: erase all elements from cache" } }; public: RGWSI_SysObj_Cache_ASocketHook(RGWSI_SysObj_Cache *_svc) : svc(_svc) {} int start(); void shutdown(); int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& out) override; }; int RGWSI_SysObj_Cache_ASocketHook::start() { auto admin_socket = svc->ctx()->get_admin_socket(); for (auto cmd : admin_commands) { int r = admin_socket->register_command(cmd[0], this, cmd[1]); if (r < 0) { ldout(svc->ctx(), 0) << "ERROR: fail to register admin socket command (r=" << r << ")" << dendl; return r; } } return 0; } void RGWSI_SysObj_Cache_ASocketHook::shutdown() { auto admin_socket = svc->ctx()->get_admin_socket(); admin_socket->unregister_commands(this); } int RGWSI_SysObj_Cache_ASocketHook::call( std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& out) { if (command == "cache list"sv) { std::optional<std::string> filter; if (auto i = cmdmap.find("filter"); i != cmdmap.cend()) { filter = boost::get<std::string>(i->second); } f->open_array_section("cache_entries"); svc->asocket.call_list(filter, f); f->close_section(); return 0; } else if (command == "cache inspect"sv) { const auto& target = boost::get<std::string>(cmdmap.at("target")); if (svc->asocket.call_inspect(target, f)) { return 0; } else { ss << "Unable to find entry "s + target + ".\n"; return -ENOENT; } } else if (command == "cache erase"sv) { const auto& target = boost::get<std::string>(cmdmap.at("target")); if (svc->asocket.call_erase(target)) { return 0; } else { ss << "Unable to find entry "s + target + ".\n"; return -ENOENT; } } else if (command == "cache zap"sv) { svc->asocket.call_zap(); return 0; } return -ENOSYS; } RGWSI_SysObj_Cache::ASocketHandler::ASocketHandler(const DoutPrefixProvider *_dpp, RGWSI_SysObj_Cache *_svc) : dpp(_dpp), svc(_svc) { hook.reset(new RGWSI_SysObj_Cache_ASocketHook(_svc)); } RGWSI_SysObj_Cache::ASocketHandler::~ASocketHandler() { } int RGWSI_SysObj_Cache::ASocketHandler::start() { return hook->start(); } void RGWSI_SysObj_Cache::ASocketHandler::shutdown() { return hook->shutdown(); } void RGWSI_SysObj_Cache::ASocketHandler::call_list(const std::optional<std::string>& filter, Formatter* f) { svc->cache.for_each( [&filter, f] (const string& name, const ObjectCacheEntry& entry) { if (!filter || name.find(*filter) != name.npos) { cache_list_dump_helper(f, name, entry.info.meta.mtime, entry.info.meta.size); } }); } int RGWSI_SysObj_Cache::ASocketHandler::call_inspect(const std::string& target, Formatter* f) { if (const auto entry = svc->cache.get(dpp, target)) { f->open_object_section("cache_entry"); f->dump_string("name", target.c_str()); entry->dump(f); f->close_section(); return true; } else { return false; } } int RGWSI_SysObj_Cache::ASocketHandler::call_erase(const std::string& target) { return svc->cache.invalidate_remove(dpp, target); } int RGWSI_SysObj_Cache::ASocketHandler::call_zap() { svc->cache.invalidate_all(); return 0; }
19,023
27.351714
133
cc
null
ceph-main/src/rgw/services/svc_sys_obj_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 "common/RWLock.h" #include "rgw_service.h" #include "rgw_cache.h" #include "svc_sys_obj_core.h" class RGWSI_Notify; class RGWSI_SysObj_Cache_CB; class RGWSI_SysObj_Cache_ASocketHook; class RGWSI_SysObj_Cache : public RGWSI_SysObj_Core { friend class RGWSI_SysObj_Cache_CB; friend class RGWServices_Def; friend class ASocketHandler; RGWSI_Notify *notify_svc{nullptr}; ObjectCache cache; std::shared_ptr<RGWSI_SysObj_Cache_CB> cb; void normalize_pool_and_obj(const rgw_pool& src_pool, const std::string& src_obj, rgw_pool& dst_pool, std::string& dst_obj); protected: void init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc, RGWSI_Notify *_notify_svc) { core_init(_rados_svc, _zone_svc); notify_svc = _notify_svc; } int do_start(optional_yield, const DoutPrefixProvider *dpp) override; void shutdown() override; int raw_stat(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, uint64_t *psize, real_time *pmtime, std::map<std::string, bufferlist> *attrs, RGWObjVersionTracker *objv_tracker, optional_yield y) override; int read(const DoutPrefixProvider *dpp, RGWSI_SysObj_Obj_GetObjState& read_state, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, bufferlist *bl, off_t ofs, off_t end, ceph::real_time* pmtime, uint64_t* psize, std::map<std::string, bufferlist> *attrs, bool raw_attrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version>, optional_yield y) override; int get_attr(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const char *name, bufferlist *dest, optional_yield y) override; int set_attrs(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, std::map<std::string, bufferlist>& attrs, std::map<std::string, bufferlist> *rmattrs, RGWObjVersionTracker *objv_tracker, bool exclusive, optional_yield y) override; int remove(const DoutPrefixProvider *dpp, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, optional_yield y) override; int write(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, real_time *pmtime, std::map<std::string, bufferlist>& attrs, bool exclusive, const bufferlist& data, RGWObjVersionTracker *objv_tracker, real_time set_mtime, optional_yield y) override; int write_data(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const bufferlist& bl, bool exclusive, RGWObjVersionTracker *objv_tracker, optional_yield y); int distribute_cache(const DoutPrefixProvider *dpp, const std::string& normal_name, const rgw_raw_obj& obj, ObjectCacheInfo& obj_info, int op, optional_yield y); int watch_cb(const DoutPrefixProvider *dpp, uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl); void set_enabled(bool status); public: RGWSI_SysObj_Cache(const DoutPrefixProvider *dpp, CephContext *cct) : RGWSI_SysObj_Core(cct), asocket(dpp, this) { cache.set_ctx(cct); } bool chain_cache_entry(const DoutPrefixProvider *dpp, std::initializer_list<rgw_cache_entry_info *> cache_info_entries, RGWChainedCache::Entry *chained_entry); void register_chained_cache(RGWChainedCache *cc); void unregister_chained_cache(RGWChainedCache *cc); class ASocketHandler { const DoutPrefixProvider *dpp; RGWSI_SysObj_Cache *svc; std::unique_ptr<RGWSI_SysObj_Cache_ASocketHook> hook; public: ASocketHandler(const DoutPrefixProvider *dpp, RGWSI_SysObj_Cache *_svc); ~ASocketHandler(); int start(); void shutdown(); // `call_list` must iterate over all cache entries and call // `cache_list_dump_helper` with the supplied Formatter on any that // include `filter` as a substd::string. // void call_list(const std::optional<std::string>& filter, Formatter* f); // `call_inspect` must look up the requested target and, if found, // dump it to the supplied Formatter and return true. If not found, // it must return false. // int call_inspect(const std::string& target, Formatter* f); // `call_erase` must erase the requested target and return true. If // the requested target does not exist, it should return false. int call_erase(const std::string& target); // `call_zap` must erase the cache. int call_zap(); } asocket; }; template <class T> class RGWChainedCacheImpl : public RGWChainedCache { RGWSI_SysObj_Cache *svc{nullptr}; ceph::timespan expiry; RWLock lock; std::unordered_map<std::string, std::pair<T, ceph::coarse_mono_time>> entries; public: RGWChainedCacheImpl() : lock("RGWChainedCacheImpl::lock") {} ~RGWChainedCacheImpl() { if (!svc) { return; } svc->unregister_chained_cache(this); } void unregistered() override { svc = nullptr; } void init(RGWSI_SysObj_Cache *_svc) { if (!_svc) { return; } svc = _svc; svc->register_chained_cache(this); expiry = std::chrono::seconds(svc->ctx()->_conf.get_val<uint64_t>( "rgw_cache_expiry_interval")); } boost::optional<T> find(const std::string& key) { std::shared_lock rl{lock}; auto iter = entries.find(key); if (iter == entries.end()) { return boost::none; } if (expiry.count() && (ceph::coarse_mono_clock::now() - iter->second.second) > expiry) { return boost::none; } return iter->second.first; } bool put(const DoutPrefixProvider *dpp, RGWSI_SysObj_Cache *svc, const std::string& key, T *entry, std::initializer_list<rgw_cache_entry_info *> cache_info_entries) { if (!svc) { return false; } Entry chain_entry(this, key, entry); /* we need the svc cache to call us under its lock to maintain lock ordering */ return svc->chain_cache_entry(dpp, cache_info_entries, &chain_entry); } void chain_cb(const std::string& key, void *data) override { T *entry = static_cast<T *>(data); std::unique_lock wl{lock}; entries[key].first = *entry; if (expiry.count() > 0) { entries[key].second = ceph::coarse_mono_clock::now(); } } void invalidate(const std::string& key) override { std::unique_lock wl{lock}; entries.erase(key); } void invalidate_all() override { std::unique_lock wl{lock}; entries.clear(); } }; /* RGWChainedCacheImpl */
6,954
30.188341
126
h
null
ceph-main/src/rgw/services/svc_sys_obj_core.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_sys_obj_core.h" #include "svc_rados.h" #include "svc_zone.h" #include "rgw_tools.h" #define dout_subsys ceph_subsys_rgw using namespace std; int RGWSI_SysObj_Core_GetObjState::get_rados_obj(const DoutPrefixProvider *dpp, RGWSI_RADOS *rados_svc, RGWSI_Zone *zone_svc, const rgw_raw_obj& obj, RGWSI_RADOS::Obj **pobj) { if (!has_rados_obj) { if (obj.oid.empty()) { ldpp_dout(dpp, 0) << "ERROR: obj.oid is empty" << dendl; return -EINVAL; } rados_obj = rados_svc->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } has_rados_obj = true; } *pobj = &rados_obj; return 0; } int RGWSI_SysObj_Core::get_rados_obj(const DoutPrefixProvider *dpp, RGWSI_Zone *zone_svc, const rgw_raw_obj& obj, RGWSI_RADOS::Obj *pobj) { if (obj.oid.empty()) { ldpp_dout(dpp, 0) << "ERROR: obj.oid is empty" << dendl; return -EINVAL; } *pobj = rados_svc->obj(obj); int r = pobj->open(dpp); if (r < 0) { return r; } return 0; } int RGWSI_SysObj_Core::raw_stat(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, uint64_t *psize, real_time *pmtime, map<string, bufferlist> *attrs, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { return r; } uint64_t size = 0; struct timespec mtime_ts; librados::ObjectReadOperation op; if (objv_tracker) { objv_tracker->prepare_op_for_read(&op); } op.getxattrs(attrs, nullptr); if (psize || pmtime) { op.stat2(&size, &mtime_ts, nullptr); } bufferlist outbl; r = rados_obj.operate(dpp, &op, &outbl, y); if (r < 0) return r; if (psize) *psize = size; if (pmtime) *pmtime = ceph::real_clock::from_timespec(mtime_ts); return 0; } int RGWSI_SysObj_Core::stat(RGWSI_SysObj_Obj_GetObjState& _state, const rgw_raw_obj& obj, map<string, bufferlist> *attrs, bool raw_attrs, real_time *lastmod, uint64_t *obj_size, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { uint64_t size = 0; ceph::real_time mtime; std::map<std::string, bufferlist> attrset; int r = raw_stat(dpp, obj, &size, &mtime, &attrset, objv_tracker, y); if (r < 0) return r; if (attrs) { if (raw_attrs) { *attrs = std::move(attrset); } else { rgw_filter_attrset(attrset, RGW_ATTR_PREFIX, attrs); } if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) { map<string, bufferlist>::iterator iter; for (iter = attrs->begin(); iter != attrs->end(); ++iter) { ldpp_dout(dpp, 20) << "Read xattr: " << iter->first << dendl; } } } if (obj_size) *obj_size = size; if (lastmod) *lastmod = mtime; return 0; } int RGWSI_SysObj_Core::read(const DoutPrefixProvider *dpp, RGWSI_SysObj_Obj_GetObjState& _read_state, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, bufferlist *bl, off_t ofs, off_t end, ceph::real_time* pmtime, uint64_t* psize, map<string, bufferlist> *attrs, bool raw_attrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version>, optional_yield y) { auto& read_state = static_cast<GetObjState&>(_read_state); uint64_t len; struct timespec mtime_ts; librados::ObjectReadOperation op; if (end < 0) len = 0; else len = end - ofs + 1; if (objv_tracker) { objv_tracker->prepare_op_for_read(&op); } if (psize || pmtime) { op.stat2(psize, &mtime_ts, nullptr); } ldpp_dout(dpp, 20) << "rados->read ofs=" << ofs << " len=" << len << dendl; op.read(ofs, len, bl, nullptr); map<string, bufferlist> unfiltered_attrset; if (attrs) { if (raw_attrs) { op.getxattrs(attrs, nullptr); } else { op.getxattrs(&unfiltered_attrset, nullptr); } } RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } r = rados_obj.operate(dpp, &op, nullptr, y); if (r < 0) { ldpp_dout(dpp, 20) << "rados_obj.operate() r=" << r << " bl.length=" << bl->length() << dendl; return r; } ldpp_dout(dpp, 20) << "rados_obj.operate() r=" << r << " bl.length=" << bl->length() << dendl; uint64_t op_ver = rados_obj.get_last_version(); if (read_state.last_ver > 0 && read_state.last_ver != op_ver) { ldpp_dout(dpp, 5) << "raced with an object write, abort" << dendl; return -ECANCELED; } if (pmtime) { *pmtime = ceph::real_clock::from_timespec(mtime_ts); } if (attrs && !raw_attrs) { rgw_filter_attrset(unfiltered_attrset, RGW_ATTR_PREFIX, attrs); } read_state.last_ver = op_ver; return bl->length(); } /** * Get an attribute for a system object. * obj: the object to get attr * name: name of the attr to retrieve * dest: bufferlist to store the result in * Returns: 0 on success, -ERR# otherwise. */ int RGWSI_SysObj_Core::get_attr(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const char *name, bufferlist *dest, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } librados::ObjectReadOperation op; int rval; op.getxattr(name, dest, &rval); r = rados_obj.operate(dpp, &op, nullptr, y); if (r < 0) return r; return 0; } int RGWSI_SysObj_Core::set_attrs(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, map<string, bufferlist>& attrs, map<string, bufferlist> *rmattrs, RGWObjVersionTracker *objv_tracker, bool exclusive, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } librados::ObjectWriteOperation op; if (exclusive) { op.create(true); // exclusive create } if (objv_tracker) { objv_tracker->prepare_op_for_write(&op); } map<string, bufferlist>::iterator iter; if (rmattrs) { for (iter = rmattrs->begin(); iter != rmattrs->end(); ++iter) { const string& name = iter->first; op.rmxattr(name.c_str()); } } for (iter = attrs.begin(); iter != attrs.end(); ++iter) { const string& name = iter->first; bufferlist& bl = iter->second; if (!bl.length()) continue; op.setxattr(name.c_str(), bl); } if (!op.size()) return 0; bufferlist bl; r = rados_obj.operate(dpp, &op, y); if (r < 0) return r; if (objv_tracker) { objv_tracker->apply_write(); } return 0; } int RGWSI_SysObj_Core::omap_get_vals(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const string& marker, uint64_t count, std::map<string, bufferlist> *m, bool *pmore, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } string start_after = marker; bool more; do { librados::ObjectReadOperation op; std::map<string, bufferlist> t; int rval; op.omap_get_vals2(start_after, count, &t, &more, &rval); r = rados_obj.operate(dpp, &op, nullptr, y); if (r < 0) { return r; } if (t.empty()) { break; } count -= t.size(); start_after = t.rbegin()->first; m->insert(t.begin(), t.end()); } while (more && count > 0); if (pmore) { *pmore = more; } return 0; } int RGWSI_SysObj_Core::omap_get_all(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, std::map<string, bufferlist> *m, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } #define MAX_OMAP_GET_ENTRIES 1024 const int count = MAX_OMAP_GET_ENTRIES; string start_after; bool more; do { librados::ObjectReadOperation op; std::map<string, bufferlist> t; int rval; op.omap_get_vals2(start_after, count, &t, &more, &rval); r = rados_obj.operate(dpp, &op, nullptr, y); if (r < 0) { return r; } if (t.empty()) { break; } start_after = t.rbegin()->first; m->insert(t.begin(), t.end()); } while (more); return 0; } int RGWSI_SysObj_Core::omap_set(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::string& key, bufferlist& bl, bool must_exist, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } ldpp_dout(dpp, 15) << "omap_set obj=" << obj << " key=" << key << dendl; map<string, bufferlist> m; m[key] = bl; librados::ObjectWriteOperation op; if (must_exist) op.assert_exists(); op.omap_set(m); r = rados_obj.operate(dpp, &op, y); return r; } int RGWSI_SysObj_Core::omap_set(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::map<std::string, bufferlist>& m, bool must_exist, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } librados::ObjectWriteOperation op; if (must_exist) op.assert_exists(); op.omap_set(m); r = rados_obj.operate(dpp, &op, y); return r; } int RGWSI_SysObj_Core::omap_del(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::string& key, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } set<string> k; k.insert(key); librados::ObjectWriteOperation op; op.omap_rm_keys(k); r = rados_obj.operate(dpp, &op, y); return r; } int RGWSI_SysObj_Core::notify(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, bufferlist& bl, uint64_t timeout_ms, bufferlist *pbl, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } r = rados_obj.notify(dpp, bl, timeout_ms, pbl, y); return r; } int RGWSI_SysObj_Core::remove(const DoutPrefixProvider *dpp, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } librados::ObjectWriteOperation op; if (objv_tracker) { objv_tracker->prepare_op_for_write(&op); } op.remove(); r = rados_obj.operate(dpp, &op, y); if (r < 0) return r; return 0; } int RGWSI_SysObj_Core::write(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, real_time *pmtime, map<std::string, bufferlist>& attrs, bool exclusive, const bufferlist& data, RGWObjVersionTracker *objv_tracker, real_time set_mtime, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } librados::ObjectWriteOperation op; if (exclusive) { op.create(true); // exclusive create } else { op.remove(); op.set_op_flags2(LIBRADOS_OP_FLAG_FAILOK); op.create(false); } if (objv_tracker) { objv_tracker->prepare_op_for_write(&op); } if (real_clock::is_zero(set_mtime)) { set_mtime = real_clock::now(); } struct timespec mtime_ts = real_clock::to_timespec(set_mtime); op.mtime2(&mtime_ts); op.write_full(data); bufferlist acl_bl; for (map<string, bufferlist>::iterator iter = attrs.begin(); iter != attrs.end(); ++iter) { const string& name = iter->first; bufferlist& bl = iter->second; if (!bl.length()) continue; op.setxattr(name.c_str(), bl); } r = rados_obj.operate(dpp, &op, y); if (r < 0) { return r; } if (objv_tracker) { objv_tracker->apply_write(); } if (pmtime) { *pmtime = set_mtime; } return 0; } int RGWSI_SysObj_Core::write_data(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const bufferlist& bl, bool exclusive, RGWObjVersionTracker *objv_tracker, optional_yield y) { RGWSI_RADOS::Obj rados_obj; int r = get_rados_obj(dpp, zone_svc, obj, &rados_obj); if (r < 0) { ldpp_dout(dpp, 20) << "get_rados_obj() on obj=" << obj << " returned " << r << dendl; return r; } librados::ObjectWriteOperation op; if (exclusive) { op.create(true); } if (objv_tracker) { objv_tracker->prepare_op_for_write(&op); } op.write_full(bl); r = rados_obj.operate(dpp, &op, y); if (r < 0) return r; if (objv_tracker) { objv_tracker->apply_write(); } return 0; } int RGWSI_SysObj_Core::pool_list_prefixed_objs(const DoutPrefixProvider *dpp, const rgw_pool& pool, const string& prefix, std::function<void(const string&)> cb) { bool is_truncated; auto rados_pool = rados_svc->pool(pool); auto op = rados_pool.op(); RGWAccessListFilterPrefix filter(prefix); int r = op.init(dpp, string(), &filter); if (r < 0) { return r; } do { vector<string> oids; #define MAX_OBJS_DEFAULT 1000 int r = op.get_next(dpp, MAX_OBJS_DEFAULT, &oids, &is_truncated); if (r < 0) { return r; } for (auto& val : oids) { if (val.size() > prefix.size()) { cb(val.substr(prefix.size())); } } } while (is_truncated); return 0; } int RGWSI_SysObj_Core::pool_list_objects_init(const DoutPrefixProvider *dpp, const rgw_pool& pool, const string& marker, const string& prefix, RGWSI_SysObj::Pool::ListCtx *_ctx) { _ctx->impl.emplace<PoolListImplInfo>(prefix); auto& ctx = static_cast<PoolListImplInfo&>(*_ctx->impl); ctx.pool = rados_svc->pool(pool); ctx.op = ctx.pool.op(); int r = ctx.op.init(dpp, marker, &ctx.filter); if (r < 0) { ldpp_dout(dpp, 10) << "failed to list objects pool_iterate_begin() returned r=" << r << dendl; return r; } return 0; } int RGWSI_SysObj_Core::pool_list_objects_next(const DoutPrefixProvider *dpp, RGWSI_SysObj::Pool::ListCtx& _ctx, int max, vector<string> *oids, bool *is_truncated) { if (!_ctx.impl) { return -EINVAL; } auto& ctx = static_cast<PoolListImplInfo&>(*_ctx.impl); int r = ctx.op.get_next(dpp, max, oids, is_truncated); if (r < 0) { if(r != -ENOENT) ldpp_dout(dpp, 10) << "failed to list objects pool_iterate returned r=" << r << dendl; return r; } return oids->size(); } int RGWSI_SysObj_Core::pool_list_objects_get_marker(RGWSI_SysObj::Pool::ListCtx& _ctx, string *marker) { if (!_ctx.impl) { return -EINVAL; } auto& ctx = static_cast<PoolListImplInfo&>(*_ctx.impl); return ctx.op.get_marker(marker); }
18,124
26.173913
110
cc
null
ceph-main/src/rgw/services/svc_sys_obj_core.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_service.h" #include "svc_rados.h" #include "svc_sys_obj.h" #include "svc_sys_obj_core_types.h" class RGWSI_Zone; struct rgw_cache_entry_info; class RGWSI_SysObj_Core : public RGWServiceInstance { friend class RGWServices_Def; friend class RGWSI_SysObj; protected: RGWSI_RADOS *rados_svc{nullptr}; RGWSI_Zone *zone_svc{nullptr}; using GetObjState = RGWSI_SysObj_Core_GetObjState; using PoolListImplInfo = RGWSI_SysObj_Core_PoolListImplInfo; void core_init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc) { rados_svc = _rados_svc; zone_svc = _zone_svc; } int get_rados_obj(const DoutPrefixProvider *dpp, RGWSI_Zone *zone_svc, const rgw_raw_obj& obj, RGWSI_RADOS::Obj *pobj); virtual int raw_stat(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, uint64_t *psize, real_time *pmtime, std::map<std::string, bufferlist> *attrs, RGWObjVersionTracker *objv_tracker, optional_yield y); virtual int read(const DoutPrefixProvider *dpp, RGWSI_SysObj_Obj_GetObjState& read_state, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, bufferlist *bl, off_t ofs, off_t end, ceph::real_time* pmtime, uint64_t* psize, std::map<std::string, bufferlist> *attrs, bool raw_attrs, rgw_cache_entry_info *cache_info, boost::optional<obj_version>, optional_yield y); virtual int remove(const DoutPrefixProvider *dpp, RGWObjVersionTracker *objv_tracker, const rgw_raw_obj& obj, optional_yield y); virtual int write(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, real_time *pmtime, std::map<std::string, bufferlist>& attrs, bool exclusive, const bufferlist& data, RGWObjVersionTracker *objv_tracker, real_time set_mtime, optional_yield y); virtual int write_data(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const bufferlist& bl, bool exclusive, RGWObjVersionTracker *objv_tracker, optional_yield y); virtual int get_attr(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const char *name, bufferlist *dest, optional_yield y); virtual int set_attrs(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, std::map<std::string, bufferlist>& attrs, std::map<std::string, bufferlist> *rmattrs, RGWObjVersionTracker *objv_tracker, bool exclusive, optional_yield y); virtual int omap_get_all(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, std::map<std::string, bufferlist> *m, optional_yield y); virtual int omap_get_vals(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::string& marker, uint64_t count, std::map<std::string, bufferlist> *m, bool *pmore, optional_yield y); virtual int omap_set(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::string& key, bufferlist& bl, bool must_exist, optional_yield y); virtual int omap_set(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::map<std::string, bufferlist>& m, bool must_exist, optional_yield y); virtual int omap_del(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, const std::string& key, optional_yield y); virtual int notify(const DoutPrefixProvider *dpp, const rgw_raw_obj& obj, bufferlist& bl, uint64_t timeout_ms, bufferlist *pbl, optional_yield y); virtual int pool_list_prefixed_objs(const DoutPrefixProvider *dpp, const rgw_pool& pool, const std::string& prefix, std::function<void(const std::string&)> cb); virtual int pool_list_objects_init(const DoutPrefixProvider *dpp, const rgw_pool& pool, const std::string& marker, const std::string& prefix, RGWSI_SysObj::Pool::ListCtx *ctx); virtual int pool_list_objects_next(const DoutPrefixProvider *dpp, RGWSI_SysObj::Pool::ListCtx& ctx, int max, std::vector<std::string> *oids, bool *is_truncated); virtual int pool_list_objects_get_marker(RGWSI_SysObj::Pool::ListCtx& _ctx, std::string *marker); int stat(RGWSI_SysObj_Obj_GetObjState& state, const rgw_raw_obj& obj, std::map<std::string, bufferlist> *attrs, bool raw_attrs, real_time *lastmod, uint64_t *obj_size, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); public: RGWSI_SysObj_Core(CephContext *cct): RGWServiceInstance(cct) {} RGWSI_Zone *get_zone_svc() { return zone_svc; } };
5,988
40.020548
121
h
null
ceph-main/src/rgw/services/svc_sys_obj_core_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_service.h" #include "svc_rados.h" #include "svc_sys_obj_types.h" struct RGWSI_SysObj_Core_GetObjState : public RGWSI_SysObj_Obj_GetObjState { RGWSI_RADOS::Obj rados_obj; bool has_rados_obj{false}; uint64_t last_ver{0}; RGWSI_SysObj_Core_GetObjState() {} int get_rados_obj(const DoutPrefixProvider *dpp, RGWSI_RADOS *rados_svc, RGWSI_Zone *zone_svc, const rgw_raw_obj& obj, RGWSI_RADOS::Obj **pobj); }; struct RGWSI_SysObj_Core_PoolListImplInfo : public RGWSI_SysObj_Pool_ListInfo { RGWSI_RADOS::Pool pool; RGWSI_RADOS::Pool::List op; RGWAccessListFilterPrefix filter; RGWSI_SysObj_Core_PoolListImplInfo(const std::string& prefix) : op(pool.op()), filter(prefix) {} };
909
25
98
h
null
ceph-main/src/rgw/services/svc_sys_obj_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_service.h" struct RGWSI_SysObj_Obj_GetObjState { }; struct RGWSI_SysObj_Pool_ListInfo { };
230
13.4375
70
h
null
ceph-main/src/rgw/services/svc_tier_rados.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_tier_rados.h" using namespace std; const std::string MP_META_SUFFIX = ".meta"; MultipartMetaFilter::~MultipartMetaFilter() {} bool MultipartMetaFilter::filter(const string& name, string& key) { // the length of the suffix so we can skip past it static const size_t MP_META_SUFFIX_LEN = MP_META_SUFFIX.length(); size_t len = name.size(); // make sure there's room for suffix plus at least one more // character if (len <= MP_META_SUFFIX_LEN) return false; size_t pos = name.find(MP_META_SUFFIX, len - MP_META_SUFFIX_LEN); if (pos == string::npos) return false; pos = name.rfind('.', pos - 1); if (pos == string::npos) return false; key = name.substr(0, pos); return true; }
841
21.756757
70
cc
null
ceph-main/src/rgw/services/svc_tier_rados.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 <iomanip> #include "rgw_service.h" #include "svc_rados.h" extern const std::string MP_META_SUFFIX; class RGWMPObj { std::string oid; std::string prefix; std::string meta; std::string upload_id; public: RGWMPObj() {} RGWMPObj(const std::string& _oid, const std::string& _upload_id) { init(_oid, _upload_id, _upload_id); } RGWMPObj(const std::string& _oid, std::optional<std::string> _upload_id) { if (_upload_id) { init(_oid, *_upload_id, *_upload_id); } else { from_meta(_oid); } } void init(const std::string& _oid, const std::string& _upload_id) { init(_oid, _upload_id, _upload_id); } void init(const std::string& _oid, const std::string& _upload_id, const std::string& part_unique_str) { if (_oid.empty()) { clear(); return; } oid = _oid; upload_id = _upload_id; prefix = oid + "."; meta = prefix + upload_id + MP_META_SUFFIX; prefix.append(part_unique_str); } const std::string& get_meta() const { return meta; } std::string get_part(int num) const { char buf[16]; snprintf(buf, 16, ".%d", num); std::string s = prefix; s.append(buf); return s; } std::string get_part(const std::string& part) const { std::string s = prefix; s.append("."); s.append(part); return s; } const std::string& get_upload_id() const { return upload_id; } const std::string& get_key() const { return oid; } bool from_meta(const std::string& meta) { int end_pos = meta.rfind('.'); // search for ".meta" if (end_pos < 0) return false; int mid_pos = meta.rfind('.', end_pos - 1); // <key>.<upload_id> if (mid_pos < 0) return false; oid = meta.substr(0, mid_pos); upload_id = meta.substr(mid_pos + 1, end_pos - mid_pos - 1); init(oid, upload_id, upload_id); return true; } void clear() { oid = ""; prefix = ""; meta = ""; upload_id = ""; } friend std::ostream& operator<<(std::ostream& out, const RGWMPObj& obj) { return out << "RGWMPObj:{ prefix=" << std::quoted(obj.prefix) << ", meta=" << std::quoted(obj.meta) << " }"; } }; // class RGWMPObj /** * A filter to a) test whether an object name is a multipart meta * object, and b) filter out just the key used to determine the bucket * index shard. * * Objects for multipart meta have names adorned with an upload id and * other elements -- specifically a ".", MULTIPART_UPLOAD_ID_PREFIX, * unique id, and MP_META_SUFFIX. This filter will return true when * the name provided is such. It will also extract the key used for * bucket index shard calculation from the adorned name. */ class MultipartMetaFilter : public RGWAccessListFilter { public: MultipartMetaFilter() {} virtual ~MultipartMetaFilter() override; /** * @param name [in] The object name as it appears in the bucket index. * @param key [out] An output parameter that will contain the bucket * index key if this entry is in the form of a multipart meta object. * @return true if the name provided is in the form of a multipart meta * object, false otherwise */ bool filter(const std::string& name, std::string& key) override; }; class RGWSI_Tier_RADOS : public RGWServiceInstance { RGWSI_Zone *zone_svc{nullptr}; public: RGWSI_Tier_RADOS(CephContext *cct): RGWServiceInstance(cct) {} void init(RGWSI_Zone *_zone_svc) { zone_svc = _zone_svc; } static inline bool raw_obj_to_obj(const rgw_bucket& bucket, const rgw_raw_obj& raw_obj, rgw_obj *obj) { ssize_t pos = raw_obj.oid.find('_', bucket.marker.length()); if (pos < 0) { return false; } if (!rgw_obj_key::parse_raw_oid(raw_obj.oid.substr(pos + 1), &obj->key)) { return false; } obj->bucket = bucket; return true; } };
4,259
26.483871
105
h
null
ceph-main/src/rgw/services/svc_user.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_user.h" RGWSI_User::RGWSI_User(CephContext *cct): RGWServiceInstance(cct) { } RGWSI_User::~RGWSI_User() { }
231
18.333333
70
cc
null
ceph-main/src/rgw/services/svc_user.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 "svc_meta_be.h" #include "rgw_service.h" class RGWUserBuckets; class RGWGetUserStats_CB; class RGWSI_User : public RGWServiceInstance { public: RGWSI_User(CephContext *cct); virtual ~RGWSI_User(); static std::string get_meta_key(const rgw_user& user) { return user.to_str(); } static rgw_user user_from_meta_key(const std::string& key) { return rgw_user(key); } virtual RGWSI_MetaBackend_Handler *get_be_handler() = 0; /* base svc_user interfaces */ virtual int read_user_info(RGWSI_MetaBackend::Context *ctx, const rgw_user& user, RGWUserInfo *info, RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, rgw_cache_entry_info * const cache_info, std::map<std::string, bufferlist> * const pattrs, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int store_user_info(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& info, RGWUserInfo *old_info, RGWObjVersionTracker *objv_tracker, const real_time& mtime, bool exclusive, std::map<std::string, bufferlist> *attrs, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int remove_user_info(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int get_user_info_by_email(RGWSI_MetaBackend::Context *ctx, const std::string& email, RGWUserInfo *info, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int get_user_info_by_swift(RGWSI_MetaBackend::Context *ctx, const std::string& swift_name, RGWUserInfo *info, /* out */ RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int get_user_info_by_access_key(RGWSI_MetaBackend::Context *ctx, const std::string& access_key, RGWUserInfo *info, RGWObjVersionTracker* objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int add_bucket(const DoutPrefixProvider *dpp, const rgw_user& user, const rgw_bucket& bucket, ceph::real_time creation_time, optional_yield y) = 0; virtual int remove_bucket(const DoutPrefixProvider *dpp, const rgw_user& user, const rgw_bucket& _bucket, optional_yield) = 0; virtual int list_buckets(const DoutPrefixProvider *dpp, const rgw_user& user, const std::string& marker, const std::string& end_marker, uint64_t max, RGWUserBuckets *buckets, bool *is_truncated, optional_yield y) = 0; virtual int flush_bucket_stats(const DoutPrefixProvider *dpp, const rgw_user& user, const RGWBucketEnt& ent, optional_yield y) = 0; virtual int complete_flush_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) = 0; virtual int reset_bucket_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) = 0; virtual int read_stats(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const rgw_user& user, RGWStorageStats *stats, ceph::real_time *last_stats_sync, /* last time a full stats sync completed */ ceph::real_time *last_stats_update, optional_yield y) = 0; /* last time a stats update was done */ virtual int read_stats_async(const DoutPrefixProvider *dpp, const rgw_user& user, RGWGetUserStats_CB *cb) = 0; };
5,374
40.992188
89
h
null
ceph-main/src/rgw/services/svc_user_rados.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.hpp> #include "svc_user.h" #include "svc_user_rados.h" #include "svc_zone.h" #include "svc_sys_obj.h" #include "svc_sys_obj_cache.h" #include "svc_meta.h" #include "svc_meta_be_sobj.h" #include "svc_sync_modules.h" #include "rgw_user.h" #include "rgw_bucket.h" #include "rgw_tools.h" #include "rgw_zone.h" #include "rgw_rados.h" #include "cls/user/cls_user_client.h" #define dout_subsys ceph_subsys_rgw #define RGW_BUCKETS_OBJ_SUFFIX ".buckets" using namespace std; class RGWSI_User_Module : public RGWSI_MBSObj_Handler_Module { RGWSI_User_RADOS::Svc& svc; const string prefix; public: RGWSI_User_Module(RGWSI_User_RADOS::Svc& _svc) : RGWSI_MBSObj_Handler_Module("user"), svc(_svc) {} void get_pool_and_oid(const string& key, rgw_pool *pool, string *oid) override { if (pool) { *pool = svc.zone->get_zone_params().user_uid_pool; } if (oid) { *oid = key; } } const string& get_oid_prefix() override { return prefix; } bool is_valid_oid(const string& oid) override { // filter out the user.buckets objects return !boost::algorithm::ends_with(oid, RGW_BUCKETS_OBJ_SUFFIX); } string key_to_oid(const string& key) override { return key; } string oid_to_key(const string& oid) override { return oid; } }; RGWSI_User_RADOS::RGWSI_User_RADOS(CephContext *cct): RGWSI_User(cct) { } RGWSI_User_RADOS::~RGWSI_User_RADOS() { } void RGWSI_User_RADOS::init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_SysObj_Cache *_cache_svc, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc, RGWSI_SyncModules *_sync_modules_svc) { svc.user = this; svc.rados = _rados_svc; svc.zone = _zone_svc; svc.sysobj = _sysobj_svc; svc.cache = _cache_svc; svc.meta = _meta_svc; svc.meta_be = _meta_be_svc; svc.sync_modules = _sync_modules_svc; } int RGWSI_User_RADOS::do_start(optional_yield, const DoutPrefixProvider *dpp) { uinfo_cache.reset(new RGWChainedCacheImpl<user_info_cache_entry>); uinfo_cache->init(svc.cache); int r = svc.meta->create_be_handler(RGWSI_MetaBackend::Type::MDBE_SOBJ, &be_handler); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to create be handler: r=" << r << dendl; return r; } RGWSI_MetaBackend_Handler_SObj *bh = static_cast<RGWSI_MetaBackend_Handler_SObj *>(be_handler); auto module = new RGWSI_User_Module(svc); be_module.reset(module); bh->set_module(module); return 0; } rgw_raw_obj RGWSI_User_RADOS::get_buckets_obj(const rgw_user& user) const { string oid = user.to_str() + RGW_BUCKETS_OBJ_SUFFIX; return rgw_raw_obj(svc.zone->get_zone_params().user_uid_pool, oid); } int RGWSI_User_RADOS::read_user_info(RGWSI_MetaBackend::Context *ctx, const rgw_user& user, RGWUserInfo *info, RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, rgw_cache_entry_info * const cache_info, map<string, bufferlist> * const pattrs, optional_yield y, const DoutPrefixProvider *dpp) { if(user.id == RGW_USER_ANON_ID) { ldpp_dout(dpp, 20) << "RGWSI_User_RADOS::read_user_info(): anonymous user" << dendl; return -ENOENT; } bufferlist bl; RGWUID user_id; RGWSI_MBSObj_GetParams params(&bl, pattrs, pmtime); params.set_cache_info(cache_info); int ret = svc.meta_be->get_entry(ctx, get_meta_key(user), params, objv_tracker, y, dpp); if (ret < 0) { return ret; } auto iter = bl.cbegin(); try { decode(user_id, iter); if (user_id.user_id != user) { ldpp_dout(dpp, -1) << "ERROR: rgw_get_user_info_by_uid(): user id mismatch: " << user_id.user_id << " != " << user << dendl; return -EIO; } if (!iter.end()) { decode(*info, iter); } } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: failed to decode user info, caught buffer::error" << dendl; return -EIO; } return 0; } class PutOperation { RGWSI_User_RADOS::Svc& svc; RGWSI_MetaBackend_SObj::Context_SObj *ctx; RGWUID ui; const RGWUserInfo& info; RGWUserInfo *old_info; RGWObjVersionTracker *objv_tracker; const real_time& mtime; bool exclusive; map<string, bufferlist> *pattrs; RGWObjVersionTracker ot; string err_msg; optional_yield y; void set_err_msg(string msg) { if (!err_msg.empty()) { err_msg = std::move(msg); } } public: PutOperation(RGWSI_User_RADOS::Svc& svc, RGWSI_MetaBackend::Context *_ctx, const RGWUserInfo& info, RGWUserInfo *old_info, RGWObjVersionTracker *objv_tracker, const real_time& mtime, bool exclusive, map<string, bufferlist> *pattrs, optional_yield y) : svc(svc), info(info), old_info(old_info), objv_tracker(objv_tracker), mtime(mtime), exclusive(exclusive), pattrs(pattrs), y(y) { ctx = static_cast<RGWSI_MetaBackend_SObj::Context_SObj *>(_ctx); ui.user_id = info.user_id; } int prepare(const DoutPrefixProvider *dpp) { if (objv_tracker) { ot = *objv_tracker; } if (ot.write_version.tag.empty()) { if (ot.read_version.tag.empty()) { ot.generate_new_write_ver(svc.meta_be->ctx()); } else { ot.write_version = ot.read_version; ot.write_version.ver++; } } for (auto iter = info.swift_keys.begin(); iter != info.swift_keys.end(); ++iter) { if (old_info && old_info->swift_keys.count(iter->first) != 0) continue; auto& k = iter->second; /* check if swift mapping exists */ RGWUserInfo inf; int r = svc.user->get_user_info_by_swift(ctx, k.id, &inf, nullptr, nullptr, y, dpp); if (r >= 0 && inf.user_id != info.user_id && (!old_info || inf.user_id != old_info->user_id)) { ldpp_dout(dpp, 0) << "WARNING: can't store user info, swift id (" << k.id << ") already mapped to another user (" << info.user_id << ")" << dendl; return -EEXIST; } } /* check if access keys already exist */ for (auto iter = info.access_keys.begin(); iter != info.access_keys.end(); ++iter) { if (old_info && old_info->access_keys.count(iter->first) != 0) continue; auto& k = iter->second; RGWUserInfo inf; int r = svc.user->get_user_info_by_access_key(ctx, k.id, &inf, nullptr, nullptr, y, dpp); if (r >= 0 && inf.user_id != info.user_id && (!old_info || inf.user_id != old_info->user_id)) { ldpp_dout(dpp, 0) << "WARNING: can't store user info, access key already mapped to another user" << dendl; return -EEXIST; } } return 0; } int put(const DoutPrefixProvider *dpp) { bufferlist data_bl; encode(ui, data_bl); encode(info, data_bl); RGWSI_MBSObj_PutParams params(data_bl, pattrs, mtime, exclusive); int ret = svc.meta_be->put(ctx, RGWSI_User::get_meta_key(info.user_id), params, &ot, y, dpp); if (ret < 0) return ret; return 0; } int complete(const DoutPrefixProvider *dpp) { int ret; bufferlist link_bl; encode(ui, link_bl); if (!info.user_email.empty()) { if (!old_info || old_info->user_email.compare(info.user_email) != 0) { /* only if new index changed */ ret = rgw_put_system_obj(dpp, svc.sysobj, svc.zone->get_zone_params().user_email_pool, info.user_email, link_bl, exclusive, NULL, real_time(), y); if (ret < 0) return ret; } } const bool renamed = old_info && old_info->user_id != info.user_id; for (auto iter = info.access_keys.begin(); iter != info.access_keys.end(); ++iter) { auto& k = iter->second; if (old_info && old_info->access_keys.count(iter->first) != 0 && !renamed) continue; ret = rgw_put_system_obj(dpp, svc.sysobj, svc.zone->get_zone_params().user_keys_pool, k.id, link_bl, exclusive, NULL, real_time(), y); if (ret < 0) return ret; } for (auto siter = info.swift_keys.begin(); siter != info.swift_keys.end(); ++siter) { auto& k = siter->second; if (old_info && old_info->swift_keys.count(siter->first) != 0 && !renamed) continue; ret = rgw_put_system_obj(dpp, svc.sysobj, svc.zone->get_zone_params().user_swift_pool, k.id, link_bl, exclusive, NULL, real_time(), y); if (ret < 0) return ret; } if (old_info) { ret = remove_old_indexes(*old_info, info, y, dpp); if (ret < 0) { return ret; } } return 0; } int remove_old_indexes(const RGWUserInfo& old_info, const RGWUserInfo& new_info, optional_yield y, const DoutPrefixProvider *dpp) { int ret; if (!old_info.user_id.empty() && old_info.user_id != new_info.user_id) { if (old_info.user_id.tenant != new_info.user_id.tenant) { ldpp_dout(dpp, 0) << "ERROR: tenant mismatch: " << old_info.user_id.tenant << " != " << new_info.user_id.tenant << dendl; return -EINVAL; } ret = svc.user->remove_uid_index(ctx, old_info, nullptr, y, dpp); if (ret < 0 && ret != -ENOENT) { set_err_msg("ERROR: could not remove index for uid " + old_info.user_id.to_str()); return ret; } } if (!old_info.user_email.empty() && old_info.user_email != new_info.user_email) { ret = svc.user->remove_email_index(dpp, old_info.user_email, y); if (ret < 0 && ret != -ENOENT) { set_err_msg("ERROR: could not remove index for email " + old_info.user_email); return ret; } } for ([[maybe_unused]] const auto& [name, access_key] : old_info.access_keys) { if (!new_info.access_keys.count(access_key.id)) { ret = svc.user->remove_key_index(dpp, access_key, y); if (ret < 0 && ret != -ENOENT) { set_err_msg("ERROR: could not remove index for key " + access_key.id); return ret; } } } for (auto old_iter = old_info.swift_keys.begin(); old_iter != old_info.swift_keys.end(); ++old_iter) { const auto& swift_key = old_iter->second; auto new_iter = new_info.swift_keys.find(swift_key.id); if (new_iter == new_info.swift_keys.end()) { ret = svc.user->remove_swift_name_index(dpp, swift_key.id, y); if (ret < 0 && ret != -ENOENT) { set_err_msg("ERROR: could not remove index for swift_name " + swift_key.id); return ret; } } } return 0; } const string& get_err_msg() { return err_msg; } }; int RGWSI_User_RADOS::store_user_info(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& info, RGWUserInfo *old_info, RGWObjVersionTracker *objv_tracker, const real_time& mtime, bool exclusive, map<string, bufferlist> *attrs, optional_yield y, const DoutPrefixProvider *dpp) { PutOperation op(svc, ctx, info, old_info, objv_tracker, mtime, exclusive, attrs, y); int r = op.prepare(dpp); if (r < 0) { return r; } r = op.put(dpp); if (r < 0) { return r; } r = op.complete(dpp); if (r < 0) { return r; } return 0; } int RGWSI_User_RADOS::remove_key_index(const DoutPrefixProvider *dpp, const RGWAccessKey& access_key, optional_yield y) { rgw_raw_obj obj(svc.zone->get_zone_params().user_keys_pool, access_key.id); auto sysobj = svc.sysobj->get_obj(obj); return sysobj.wop().remove(dpp, y); } int RGWSI_User_RADOS::remove_email_index(const DoutPrefixProvider *dpp, const string& email, optional_yield y) { if (email.empty()) { return 0; } rgw_raw_obj obj(svc.zone->get_zone_params().user_email_pool, email); auto sysobj = svc.sysobj->get_obj(obj); return sysobj.wop().remove(dpp, y); } int RGWSI_User_RADOS::remove_swift_name_index(const DoutPrefixProvider *dpp, const string& swift_name, optional_yield y) { rgw_raw_obj obj(svc.zone->get_zone_params().user_swift_pool, swift_name); auto sysobj = svc.sysobj->get_obj(obj); return sysobj.wop().remove(dpp, y); } /** * delete a user's presence from the RGW system. * First remove their bucket ACLs, then delete them * from the user and user email pools. This leaves the pools * themselves alone, as well as any ACLs embedded in object xattrs. */ int RGWSI_User_RADOS::remove_user_info(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { int ret; auto kiter = info.access_keys.begin(); for (; kiter != info.access_keys.end(); ++kiter) { ldpp_dout(dpp, 10) << "removing key index: " << kiter->first << dendl; ret = remove_key_index(dpp, kiter->second, y); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: could not remove " << kiter->first << " (access key object), should be fixed (err=" << ret << ")" << dendl; return ret; } } auto siter = info.swift_keys.begin(); for (; siter != info.swift_keys.end(); ++siter) { auto& k = siter->second; ldpp_dout(dpp, 10) << "removing swift subuser index: " << k.id << dendl; /* check if swift mapping exists */ ret = remove_swift_name_index(dpp, k.id, y); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: could not remove " << k.id << " (swift name object), should be fixed (err=" << ret << ")" << dendl; return ret; } } ldpp_dout(dpp, 10) << "removing email index: " << info.user_email << dendl; ret = remove_email_index(dpp, info.user_email, y); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: could not remove email index object for " << info.user_email << ", should be fixed (err=" << ret << ")" << dendl; return ret; } rgw_raw_obj uid_bucks = get_buckets_obj(info.user_id); ldpp_dout(dpp, 10) << "removing user buckets index" << dendl; auto sysobj = svc.sysobj->get_obj(uid_bucks); ret = sysobj.wop().remove(dpp, y); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: could not remove " << info.user_id << ":" << uid_bucks << ", should be fixed (err=" << ret << ")" << dendl; return ret; } ret = remove_uid_index(ctx, info, objv_tracker, y, dpp); if (ret < 0 && ret != -ENOENT) { return ret; } return 0; } int RGWSI_User_RADOS::remove_uid_index(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& user_info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) { ldpp_dout(dpp, 10) << "removing user index: " << user_info.user_id << dendl; RGWSI_MBSObj_RemoveParams params; int ret = svc.meta_be->remove(ctx, get_meta_key(user_info.user_id), params, objv_tracker, y, dpp); if (ret < 0 && ret != -ENOENT && ret != -ECANCELED) { string key; user_info.user_id.to_str(key); rgw_raw_obj uid_obj(svc.zone->get_zone_params().user_uid_pool, key); ldpp_dout(dpp, 0) << "ERROR: could not remove " << user_info.user_id << ":" << uid_obj << ", should be fixed (err=" << ret << ")" << dendl; return ret; } return 0; } int RGWSI_User_RADOS::get_user_info_from_index(RGWSI_MetaBackend::Context* ctx, const string& key, const rgw_pool& pool, RGWUserInfo *info, RGWObjVersionTracker* objv_tracker, real_time* pmtime, optional_yield y, const DoutPrefixProvider* dpp) { string cache_key = pool.to_str() + "/" + key; if (auto e = uinfo_cache->find(cache_key)) { *info = e->info; if (objv_tracker) *objv_tracker = e->objv_tracker; if (pmtime) *pmtime = e->mtime; return 0; } user_info_cache_entry e; bufferlist bl; RGWUID uid; int ret = rgw_get_system_obj(svc.sysobj, pool, key, bl, nullptr, &e.mtime, y, dpp); if (ret < 0) return ret; rgw_cache_entry_info cache_info; auto iter = bl.cbegin(); try { decode(uid, iter); int ret = read_user_info(ctx, uid.user_id, &e.info, &e.objv_tracker, nullptr, &cache_info, nullptr, y, dpp); if (ret < 0) { return ret; } } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: failed to decode user info, caught buffer::error" << dendl; return -EIO; } uinfo_cache->put(dpp, svc.cache, cache_key, &e, { &cache_info }); *info = e.info; if (objv_tracker) *objv_tracker = e.objv_tracker; if (pmtime) *pmtime = e.mtime; return 0; } /** * Given an email, finds the user info associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ int RGWSI_User_RADOS::get_user_info_by_email(RGWSI_MetaBackend::Context *ctx, const string& email, RGWUserInfo *info, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp) { return get_user_info_from_index(ctx, email, svc.zone->get_zone_params().user_email_pool, info, objv_tracker, pmtime, y, dpp); } /** * Given an swift username, finds the user_info associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ int RGWSI_User_RADOS::get_user_info_by_swift(RGWSI_MetaBackend::Context *ctx, const string& swift_name, RGWUserInfo *info, /* out */ RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, optional_yield y, const DoutPrefixProvider *dpp) { return get_user_info_from_index(ctx, swift_name, svc.zone->get_zone_params().user_swift_pool, info, objv_tracker, pmtime, y, dpp); } /** * Given an access key, finds the user info associated with it. * returns: 0 on success, -ERR# on failure (including nonexistence) */ int RGWSI_User_RADOS::get_user_info_by_access_key(RGWSI_MetaBackend::Context *ctx, const std::string& access_key, RGWUserInfo *info, RGWObjVersionTracker* objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp) { return get_user_info_from_index(ctx, access_key, svc.zone->get_zone_params().user_keys_pool, info, objv_tracker, pmtime, y, dpp); } int RGWSI_User_RADOS::cls_user_update_buckets(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, list<cls_user_bucket_entry>& entries, bool add, optional_yield y) { auto rados_obj = svc.rados->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } librados::ObjectWriteOperation op; cls_user_set_buckets(op, entries, add); r = rados_obj.operate(dpp, &op, y); if (r < 0) { return r; } return 0; } int RGWSI_User_RADOS::cls_user_add_bucket(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, const cls_user_bucket_entry& entry, optional_yield y) { list<cls_user_bucket_entry> l; l.push_back(entry); return cls_user_update_buckets(dpp, obj, l, true, y); } int RGWSI_User_RADOS::cls_user_remove_bucket(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, const cls_user_bucket& bucket, optional_yield y) { auto rados_obj = svc.rados->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } librados::ObjectWriteOperation op; ::cls_user_remove_bucket(op, bucket); r = rados_obj.operate(dpp, &op, y); if (r < 0) return r; return 0; } int RGWSI_User_RADOS::add_bucket(const DoutPrefixProvider *dpp, const rgw_user& user, const rgw_bucket& bucket, ceph::real_time creation_time, optional_yield y) { int ret; cls_user_bucket_entry new_bucket; bucket.convert(&new_bucket.bucket); new_bucket.size = 0; if (real_clock::is_zero(creation_time)) new_bucket.creation_time = real_clock::now(); else new_bucket.creation_time = creation_time; rgw_raw_obj obj = get_buckets_obj(user); ret = cls_user_add_bucket(dpp, obj, new_bucket, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: error adding bucket to user: ret=" << ret << dendl; return ret; } return 0; } int RGWSI_User_RADOS::remove_bucket(const DoutPrefixProvider *dpp, const rgw_user& user, const rgw_bucket& _bucket, optional_yield y) { cls_user_bucket bucket; bucket.name = _bucket.name; rgw_raw_obj obj = get_buckets_obj(user); int ret = cls_user_remove_bucket(dpp, obj, bucket, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: error removing bucket from user: ret=" << ret << dendl; } return 0; } int RGWSI_User_RADOS::cls_user_flush_bucket_stats(const DoutPrefixProvider *dpp, rgw_raw_obj& user_obj, const RGWBucketEnt& ent, optional_yield y) { cls_user_bucket_entry entry; ent.convert(&entry); list<cls_user_bucket_entry> entries; entries.push_back(entry); int r = cls_user_update_buckets(dpp, user_obj, entries, false, y); if (r < 0) { ldpp_dout(dpp, 20) << "cls_user_update_buckets() returned " << r << dendl; return r; } return 0; } int RGWSI_User_RADOS::cls_user_list_buckets(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, const string& in_marker, const string& end_marker, const int max_entries, list<cls_user_bucket_entry>& entries, string * const out_marker, bool * const truncated, optional_yield y) { auto rados_obj = svc.rados->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } librados::ObjectReadOperation op; int rc; cls_user_bucket_list(op, in_marker, end_marker, max_entries, entries, out_marker, truncated, &rc); bufferlist ibl; r = rados_obj.operate(dpp, &op, &ibl, y); if (r < 0) return r; if (rc < 0) return rc; return 0; } int RGWSI_User_RADOS::list_buckets(const DoutPrefixProvider *dpp, const rgw_user& user, const string& marker, const string& end_marker, uint64_t max, RGWUserBuckets *buckets, bool *is_truncated, optional_yield y) { int ret; buckets->clear(); if (user.id == RGW_USER_ANON_ID) { ldpp_dout(dpp, 20) << "RGWSI_User_RADOS::list_buckets(): anonymous user" << dendl; *is_truncated = false; return 0; } rgw_raw_obj obj = get_buckets_obj(user); bool truncated = false; string m = marker; uint64_t total = 0; do { std::list<cls_user_bucket_entry> entries; ret = cls_user_list_buckets(dpp, obj, m, end_marker, max - total, entries, &m, &truncated, y); if (ret == -ENOENT) { ret = 0; } if (ret < 0) { return ret; } for (auto& entry : entries) { buckets->add(RGWBucketEnt(user, std::move(entry))); total++; } } while (truncated && total < max); if (is_truncated) { *is_truncated = truncated; } return 0; } int RGWSI_User_RADOS::flush_bucket_stats(const DoutPrefixProvider *dpp, const rgw_user& user, const RGWBucketEnt& ent, optional_yield y) { rgw_raw_obj obj = get_buckets_obj(user); return cls_user_flush_bucket_stats(dpp, obj, ent, y); } int RGWSI_User_RADOS::reset_bucket_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) { return cls_user_reset_stats(dpp, user, y); } int RGWSI_User_RADOS::cls_user_reset_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) { rgw_raw_obj obj = get_buckets_obj(user); auto rados_obj = svc.rados->obj(obj); int rval, r = rados_obj.open(dpp); if (r < 0) { return r; } cls_user_reset_stats2_op call; cls_user_reset_stats2_ret ret; do { buffer::list in, out; librados::ObjectWriteOperation op; call.time = real_clock::now(); ret.update_call(call); encode(call, in); op.exec("user", "reset_user_stats2", in, &out, &rval); r = rados_obj.operate(dpp, &op, y, librados::OPERATION_RETURNVEC); if (r < 0) { return r; } try { auto bliter = out.cbegin(); decode(ret, bliter); } catch (ceph::buffer::error& err) { return -EINVAL; } } while (ret.truncated); return rval; } int RGWSI_User_RADOS::complete_flush_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) { rgw_raw_obj obj = get_buckets_obj(user); auto rados_obj = svc.rados->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } librados::ObjectWriteOperation op; ::cls_user_complete_stats_sync(op); return rados_obj.operate(dpp, &op, y); } int RGWSI_User_RADOS::cls_user_get_header(const DoutPrefixProvider *dpp, const rgw_user& user, cls_user_header *header, optional_yield y) { rgw_raw_obj obj = get_buckets_obj(user); auto rados_obj = svc.rados->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } int rc; bufferlist ibl; librados::ObjectReadOperation op; ::cls_user_get_header(op, header, &rc); return rados_obj.operate(dpp, &op, &ibl, y); } int RGWSI_User_RADOS::cls_user_get_header_async(const DoutPrefixProvider *dpp, const string& user_str, RGWGetUserHeader_CB *cb) { rgw_raw_obj obj = get_buckets_obj(rgw_user(user_str)); auto rados_obj = svc.rados->obj(obj); int r = rados_obj.open(dpp); if (r < 0) { return r; } auto& ref = rados_obj.get_ref(); r = ::cls_user_get_header_async(ref.pool.ioctx(), ref.obj.oid, cb); if (r < 0) { return r; } return 0; } int RGWSI_User_RADOS::read_stats(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const rgw_user& user, RGWStorageStats *stats, ceph::real_time *last_stats_sync, ceph::real_time *last_stats_update, optional_yield y) { string user_str = user.to_str(); RGWUserInfo info; real_time mtime; int ret = read_user_info(ctx, user, &info, nullptr, &mtime, nullptr, nullptr, y, dpp); if (ret < 0) { return ret; } cls_user_header header; int r = cls_user_get_header(dpp, rgw_user(user_str), &header, y); if (r < 0 && r != -ENOENT) return r; const cls_user_stats& hs = header.stats; stats->size = hs.total_bytes; stats->size_rounded = hs.total_bytes_rounded; stats->num_objects = hs.total_entries; if (last_stats_sync) { *last_stats_sync = header.last_stats_sync; } if (last_stats_update) { *last_stats_update = header.last_stats_update; } return 0; } class RGWGetUserStatsContext : public RGWGetUserHeader_CB { RGWGetUserStats_CB *cb; public: explicit RGWGetUserStatsContext(RGWGetUserStats_CB * const cb) : cb(cb) {} void handle_response(int r, cls_user_header& header) override { const cls_user_stats& hs = header.stats; if (r >= 0) { RGWStorageStats stats; stats.size = hs.total_bytes; stats.size_rounded = hs.total_bytes_rounded; stats.num_objects = hs.total_entries; cb->set_response(stats); } cb->handle_response(r); cb->put(); } }; int RGWSI_User_RADOS::read_stats_async(const DoutPrefixProvider *dpp, const rgw_user& user, RGWGetUserStats_CB *_cb) { string user_str = user.to_str(); RGWGetUserStatsContext *cb = new RGWGetUserStatsContext(_cb); int r = cls_user_get_header_async(dpp, user_str, cb); if (r < 0) { delete cb; return r; } return 0; }
29,944
29.902993
160
cc
null
ceph-main/src/rgw/services/svc_user_rados.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_service.h" #include "svc_meta_be.h" #include "svc_user.h" #include "rgw_bucket.h" class RGWSI_RADOS; class RGWSI_Zone; class RGWSI_SysObj; class RGWSI_SysObj_Cache; class RGWSI_Meta; class RGWSI_SyncModules; class RGWSI_MetaBackend_Handler; struct rgw_cache_entry_info; class RGWGetUserHeader_CB; class RGWGetUserStats_CB; template <class T> class RGWChainedCacheImpl; class RGWSI_User_RADOS : public RGWSI_User { friend class PutOperation; std::unique_ptr<RGWSI_MetaBackend::Module> be_module; RGWSI_MetaBackend_Handler *be_handler; struct user_info_cache_entry { RGWUserInfo info; RGWObjVersionTracker objv_tracker; real_time mtime; }; using RGWChainedCacheImpl_user_info_cache_entry = RGWChainedCacheImpl<user_info_cache_entry>; std::unique_ptr<RGWChainedCacheImpl_user_info_cache_entry> uinfo_cache; rgw_raw_obj get_buckets_obj(const rgw_user& user_id) const; int get_user_info_from_index(RGWSI_MetaBackend::Context *ctx, const std::string& key, const rgw_pool& pool, RGWUserInfo *info, RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, optional_yield y, const DoutPrefixProvider *dpp); int remove_uid_index(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& user_info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp); int remove_key_index(const DoutPrefixProvider *dpp, const RGWAccessKey& access_key, optional_yield y); int remove_email_index(const DoutPrefixProvider *dpp, const std::string& email, optional_yield y); int remove_swift_name_index(const DoutPrefixProvider *dpp, const std::string& swift_name, optional_yield y); /* admin management */ int cls_user_update_buckets(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, std::list<cls_user_bucket_entry>& entries, bool add, optional_yield y); int cls_user_add_bucket(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, const cls_user_bucket_entry& entry, optional_yield y); int cls_user_remove_bucket(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, const cls_user_bucket& bucket, optional_yield y); /* quota stats */ int cls_user_flush_bucket_stats(const DoutPrefixProvider *dpp, rgw_raw_obj& user_obj, const RGWBucketEnt& ent, optional_yield y); int cls_user_list_buckets(const DoutPrefixProvider *dpp, rgw_raw_obj& obj, const std::string& in_marker, const std::string& end_marker, const int max_entries, std::list<cls_user_bucket_entry>& entries, std::string * const out_marker, bool * const truncated, optional_yield y); int cls_user_reset_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y); int cls_user_get_header(const DoutPrefixProvider *dpp, const rgw_user& user, cls_user_header *header, optional_yield y); int cls_user_get_header_async(const DoutPrefixProvider *dpp, const std::string& user, RGWGetUserHeader_CB *cb); int do_start(optional_yield, const DoutPrefixProvider *dpp) override; public: struct Svc { RGWSI_User_RADOS *user{nullptr}; RGWSI_RADOS *rados{nullptr}; RGWSI_Zone *zone{nullptr}; RGWSI_SysObj *sysobj{nullptr}; RGWSI_SysObj_Cache *cache{nullptr}; RGWSI_Meta *meta{nullptr}; RGWSI_MetaBackend *meta_be{nullptr}; RGWSI_SyncModules *sync_modules{nullptr}; } svc; RGWSI_User_RADOS(CephContext *cct); ~RGWSI_User_RADOS(); void init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc, RGWSI_SysObj *_sysobj_svc, RGWSI_SysObj_Cache *_cache_svc, RGWSI_Meta *_meta_svc, RGWSI_MetaBackend *_meta_be_svc, RGWSI_SyncModules *_sync_modules); RGWSI_MetaBackend_Handler *get_be_handler() override { return be_handler; } int read_user_info(RGWSI_MetaBackend::Context *ctx, const rgw_user& user, RGWUserInfo *info, RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, rgw_cache_entry_info * const cache_info, std::map<std::string, bufferlist> * const pattrs, optional_yield y, const DoutPrefixProvider *dpp) override; int store_user_info(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& info, RGWUserInfo *old_info, RGWObjVersionTracker *objv_tracker, const real_time& mtime, bool exclusive, std::map<std::string, bufferlist> *attrs, optional_yield y, const DoutPrefixProvider *dpp) override; int remove_user_info(RGWSI_MetaBackend::Context *ctx, const RGWUserInfo& info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) override; int get_user_info_by_email(RGWSI_MetaBackend::Context *ctx, const std::string& email, RGWUserInfo *info, RGWObjVersionTracker *objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp) override; int get_user_info_by_swift(RGWSI_MetaBackend::Context *ctx, const std::string& swift_name, RGWUserInfo *info, /* out */ RGWObjVersionTracker * const objv_tracker, real_time * const pmtime, optional_yield y, const DoutPrefixProvider *dpp) override; int get_user_info_by_access_key(RGWSI_MetaBackend::Context *ctx, const std::string& access_key, RGWUserInfo *info, RGWObjVersionTracker* objv_tracker, real_time *pmtime, optional_yield y, const DoutPrefixProvider *dpp) override; /* user buckets directory */ int add_bucket(const DoutPrefixProvider *dpp, const rgw_user& user, const rgw_bucket& bucket, ceph::real_time creation_time, optional_yield y) override; int remove_bucket(const DoutPrefixProvider *dpp, const rgw_user& user, const rgw_bucket& _bucket, optional_yield y) override; int list_buckets(const DoutPrefixProvider *dpp, const rgw_user& user, const std::string& marker, const std::string& end_marker, uint64_t max, RGWUserBuckets *buckets, bool *is_truncated, optional_yield y) override; /* quota related */ int flush_bucket_stats(const DoutPrefixProvider *dpp, const rgw_user& user, const RGWBucketEnt& ent, optional_yield y) override; int complete_flush_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) override; int reset_bucket_stats(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y) override; int read_stats(const DoutPrefixProvider *dpp, RGWSI_MetaBackend::Context *ctx, const rgw_user& user, RGWStorageStats *stats, ceph::real_time *last_stats_sync, /* last time a full stats sync completed */ ceph::real_time *last_stats_update, optional_yield y) override; /* last time a stats update was done */ int read_stats_async(const DoutPrefixProvider *dpp, const rgw_user& user, RGWGetUserStats_CB *cb) override; };
8,779
40.415094
150
h
null
ceph-main/src/rgw/services/svc_zone.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_zone.h" #include "svc_rados.h" #include "svc_sys_obj.h" #include "svc_sync_modules.h" #include "rgw_zone.h" #include "rgw_rest_conn.h" #include "rgw_bucket_sync.h" #include "common/errno.h" #include "include/random.h" #define dout_subsys ceph_subsys_rgw using namespace std; using namespace rgw_zone_defaults; RGWSI_Zone::RGWSI_Zone(CephContext *cct) : RGWServiceInstance(cct) { } void RGWSI_Zone::init(RGWSI_SysObj *_sysobj_svc, RGWSI_RADOS * _rados_svc, RGWSI_SyncModules * _sync_modules_svc, RGWSI_Bucket_Sync *_bucket_sync_svc) { sysobj_svc = _sysobj_svc; rados_svc = _rados_svc; sync_modules_svc = _sync_modules_svc; bucket_sync_svc = _bucket_sync_svc; realm = new RGWRealm(); zonegroup = new RGWZoneGroup(); zone_public_config = new RGWZone(); zone_params = new RGWZoneParams(); current_period = new RGWPeriod(); } RGWSI_Zone::~RGWSI_Zone() { delete realm; delete zonegroup; delete zone_public_config; delete zone_params; delete current_period; } std::shared_ptr<RGWBucketSyncPolicyHandler> RGWSI_Zone::get_sync_policy_handler(std::optional<rgw_zone_id> zone) const { if (!zone || *zone == zone_id()) { return sync_policy_handler; } auto iter = sync_policy_handlers.find(*zone); if (iter == sync_policy_handlers.end()) { return std::shared_ptr<RGWBucketSyncPolicyHandler>(); } return iter->second; } bool RGWSI_Zone::zone_syncs_from(const RGWZone& target_zone, const RGWZone& source_zone) const { return target_zone.syncs_from(source_zone.name) && sync_modules_svc->get_manager()->supports_data_export(source_zone.tier_type); } int RGWSI_Zone::search_realm_with_zone(const DoutPrefixProvider *dpp, const rgw_zone_id& zid, RGWRealm *prealm, RGWPeriod *pperiod, RGWZoneGroup *pzonegroup, bool *pfound, optional_yield y) { auto& found = *pfound; found = false; list<string> realms; int r = list_realms(dpp, realms); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to list realms: r=" << r << dendl; return r; } for (auto& realm_name : realms) { string realm_id; RGWRealm realm(realm_id, realm_name); r = realm.init(dpp, cct, sysobj_svc, y); if (r < 0) { ldpp_dout(dpp, 0) << "WARNING: can't open realm " << realm_name << ": " << cpp_strerror(-r) << " ... skipping" << dendl; continue; } r = realm.find_zone(dpp, zid, pperiod, pzonegroup, &found, y); if (r < 0) { ldpp_dout(dpp, 20) << __func__ << "(): ERROR: realm.find_zone() returned r=" << r<< dendl; return r; } if (found) { *prealm = realm; ldpp_dout(dpp, 20) << __func__ << "(): found realm_id=" << realm_id << " realm_name=" << realm_name << dendl; return 0; } } return 0; } int RGWSI_Zone::do_start(optional_yield y, const DoutPrefixProvider *dpp) { int ret = sysobj_svc->start(y, dpp); if (ret < 0) { return ret; } assert(sysobj_svc->is_started()); /* if not then there's ordering issue */ ret = rados_svc->start(y, dpp); if (ret < 0) { return ret; } ret = realm->init(dpp, cct, sysobj_svc, y); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "failed reading realm info: ret "<< ret << " " << cpp_strerror(-ret) << dendl; return ret; } ldpp_dout(dpp, 20) << "realm " << realm->get_name() << " " << realm->get_id() << dendl; ret = current_period->init(dpp, cct, sysobj_svc, realm->get_id(), y, realm->get_name()); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "failed reading current period info: " << " " << cpp_strerror(-ret) << dendl; return ret; } ret = zone_params->init(dpp, cct, sysobj_svc, y); bool found_zone = (ret == 0); if (ret < 0 && ret != -ENOENT) { lderr(cct) << "failed reading zone info: ret "<< ret << " " << cpp_strerror(-ret) << dendl; return ret; } cur_zone_id = rgw_zone_id(zone_params->get_id()); bool found_period_conf = false; /* try to find zone in period config (if we have one) */ if (found_zone && !current_period->get_id().empty()) { found_period_conf = current_period->find_zone(dpp, cur_zone_id, zonegroup, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: current_period->find_zone() returned ret=" << ret << dendl; return ret; } if (!found_period_conf) { ldpp_dout(dpp, 0) << "period (" << current_period->get_id() << " does not have zone " << cur_zone_id << " configured" << dendl; } } RGWRealm search_realm; if (found_zone && !found_period_conf) { ldpp_dout(dpp, 20) << "searching for the correct realm" << dendl; ret = search_realm_with_zone(dpp, cur_zone_id, realm, current_period, zonegroup, &found_period_conf, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: search_realm_conf() failed: ret="<< ret << dendl; return ret; } } bool zg_initialized = found_period_conf; if (!zg_initialized) { /* couldn't find a proper period config, use local zonegroup */ ret = zonegroup->init(dpp, cct, sysobj_svc, y); zg_initialized = (ret == 0); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "failed reading zonegroup info: " << cpp_strerror(-ret) << dendl; return ret; } } auto& zonegroup_param = cct->_conf->rgw_zonegroup; bool init_from_period = found_period_conf; bool explicit_zg = !zonegroup_param.empty(); if (!zg_initialized && (!explicit_zg || zonegroup_param == default_zonegroup_name)) { /* we couldn't initialize any zonegroup, falling back to a non-multisite config with default zonegroup */ ret = create_default_zg(dpp, y); if (ret < 0) { return ret; } zg_initialized = true; } if (!zg_initialized) { ldpp_dout(dpp, 0) << "ERROR: could not find zonegroup (" << zonegroup_param << ")" << dendl; return -ENOENT; } /* we have zonegroup now */ if (explicit_zg && zonegroup->get_name() != zonegroup_param) { ldpp_dout(dpp, 0) << "ERROR: incorrect zonegroup: " << zonegroup_param << " (got: " << zonegroup_param << ", expected: " << zonegroup->get_name() << ")" << dendl; return -EINVAL; } auto& zone_param = cct->_conf->rgw_zone; bool explicit_zone = !zone_param.empty(); if (!found_zone) { if ((!explicit_zone || zone_param == default_zone_name) && zonegroup->get_name() == default_zonegroup_name) { ret = init_default_zone(dpp, y); if (ret < 0 && ret != -ENOENT) { return ret; } cur_zone_id = zone_params->get_id(); } else { ldpp_dout(dpp, 0) << "ERROR: could not find zone (" << zone_param << ")" << dendl; return -ENOENT; } } /* we have zone now */ auto zone_iter = zonegroup->zones.find(zone_params->get_id()); if (zone_iter == zonegroup->zones.end()) { /* shouldn't happen if relying on period config */ if (!init_from_period) { ldpp_dout(dpp, -1) << "Cannot find zone id=" << zone_params->get_id() << " (name=" << zone_params->get_name() << ")" << dendl; return -EINVAL; } ldpp_dout(dpp, 1) << "Cannot find zone id=" << zone_params->get_id() << " (name=" << zone_params->get_name() << "), switching to local zonegroup configuration" << dendl; init_from_period = false; zone_iter = zonegroup->zones.find(zone_params->get_id()); } if (zone_iter == zonegroup->zones.end()) { ldpp_dout(dpp, -1) << "Cannot find zone id=" << zone_params->get_id() << " (name=" << zone_params->get_name() << ")" << dendl; return -EINVAL; } *zone_public_config = zone_iter->second; ldout(cct, 20) << "zone " << zone_params->get_name() << " found" << dendl; ldpp_dout(dpp, 4) << "Realm: " << std::left << setw(20) << realm->get_name() << " (" << realm->get_id() << ")" << dendl; ldpp_dout(dpp, 4) << "ZoneGroup: " << std::left << setw(20) << zonegroup->get_name() << " (" << zonegroup->get_id() << ")" << dendl; ldpp_dout(dpp, 4) << "Zone: " << std::left << setw(20) << zone_params->get_name() << " (" << zone_params->get_id() << ")" << dendl; if (init_from_period) { ldpp_dout(dpp, 4) << "using period configuration: " << current_period->get_id() << ":" << current_period->get_epoch() << dendl; ret = init_zg_from_period(dpp, y); if (ret < 0) { return ret; } } else { ldout(cct, 10) << "cannot find current period zonegroup using local zonegroup configuration" << dendl; ret = init_zg_from_local(dpp, y); if (ret < 0) { return ret; } // read period_config into current_period auto& period_config = current_period->get_config(); ret = period_config.read(dpp, sysobj_svc, zonegroup->realm_id, y); if (ret < 0 && ret != -ENOENT) { ldout(cct, 0) << "ERROR: failed to read period config: " << cpp_strerror(ret) << dendl; return ret; } } zone_short_id = current_period->get_map().get_zone_short_id(zone_params->get_id()); for (auto ziter : zonegroup->zones) { auto zone_handler = std::make_shared<RGWBucketSyncPolicyHandler>(this, sync_modules_svc, bucket_sync_svc, ziter.second.id); ret = zone_handler->init(dpp, y); if (ret < 0) { ldpp_dout(dpp, -1) << "ERROR: could not initialize zone policy handler for zone=" << ziter.second.name << dendl; return ret; } sync_policy_handlers[ziter.second.id] = zone_handler; } sync_policy_handler = sync_policy_handlers[zone_id()]; /* we made sure earlier that zonegroup->zones has our zone */ set<rgw_zone_id> source_zones; set<rgw_zone_id> target_zones; sync_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 */ ret = sync_modules_svc->start(y, dpp); if (ret < 0) { return ret; } auto sync_modules = sync_modules_svc->get_manager(); RGWSyncModuleRef sm; if (!sync_modules->get_module(zone_public_config->tier_type, &sm)) { ldpp_dout(dpp, -1) << "ERROR: tier type not found: " << zone_public_config->tier_type << dendl; return -EINVAL; } writeable_zone = sm->supports_writes(); exports_data = sm->supports_data_export(); /* first build all zones index */ for (auto ziter : zonegroup->zones) { const rgw_zone_id& id = ziter.first; RGWZone& z = ziter.second; zone_id_by_name[z.name] = id; zone_by_id[id] = z; } if (zone_by_id.find(zone_id()) == zone_by_id.end()) { ldpp_dout(dpp, 0) << "WARNING: could not find zone config in zonegroup for local zone (" << zone_id() << "), will use defaults" << dendl; } for (const auto& ziter : zonegroup->zones) { const rgw_zone_id& id = ziter.first; const RGWZone& z = ziter.second; if (id == zone_id()) { continue; } if (z.endpoints.empty()) { ldpp_dout(dpp, 0) << "WARNING: can't generate connection for zone " << z.id << " id " << z.name << ": no endpoints defined" << dendl; continue; } ldpp_dout(dpp, 20) << "generating connection object for zone " << z.name << " id " << z.id << dendl; RGWRESTConn *conn = new RGWRESTConn(cct, z.id, z.endpoints, zone_params->system_key, zonegroup->get_id(), zonegroup->api_name); zone_conn_map[id] = conn; bool zone_is_source = source_zones.find(z.id) != source_zones.end(); bool zone_is_target = target_zones.find(z.id) != target_zones.end(); if (zone_is_source || zone_is_target) { if (zone_is_source && sync_modules->supports_data_export(z.tier_type)) { data_sync_source_zones.push_back(&z); } if (zone_is_target) { zone_data_notify_to_map[id] = conn; } } else { ldpp_dout(dpp, 20) << "NOTICE: not syncing to/from zone " << z.name << " id " << z.id << dendl; } } ldpp_dout(dpp, 20) << "started zone id=" << zone_params->get_id() << " (name=" << zone_params->get_name() << ") with tier type = " << zone_public_config->tier_type << dendl; return 0; } void RGWSI_Zone::shutdown() { delete rest_master_conn; for (auto& item : zone_conn_map) { auto conn = item.second; delete conn; } for (auto& item : zonegroup_conn_map) { auto conn = item.second; delete conn; } } int RGWSI_Zone::list_regions(const DoutPrefixProvider *dpp, list<string>& regions) { RGWZoneGroup zonegroup; RGWSI_SysObj::Pool syspool = sysobj_svc->get_pool(zonegroup.get_pool(cct)); return syspool.list_prefixed_objs(dpp, region_info_oid_prefix, &regions); } int RGWSI_Zone::list_zonegroups(const DoutPrefixProvider *dpp, list<string>& zonegroups) { RGWZoneGroup zonegroup; RGWSI_SysObj::Pool syspool = sysobj_svc->get_pool(zonegroup.get_pool(cct)); return syspool.list_prefixed_objs(dpp, zonegroup_names_oid_prefix, &zonegroups); } int RGWSI_Zone::list_zones(const DoutPrefixProvider *dpp, list<string>& zones) { RGWZoneParams zoneparams; RGWSI_SysObj::Pool syspool = sysobj_svc->get_pool(zoneparams.get_pool(cct)); return syspool.list_prefixed_objs(dpp, zone_names_oid_prefix, &zones); } int RGWSI_Zone::list_realms(const DoutPrefixProvider *dpp, list<string>& realms) { RGWRealm realm(cct, sysobj_svc); RGWSI_SysObj::Pool syspool = sysobj_svc->get_pool(realm.get_pool(cct)); return syspool.list_prefixed_objs(dpp, realm_names_oid_prefix, &realms); } int RGWSI_Zone::list_periods(const DoutPrefixProvider *dpp, list<string>& periods) { RGWPeriod period; list<string> raw_periods; RGWSI_SysObj::Pool syspool = sysobj_svc->get_pool(period.get_pool(cct)); int ret = syspool.list_prefixed_objs(dpp, period.get_info_oid_prefix(), &raw_periods); if (ret < 0) { return ret; } for (const auto& oid : raw_periods) { size_t pos = oid.find("."); if (pos != std::string::npos) { periods.push_back(oid.substr(0, pos)); } else { periods.push_back(oid); } } periods.sort(); // unique() only detects duplicates if they're adjacent periods.unique(); return 0; } int RGWSI_Zone::list_periods(const DoutPrefixProvider *dpp, const string& current_period, list<string>& periods, optional_yield y) { int ret = 0; string period_id = current_period; while(!period_id.empty()) { RGWPeriod period(period_id); ret = period.init(dpp, cct, sysobj_svc, y); if (ret < 0) { return ret; } periods.push_back(period.get_id()); period_id = period.get_predecessor(); } return ret; } /** * Add new connection to connections map * @param zonegroup_conn_map map which new connection will be added to * @param zonegroup zonegroup which new connection will connect to * @param new_connection pointer to new connection instance */ static void add_new_connection_to_map(map<string, RGWRESTConn *> &zonegroup_conn_map, const RGWZoneGroup &zonegroup, RGWRESTConn *new_connection) { // Delete if connection is already exists map<string, RGWRESTConn *>::iterator iterZoneGroup = zonegroup_conn_map.find(zonegroup.get_id()); if (iterZoneGroup != zonegroup_conn_map.end()) { delete iterZoneGroup->second; } // Add new connection to connections map zonegroup_conn_map[zonegroup.get_id()] = new_connection; } int RGWSI_Zone::init_zg_from_period(const DoutPrefixProvider *dpp, optional_yield y) { ldout(cct, 20) << "period zonegroup name " << zonegroup->get_name() << dendl; map<string, RGWZoneGroup>::const_iterator iter = current_period->get_map().zonegroups.find(zonegroup->get_id()); if (iter != current_period->get_map().zonegroups.end()) { ldpp_dout(dpp, 20) << "using current period zonegroup " << zonegroup->get_name() << dendl; *zonegroup = iter->second; int ret = zonegroup->init(dpp, cct, sysobj_svc, y, false); if (ret < 0) { ldpp_dout(dpp, 0) << "failed init zonegroup: " << " " << cpp_strerror(-ret) << dendl; return ret; } } for (iter = current_period->get_map().zonegroups.begin(); iter != current_period->get_map().zonegroups.end(); ++iter){ const RGWZoneGroup& zg = iter->second; // use endpoints from the zonegroup's master zone auto master = zg.zones.find(zg.master_zone); if (master == zg.zones.end()) { // Check for empty zonegroup which can happen if zone was deleted before removal if (zg.zones.size() == 0) continue; // fix missing master zone for a single zone zonegroup if (zg.master_zone.empty() && zg.zones.size() == 1) { master = zg.zones.begin(); ldpp_dout(dpp, 0) << "zonegroup " << zg.get_name() << " missing master_zone, setting zone " << master->second.name << " id:" << master->second.id << " as master" << dendl; if (zonegroup->get_id() == zg.get_id()) { zonegroup->master_zone = master->second.id; int ret = zonegroup->update(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "error updating zonegroup : " << cpp_strerror(-ret) << dendl; return ret; } } else { RGWZoneGroup fixed_zg(zg.get_id(),zg.get_name()); int ret = fixed_zg.init(dpp, cct, sysobj_svc, y); if (ret < 0) { ldpp_dout(dpp, 0) << "error initializing zonegroup : " << cpp_strerror(-ret) << dendl; return ret; } fixed_zg.master_zone = master->second.id; ret = fixed_zg.update(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "error initializing zonegroup : " << cpp_strerror(-ret) << dendl; return ret; } } } else { ldpp_dout(dpp, 0) << "zonegroup " << zg.get_name() << " missing zone for master_zone=" << zg.master_zone << dendl; return -EINVAL; } } const auto& endpoints = master->second.endpoints; add_new_connection_to_map(zonegroup_conn_map, zg, new RGWRESTConn(cct, zg.get_id(), endpoints, zone_params->system_key, zonegroup->get_id(), zg.api_name)); if (!current_period->get_master_zonegroup().empty() && zg.get_id() == current_period->get_master_zonegroup()) { rest_master_conn = new RGWRESTConn(cct, zg.get_id(), endpoints, zone_params->system_key, zonegroup->get_id(), zg.api_name); } } return 0; } int RGWSI_Zone::create_default_zg(const DoutPrefixProvider *dpp, optional_yield y) { ldout(cct, 10) << "Creating default zonegroup " << dendl; int ret = zonegroup->create_default(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "failure in zonegroup create_default: ret "<< ret << " " << cpp_strerror(-ret) << dendl; return ret; } ret = zonegroup->init(dpp, cct, sysobj_svc, y); if (ret < 0) { ldout(cct, 0) << "failure in zonegroup create_default: ret "<< ret << " " << cpp_strerror(-ret) << dendl; return ret; } return 0; } int RGWSI_Zone::init_default_zone(const DoutPrefixProvider *dpp, optional_yield y) { ldpp_dout(dpp, 10) << " Using default name "<< default_zone_name << dendl; zone_params->set_name(default_zone_name); int ret = zone_params->init(dpp, cct, sysobj_svc, y); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "failed reading zone params info: " << " " << cpp_strerror(-ret) << dendl; return ret; } return 0; } int RGWSI_Zone::init_zg_from_local(const DoutPrefixProvider *dpp, optional_yield y) { ldpp_dout(dpp, 20) << "zonegroup " << zonegroup->get_name() << dendl; if (zonegroup->is_master_zonegroup()) { // use endpoints from the zonegroup's master zone auto master = zonegroup->zones.find(zonegroup->master_zone); if (master == zonegroup->zones.end()) { // fix missing master zone for a single zone zonegroup if (zonegroup->master_zone.empty() && zonegroup->zones.size() == 1) { master = zonegroup->zones.begin(); ldpp_dout(dpp, 0) << "zonegroup " << zonegroup->get_name() << " missing master_zone, setting zone " << master->second.name << " id:" << master->second.id << " as master" << dendl; zonegroup->master_zone = master->second.id; int ret = zonegroup->update(dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "error initializing zonegroup : " << cpp_strerror(-ret) << dendl; return ret; } } else { ldpp_dout(dpp, 0) << "zonegroup " << zonegroup->get_name() << " missing zone for " "master_zone=" << zonegroup->master_zone << dendl; return -EINVAL; } } const auto& endpoints = master->second.endpoints; rest_master_conn = new RGWRESTConn(cct, zonegroup->get_id(), endpoints, zone_params->system_key, zonegroup->get_id(), zonegroup->api_name); } return 0; } const RGWZoneParams& RGWSI_Zone::get_zone_params() const { return *zone_params; } const RGWZone& RGWSI_Zone::get_zone() const { return *zone_public_config; } const RGWZoneGroup& RGWSI_Zone::get_zonegroup() const { return *zonegroup; } int RGWSI_Zone::get_zonegroup(const string& id, RGWZoneGroup& zg) const { int ret = 0; if (id == zonegroup->get_id()) { zg = *zonegroup; } else if (!current_period->get_id().empty()) { ret = current_period->get_zonegroup(zg, id); } return ret; } const RGWRealm& RGWSI_Zone::get_realm() const { return *realm; } const RGWPeriod& RGWSI_Zone::get_current_period() const { return *current_period; } const string& RGWSI_Zone::get_current_period_id() const { return current_period->get_id(); } bool RGWSI_Zone::has_zonegroup_api(const std::string& api) const { if (!current_period->get_id().empty()) { const auto& zonegroups_by_api = current_period->get_map().zonegroups_by_api; if (zonegroups_by_api.find(api) != zonegroups_by_api.end()) return true; } else if (zonegroup->api_name == api) { return true; } return false; } bool RGWSI_Zone::zone_is_writeable() { return writeable_zone && !get_zone().is_read_only(); } uint32_t RGWSI_Zone::get_zone_short_id() const { return zone_short_id; } const string& RGWSI_Zone::zone_name() const { return get_zone_params().get_name(); } RGWZone* RGWSI_Zone::find_zone(const rgw_zone_id& id) { auto iter = zone_by_id.find(id); if (iter == zone_by_id.end()) { return nullptr; } return &(iter->second); } RGWRESTConn *RGWSI_Zone::get_zone_conn(const rgw_zone_id& zone_id) { auto citer = zone_conn_map.find(zone_id.id); if (citer == zone_conn_map.end()) { return NULL; } return citer->second; } RGWRESTConn *RGWSI_Zone::get_zone_conn_by_name(const string& name) { auto i = zone_id_by_name.find(name); if (i == zone_id_by_name.end()) { return NULL; } return get_zone_conn(i->second); } bool RGWSI_Zone::find_zone_id_by_name(const string& name, rgw_zone_id *id) { auto i = zone_id_by_name.find(name); if (i == zone_id_by_name.end()) { return false; } *id = i->second; return true; } bool RGWSI_Zone::need_to_sync() const { return !(zonegroup->master_zone.empty() || !rest_master_conn || current_period->get_id().empty()); } bool RGWSI_Zone::need_to_log_data() const { return (zone_public_config->log_data && sync_module_exports_data()); } bool RGWSI_Zone::is_meta_master() const { if (!zonegroup->is_master_zonegroup()) { return false; } return (zonegroup->master_zone == zone_public_config->id); } bool RGWSI_Zone::need_to_log_metadata() const { return is_meta_master() && (zonegroup->zones.size() > 1 || current_period->is_multi_zonegroups_with_zones()); } bool RGWSI_Zone::can_reshard() const { if (current_period->get_id().empty()) { return true; // no realm } if (zonegroup->zones.size() == 1 && current_period->is_single_zonegroup()) { return true; // single zone/zonegroup } // 'resharding' feature enabled in zonegroup return zonegroup->supports(rgw::zone_features::resharding); } /** * Check to see if the bucket metadata could be synced * bucket: the bucket to check * Returns false is the bucket is not synced */ bool RGWSI_Zone::is_syncing_bucket_meta(const rgw_bucket& bucket) { /* no current period */ if (current_period->get_id().empty()) { return false; } /* zonegroup is not master zonegroup */ if (!zonegroup->is_master_zonegroup()) { return false; } /* single zonegroup and a single zone */ if (current_period->is_single_zonegroup() && zonegroup->zones.size() == 1) { return false; } /* zone is not master */ if (zonegroup->master_zone != zone_public_config->id) { return false; } return true; } int RGWSI_Zone::select_new_bucket_location(const DoutPrefixProvider *dpp, const RGWUserInfo& user_info, const string& zonegroup_id, const rgw_placement_rule& request_rule, rgw_placement_rule *pselected_rule_name, RGWZonePlacementInfo *rule_info, optional_yield y) { /* first check that zonegroup exists within current period. */ RGWZoneGroup zonegroup; int ret = get_zonegroup(zonegroup_id, zonegroup); if (ret < 0) { ldpp_dout(dpp, 0) << "could not find zonegroup " << zonegroup_id << " in current period" << dendl; return ret; } const rgw_placement_rule *used_rule; /* find placement rule. Hierarchy: request rule > user default rule > zonegroup default rule */ std::map<std::string, RGWZoneGroupPlacementTarget>::const_iterator titer; if (!request_rule.name.empty()) { used_rule = &request_rule; titer = zonegroup.placement_targets.find(request_rule.name); if (titer == zonegroup.placement_targets.end()) { ldpp_dout(dpp, 0) << "could not find requested placement id " << request_rule << " within zonegroup " << dendl; return -ERR_INVALID_LOCATION_CONSTRAINT; } } else if (!user_info.default_placement.name.empty()) { used_rule = &user_info.default_placement; titer = zonegroup.placement_targets.find(user_info.default_placement.name); if (titer == zonegroup.placement_targets.end()) { ldpp_dout(dpp, 0) << "could not find user default placement id " << user_info.default_placement << " within zonegroup " << dendl; return -ERR_INVALID_LOCATION_CONSTRAINT; } } else { if (zonegroup.default_placement.name.empty()) { // zonegroup default rule as fallback, it should not be empty. ldpp_dout(dpp, 0) << "misconfiguration, zonegroup default placement id should not be empty." << dendl; return -ERR_ZONEGROUP_DEFAULT_PLACEMENT_MISCONFIGURATION; } else { used_rule = &zonegroup.default_placement; titer = zonegroup.placement_targets.find(zonegroup.default_placement.name); if (titer == zonegroup.placement_targets.end()) { ldpp_dout(dpp, 0) << "could not find zonegroup default placement id " << zonegroup.default_placement << " within zonegroup " << dendl; return -ERR_INVALID_LOCATION_CONSTRAINT; } } } /* now check tag for the rule, whether user is permitted to use rule */ const auto& target_rule = titer->second; if (!target_rule.user_permitted(user_info.placement_tags)) { ldpp_dout(dpp, 0) << "user not permitted to use placement rule " << titer->first << dendl; return -EPERM; } const string *storage_class = &request_rule.storage_class; if (storage_class->empty()) { storage_class = &used_rule->storage_class; } rgw_placement_rule rule(titer->first, *storage_class); if (pselected_rule_name) { *pselected_rule_name = rule; } return select_bucket_location_by_rule(dpp, rule, rule_info, y); } int RGWSI_Zone::select_bucket_location_by_rule(const DoutPrefixProvider *dpp, const rgw_placement_rule& location_rule, RGWZonePlacementInfo *rule_info, optional_yield y) { if (location_rule.name.empty()) { /* we can only reach here if we're trying to set a bucket location from a bucket * created on a different zone, using a legacy / default pool configuration */ if (rule_info) { return select_legacy_bucket_placement(dpp, rule_info, y); } return 0; } /* * make sure that zone has this rule configured. We're * checking it for the local zone, because that's where this bucket object is going to * reside. */ auto piter = zone_params->placement_pools.find(location_rule.name); if (piter == zone_params->placement_pools.end()) { /* couldn't find, means we cannot really place data for this bucket in this zone */ ldpp_dout(dpp, 0) << "ERROR: This zone does not contain placement rule " << location_rule << " present in the zonegroup!" << dendl; return -EINVAL; } auto storage_class = location_rule.get_storage_class(); if (!piter->second.storage_class_exists(storage_class)) { ldpp_dout(dpp, 5) << "requested storage class does not exist: " << storage_class << dendl; return -EINVAL; } RGWZonePlacementInfo& placement_info = piter->second; if (rule_info) { *rule_info = placement_info; } return 0; } int RGWSI_Zone::select_bucket_placement(const DoutPrefixProvider *dpp, const RGWUserInfo& user_info, const string& zonegroup_id, const rgw_placement_rule& placement_rule, rgw_placement_rule *pselected_rule, RGWZonePlacementInfo *rule_info, optional_yield y) { if (!zone_params->placement_pools.empty()) { return select_new_bucket_location(dpp, user_info, zonegroup_id, placement_rule, pselected_rule, rule_info, y); } if (pselected_rule) { pselected_rule->clear(); } if (rule_info) { return select_legacy_bucket_placement(dpp, rule_info, y); } return 0; } int RGWSI_Zone::select_legacy_bucket_placement(const DoutPrefixProvider *dpp, RGWZonePlacementInfo *rule_info, optional_yield y) { bufferlist map_bl; map<string, bufferlist> m; string pool_name; bool write_map = false; rgw_raw_obj obj(zone_params->domain_root, avail_pools); auto sysobj = sysobj_svc->get_obj(obj); int ret = sysobj.rop().read(dpp, &map_bl, y); if (ret < 0) { goto read_omap; } try { auto iter = map_bl.cbegin(); decode(m, iter); } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: couldn't decode avail_pools" << dendl; } read_omap: if (m.empty()) { ret = sysobj.omap().get_all(dpp, &m, y); write_map = true; } if (ret < 0 || m.empty()) { vector<rgw_pool> pools; string s = string("default.") + default_storage_pool_suffix; pools.push_back(rgw_pool(s)); vector<int> retcodes; bufferlist bl; ret = rados_svc->pool().create(dpp, pools, &retcodes); if (ret < 0) return ret; ret = sysobj.omap().set(dpp, s, bl, y); if (ret < 0) return ret; m[s] = bl; } if (write_map) { bufferlist new_bl; encode(m, new_bl); ret = sysobj.wop().write(dpp, new_bl, y); if (ret < 0) { ldpp_dout(dpp, 0) << "WARNING: could not save avail pools map info ret=" << ret << dendl; } } auto miter = m.begin(); if (m.size() > 1) { // choose a pool at random auto r = ceph::util::generate_random_number<size_t>(0, m.size() - 1); std::advance(miter, r); } pool_name = miter->first; rgw_pool pool = pool_name; rule_info->storage_classes.set_storage_class(RGW_STORAGE_CLASS_STANDARD, &pool, nullptr); rule_info->data_extra_pool = pool_name; rule_info->index_pool = pool_name; rule_info->index_type = rgw::BucketIndexType::Normal; return 0; } int RGWSI_Zone::update_placement_map(const DoutPrefixProvider *dpp, optional_yield y) { bufferlist header; map<string, bufferlist> m; rgw_raw_obj obj(zone_params->domain_root, avail_pools); auto sysobj = sysobj_svc->get_obj(obj); int ret = sysobj.omap().get_all(dpp, &m, y); if (ret < 0) return ret; bufferlist new_bl; encode(m, new_bl); ret = sysobj.wop().write(dpp, new_bl, y); if (ret < 0) { ldpp_dout(dpp, 0) << "WARNING: could not save avail pools map info ret=" << ret << dendl; } return ret; } int RGWSI_Zone::add_bucket_placement(const DoutPrefixProvider *dpp, const rgw_pool& new_pool, optional_yield y) { int ret = rados_svc->pool(new_pool).lookup(); if (ret < 0) { // DNE, or something return ret; } rgw_raw_obj obj(zone_params->domain_root, avail_pools); auto sysobj = sysobj_svc->get_obj(obj); bufferlist empty_bl; ret = sysobj.omap().set(dpp, new_pool.to_str(), empty_bl, y); // don't care about return value update_placement_map(dpp, y); return ret; } int RGWSI_Zone::remove_bucket_placement(const DoutPrefixProvider *dpp, const rgw_pool& old_pool, optional_yield y) { rgw_raw_obj obj(zone_params->domain_root, avail_pools); auto sysobj = sysobj_svc->get_obj(obj); int ret = sysobj.omap().del(dpp, old_pool.to_str(), y); // don't care about return value update_placement_map(dpp, y); return ret; } int RGWSI_Zone::list_placement_set(const DoutPrefixProvider *dpp, set<rgw_pool>& names, optional_yield y) { bufferlist header; map<string, bufferlist> m; rgw_raw_obj obj(zone_params->domain_root, avail_pools); auto sysobj = sysobj_svc->get_obj(obj); int ret = sysobj.omap().get_all(dpp, &m, y); if (ret < 0) return ret; names.clear(); map<string, bufferlist>::iterator miter; for (miter = m.begin(); miter != m.end(); ++miter) { names.insert(rgw_pool(miter->first)); } return names.size(); } bool RGWSI_Zone::get_redirect_zone_endpoint(string *endpoint) { if (zone_public_config->redirect_zone.empty()) { return false; } auto iter = zone_conn_map.find(zone_public_config->redirect_zone); if (iter == zone_conn_map.end()) { ldout(cct, 0) << "ERROR: cannot find entry for redirect zone: " << zone_public_config->redirect_zone << dendl; return false; } RGWRESTConn *conn = iter->second; int ret = conn->get_url(*endpoint); if (ret < 0) { ldout(cct, 0) << "ERROR: redirect zone, conn->get_endpoint() returned ret=" << ret << dendl; return false; } return true; }
34,371
30.650092
173
cc
null
ceph-main/src/rgw/services/svc_zone.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_service.h" class RGWSI_RADOS; class RGWSI_SysObj; class RGWSI_SyncModules; class RGWSI_Bucket_Sync; class RGWRealm; class RGWZoneGroup; class RGWZone; class RGWZoneParams; class RGWPeriod; class RGWZonePlacementInfo; class RGWBucketSyncPolicyHandler; class RGWRESTConn; struct rgw_sync_policy_info; class RGWSI_Zone : public RGWServiceInstance { friend struct RGWServices_Def; RGWSI_SysObj *sysobj_svc{nullptr}; RGWSI_RADOS *rados_svc{nullptr}; RGWSI_SyncModules *sync_modules_svc{nullptr}; RGWSI_Bucket_Sync *bucket_sync_svc{nullptr}; RGWRealm *realm{nullptr}; RGWZoneGroup *zonegroup{nullptr}; RGWZone *zone_public_config{nullptr}; /* external zone params, e.g., entrypoints, log flags, etc. */ RGWZoneParams *zone_params{nullptr}; /* internal zone params, e.g., rados pools */ RGWPeriod *current_period{nullptr}; rgw_zone_id cur_zone_id; uint32_t zone_short_id{0}; bool writeable_zone{false}; bool exports_data{false}; std::shared_ptr<RGWBucketSyncPolicyHandler> sync_policy_handler; std::map<rgw_zone_id, std::shared_ptr<RGWBucketSyncPolicyHandler> > sync_policy_handlers; RGWRESTConn *rest_master_conn{nullptr}; std::map<rgw_zone_id, RGWRESTConn *> zone_conn_map; std::vector<const RGWZone*> data_sync_source_zones; std::map<rgw_zone_id, RGWRESTConn *> zone_data_notify_to_map; std::map<std::string, RGWRESTConn *> zonegroup_conn_map; std::map<std::string, rgw_zone_id> zone_id_by_name; std::map<rgw_zone_id, RGWZone> zone_by_id; std::unique_ptr<rgw_sync_policy_info> sync_policy; void init(RGWSI_SysObj *_sysobj_svc, RGWSI_RADOS *_rados_svc, RGWSI_SyncModules *_sync_modules_svc, RGWSI_Bucket_Sync *_bucket_sync_svc); int do_start(optional_yield y, const DoutPrefixProvider *dpp) override; void shutdown() override; int init_zg_from_period(const DoutPrefixProvider *dpp, optional_yield y); int init_zg_from_local(const DoutPrefixProvider *dpp, optional_yield y); int update_placement_map(const DoutPrefixProvider *dpp, optional_yield y); int create_default_zg(const DoutPrefixProvider *dpp, optional_yield y); int init_default_zone(const DoutPrefixProvider *dpp, optional_yield y); int search_realm_with_zone(const DoutPrefixProvider *dpp, const rgw_zone_id& zid, RGWRealm *prealm, RGWPeriod *pperiod, RGWZoneGroup *pzonegroup, bool *pfound, optional_yield y); public: RGWSI_Zone(CephContext *cct); ~RGWSI_Zone(); const RGWZoneParams& get_zone_params() const; const RGWPeriod& get_current_period() const; const RGWRealm& get_realm() const; const RGWZoneGroup& get_zonegroup() const; int get_zonegroup(const std::string& id, RGWZoneGroup& zonegroup) const; const RGWZone& get_zone() const; std::shared_ptr<RGWBucketSyncPolicyHandler> get_sync_policy_handler(std::optional<rgw_zone_id> zone = std::nullopt) const; const std::string& zone_name() const; const rgw_zone_id& zone_id() const { return cur_zone_id; } uint32_t get_zone_short_id() const; const std::string& get_current_period_id() const; bool has_zonegroup_api(const std::string& api) const; bool zone_is_writeable(); bool zone_syncs_from(const RGWZone& target_zone, const RGWZone& source_zone) const; bool get_redirect_zone_endpoint(std::string *endpoint); bool sync_module_supports_writes() const { return writeable_zone; } bool sync_module_exports_data() const { return exports_data; } RGWRESTConn *get_master_conn() { return rest_master_conn; } std::map<std::string, RGWRESTConn *>& get_zonegroup_conn_map() { return zonegroup_conn_map; } std::map<rgw_zone_id, RGWRESTConn *>& get_zone_conn_map() { return zone_conn_map; } std::vector<const RGWZone*>& get_data_sync_source_zones() { return data_sync_source_zones; } std::map<rgw_zone_id, RGWRESTConn *>& get_zone_data_notify_to_map() { return zone_data_notify_to_map; } RGWZone* find_zone(const rgw_zone_id& id); RGWRESTConn *get_zone_conn(const rgw_zone_id& zone_id); RGWRESTConn *get_zone_conn_by_name(const std::string& name); bool find_zone_id_by_name(const std::string& name, rgw_zone_id *id); int select_bucket_placement(const DoutPrefixProvider *dpp, const RGWUserInfo& user_info, const std::string& zonegroup_id, const rgw_placement_rule& rule, rgw_placement_rule *pselected_rule, RGWZonePlacementInfo *rule_info, optional_yield y); int select_legacy_bucket_placement(const DoutPrefixProvider *dpp, RGWZonePlacementInfo *rule_info, optional_yield y); int select_new_bucket_location(const DoutPrefixProvider *dpp, const RGWUserInfo& user_info, const std::string& zonegroup_id, const rgw_placement_rule& rule, rgw_placement_rule *pselected_rule_name, RGWZonePlacementInfo *rule_info, optional_yield y); int select_bucket_location_by_rule(const DoutPrefixProvider *dpp, const rgw_placement_rule& location_rule, RGWZonePlacementInfo *rule_info, optional_yield y); int add_bucket_placement(const DoutPrefixProvider *dpp, const rgw_pool& new_pool, optional_yield y); int remove_bucket_placement(const DoutPrefixProvider *dpp, const rgw_pool& old_pool, optional_yield y); int list_placement_set(const DoutPrefixProvider *dpp, std::set<rgw_pool>& names, optional_yield y); bool is_meta_master() const; bool need_to_sync() const; bool need_to_log_data() const; bool need_to_log_metadata() const; bool can_reshard() const; bool is_syncing_bucket_meta(const rgw_bucket& bucket); int list_zonegroups(const DoutPrefixProvider *dpp, std::list<std::string>& zonegroups); int list_regions(const DoutPrefixProvider *dpp, std::list<std::string>& regions); int list_zones(const DoutPrefixProvider *dpp, std::list<std::string>& zones); int list_realms(const DoutPrefixProvider *dpp, std::list<std::string>& realms); int list_periods(const DoutPrefixProvider *dpp, std::list<std::string>& periods); int list_periods(const DoutPrefixProvider *dpp, const std::string& current_period, std::list<std::string>& periods, optional_yield y); };
6,428
37.963636
160
h
null
ceph-main/src/rgw/services/svc_zone_utils.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "svc_zone_utils.h" #include "svc_rados.h" #include "svc_zone.h" #include "rgw_zone.h" using namespace std; int RGWSI_ZoneUtils::do_start(optional_yield, const DoutPrefixProvider *dpp) { init_unique_trans_id_deps(); return 0; } string RGWSI_ZoneUtils::gen_host_id() { /* uint64_t needs 16, two '-' separators and a trailing null */ const string& zone_name = zone_svc->get_zone().name; const string& zonegroup_name = zone_svc->get_zonegroup().get_name(); char charbuf[16 + zone_name.size() + zonegroup_name.size() + 2 + 1]; snprintf(charbuf, sizeof(charbuf), "%llx-%s-%s", (unsigned long long)rados_svc->instance_id(), zone_name.c_str(), zonegroup_name.c_str()); return string(charbuf); } string RGWSI_ZoneUtils::unique_id(uint64_t unique_num) { char buf[32]; snprintf(buf, sizeof(buf), ".%llu.%llu", (unsigned long long)rados_svc->instance_id(), (unsigned long long)unique_num); string s = zone_svc->get_zone_params().get_id() + buf; return s; } void RGWSI_ZoneUtils::init_unique_trans_id_deps() { char buf[16 + 2 + 1]; /* uint64_t needs 16, 2 hyphens add further 2 */ snprintf(buf, sizeof(buf), "-%llx-", (unsigned long long)rados_svc->instance_id()); url_encode(string(buf) + zone_svc->get_zone().name, trans_id_suffix); } /* In order to preserve compatibility with Swift API, transaction ID * should contain at least 32 characters satisfying following spec: * - first 21 chars must be in range [0-9a-f]. Swift uses this * space for storing fragment of UUID obtained through a call to * uuid4() function of Python's uuid module; * - char no. 22 must be a hyphen; * - at least 10 next characters constitute hex-formatted timestamp * padded with zeroes if necessary. All bytes must be in [0-9a-f] * range; * - last, optional part of transaction ID is any url-encoded string * without restriction on length. */ string RGWSI_ZoneUtils::unique_trans_id(const uint64_t unique_num) { char buf[41]; /* 2 + 21 + 1 + 16 (timestamp can consume up to 16) + 1 */ time_t timestamp = time(NULL); snprintf(buf, sizeof(buf), "tx%021llx-%010llx", (unsigned long long)unique_num, (unsigned long long)timestamp); return string(buf) + trans_id_suffix; }
2,350
35.169231
140
cc
null
ceph-main/src/rgw/services/svc_zone_utils.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_service.h" class RGWSI_RADOS; class RGWSI_Zone; class RGWSI_ZoneUtils : public RGWServiceInstance { friend struct RGWServices_Def; RGWSI_RADOS *rados_svc{nullptr}; RGWSI_Zone *zone_svc{nullptr}; std::string trans_id_suffix; void init(RGWSI_RADOS *_rados_svc, RGWSI_Zone *_zone_svc) { rados_svc = _rados_svc; zone_svc = _zone_svc; } int do_start(optional_yield, const DoutPrefixProvider *dpp) override; void init_unique_trans_id_deps(); public: RGWSI_ZoneUtils(CephContext *cct): RGWServiceInstance(cct) {} std::string gen_host_id(); std::string unique_id(uint64_t unique_num); std::string unique_trans_id(const uint64_t unique_num); };
825
20.179487
71
h
null
ceph-main/src/script/add_osd.sh
#!/usr/bin/env bash set -ex CEPH_DEV_DIR=dev CEPH_BIN=bin ceph_adm=$CEPH_BIN/ceph osd=$1 location=$2 weight=.0990 # DANGEROUS rm -rf $CEPH_DEV_DIR/osd$osd mkdir -p $CEPH_DEV_DIR/osd$osd uuid=`uuidgen` echo "add osd$osd $uuid" OSD_SECRET=$($CEPH_BIN/ceph-authtool --gen-print-key) echo "{\"cephx_secret\": \"$OSD_SECRET\"}" > $CEPH_DEV_DIR/osd$osd/new.json $CEPH_BIN/ceph osd new $uuid -i $CEPH_DEV_DIR/osd$osd/new.json rm $CEPH_DEV_DIR/osd$osd/new.json $CEPH_BIN/ceph-osd -i $osd $ARGS --mkfs --key $OSD_SECRET --osd-uuid $uuid key_fn=$CEPH_DEV_DIR/osd$osd/keyring cat > $key_fn<<EOF [osd.$osd] key = $OSD_SECRET EOF echo adding osd$osd key to auth repository $CEPH_BIN/ceph -i "$key_fn" auth add osd.$osd osd "allow *" mon "allow profile osd" mgr "allow profile osd" $CEPH_BIN/ceph osd crush add osd.$osd $weight $location echo start osd.$osd $CEPH_BIN/ceph-osd -i $osd $ARGS $COSD_ARGS
896
23.916667
107
sh
null
ceph-main/src/script/ceph-backport.sh
#!/usr/bin/env bash set -e # # ceph-backport.sh - Ceph backporting script # # Credits: This script is based on work done by Loic Dachary # # # This script automates the process of staging a backport starting from a # Backport tracker issue. # # Setup: # # ceph-backport.sh --setup # # Usage and troubleshooting: # # ceph-backport.sh --help # ceph-backport.sh --usage | less # ceph-backport.sh --troubleshooting | less # full_path="$0" SCRIPT_VERSION="16.0.0.6848" active_milestones="" backport_pr_labels="" backport_pr_number="" backport_pr_title="" backport_pr_url="" deprecated_backport_common="$HOME/bin/backport_common.sh" existing_pr_milestone_number="" github_token="" github_token_file="$HOME/.github_token" github_user="" milestone="" non_interactive="" original_issue="" original_issue_url="" original_pr="" original_pr_url="" redmine_key="" redmine_key_file="$HOME/.redmine_key" redmine_login="" redmine_user_id="" setup_ok="" this_script=$(basename "$full_path") if [[ $* == *--debug* ]]; then set -x fi # associative array keyed on "component" strings from PR titles, mapping them to # GitHub PR labels that make sense in backports declare -A comp_hash=( ["auth"]="core" ["bluestore"]="bluestore" ["build/ops"]="build/ops" ["ceph.spec"]="build/ops" ["ceph-volume"]="ceph-volume" ["cephadm"]="cephadm" ["cephfs"]="cephfs" ["cmake"]="build/ops" ["config"]="config" ["client"]="cephfs" ["common"]="common" ["core"]="core" ["dashboard"]="dashboard" ["deb"]="build/ops" ["doc"]="documentation" ["grafana"]="monitoring" ["mds"]="cephfs" ["messenger"]="core" ["mon"]="core" ["msg"]="core" ["mgr/cephadm"]="cephadm" ["mgr/dashboard"]="dashboard" ["mgr/prometheus"]="monitoring" ["mgr"]="core" ["monitoring"]="monitoring" ["orch"]="orchestrator" ["osd"]="core" ["perf"]="performance" ["prometheus"]="monitoring" ["pybind"]="pybind" ["py3"]="python3" ["python3"]="python3" ["qa"]="tests" ["rbd"]="rbd" ["rgw"]="rgw" ["rpm"]="build/ops" ["tests"]="tests" ["tool"]="tools" ) declare -A flagged_pr_hash=() function abort_due_to_setup_problem { error "problem detected in your setup" info "Run \"${this_script} --setup\" to fix" false } function assert_fail { local message="$1" error "(internal error) $message" info "This could be reported as a bug!" false } function backport_pr_needs_label { local check_label="$1" local label local needs_label="yes" while read -r label ; do if [ "$label" = "$check_label" ] ; then needs_label="" fi done <<< "$backport_pr_labels" echo "$needs_label" } function backport_pr_needs_milestone { if [ "$existing_pr_milestone_number" ] ; then echo "" else echo "yes" fi } function bail_out_github_api { local api_said="$1" local hint="$2" info "GitHub API said:" log bare "$api_said" if [ "$hint" ] ; then info "(hint) $hint" fi abort_due_to_setup_problem } function blindly_set_pr_metadata { local pr_number="$1" local json_blob="$2" curl -u ${github_user}:${github_token} --silent --data-binary "$json_blob" "https://api.github.com/repos/ceph/ceph/issues/${pr_number}" >/dev/null 2>&1 || true } function check_milestones { local milestones_to_check milestones_to_check="$(echo "$1" | tr '\n' ' ' | xargs)" info "Active milestones: $milestones_to_check" for m in $milestones_to_check ; do info "Examining all PRs targeting base branch \"$m\"" vet_prs_for_milestone "$m" done dump_flagged_prs } function check_tracker_status { local -a ok_statuses=("new" "need more info") local ts="$1" local error_msg local tslc="${ts,,}" local tslc_is_ok= for oks in "${ok_statuses[@]}"; do if [ "$tslc" = "$oks" ] ; then debug "Tracker status $ts is OK for backport to proceed" tslc_is_ok="yes" break fi done if [ "$tslc_is_ok" ] ; then true else if [ "$tslc" = "in progress" ] ; then error_msg="backport $redmine_url is already in progress" else error_msg="backport $redmine_url is closed (status: ${ts})" fi if [ "$FORCE" ] || [ "$EXISTING_PR" ] ; then warning "$error_msg" else error "$error_msg" fi fi echo "$tslc_is_ok" } function cherry_pick_phase { local base_branch local default_val local i local merged local number_of_commits local offset local sha1_to_cherry_pick local singular_or_plural_commit local yes_or_no_answer populate_original_issue if [ -z "$original_issue" ] ; then error "Could not find original issue" info "Does ${redmine_url} have a \"Copied from\" relation?" false fi info "Parent issue: ${original_issue_url}" populate_original_pr if [ -z "$original_pr" ]; then error "Could not find original PR" info "Is the \"Pull request ID\" field of ${original_issue_url} populated?" false fi info "Parent issue ostensibly fixed by: ${original_pr_url}" verbose "Examining ${original_pr_url}" remote_api_output=$(curl -u ${github_user}:${github_token} --silent "https://api.github.com/repos/ceph/ceph/pulls/${original_pr}") base_branch=$(echo "${remote_api_output}" | jq -r '.base.label') if [ "$base_branch" = "ceph:master" -o "$base_branch" = "ceph:main" ] ; then true else if [ "$FORCE" ] ; then warning "base_branch ->$base_branch<- is something other than \"ceph:master\" or \"ceph:main\"" info "--force was given, so continuing anyway" else error "${original_pr_url} is targeting ${base_branch}: cowardly refusing to perform automated cherry-pick" info "Out of an abundance of caution, the script only automates cherry-picking of commits from PRs targeting \"ceph:master\" or \"ceph:main\"." info "You can still use the script to stage the backport, though. Just prepare the local branch \"${local_branch}\" manually and re-run the script." false fi fi merged=$(echo "${remote_api_output}" | jq -r '.merged') if [ "$merged" = "true" ] ; then true else if [ "$FORCE" ] ; then warning "${original_pr_url} is not merged yet" info "--force was given, so continuing anyway" else error "${original_pr_url} is not merged yet" info "Cowardly refusing to perform automated cherry-pick" false fi fi number_of_commits=$(echo "${remote_api_output}" | jq '.commits') if [ "$number_of_commits" -eq "$number_of_commits" ] 2>/dev/null ; then # \$number_of_commits is set, and is an integer if [ "$number_of_commits" -eq "1" ] ; then singular_or_plural_commit="commit" else singular_or_plural_commit="commits" fi else error "Could not determine the number of commits in ${original_pr_url}" bail_out_github_api "$remote_api_output" fi info "Found $number_of_commits $singular_or_plural_commit in $original_pr_url" set -x git fetch "$upstream_remote" if git show-ref --verify --quiet "refs/heads/$local_branch" ; then if [ "$FORCE" ] ; then if [ "$non_interactive" ] ; then git checkout "$local_branch" git reset --hard "${upstream_remote}/${milestone}" else echo echo "A local branch $local_branch already exists and the --force option was given." echo "If you continue, any local changes in $local_branch will be lost!" echo default_val="y" echo -n "Do you really want to overwrite ${local_branch}? (default: ${default_val}) " yes_or_no_answer="$(get_user_input "$default_val")" [ "$yes_or_no_answer" ] && yes_or_no_answer="${yes_or_no_answer:0:1}" if [ "$yes_or_no_answer" = "y" ] ; then git checkout "$local_branch" git reset --hard "${upstream_remote}/${milestone}" else info "OK, bailing out!" false fi fi else set +x maybe_restore_set_x error "Cannot initialize $local_branch - local branch already exists" false fi else git checkout "${upstream_remote}/${milestone}" -b "$local_branch" fi git fetch "$upstream_remote" "pull/$original_pr/head:pr-$original_pr" set +x maybe_restore_set_x info "Attempting to cherry pick $number_of_commits commits from ${original_pr_url} into local branch $local_branch" offset="$((number_of_commits - 1))" || true for ((i=offset; i>=0; i--)) ; do info "Running \"git cherry-pick -x\" on $(git log --oneline --max-count=1 --no-decorate "pr-${original_pr}~${i}")" sha1_to_cherry_pick=$(git rev-parse --verify "pr-${original_pr}~${i}") set -x if git cherry-pick -x "$sha1_to_cherry_pick" ; then set +x maybe_restore_set_x else set +x maybe_restore_set_x [ "$VERBOSE" ] && git status error "Cherry pick failed" info "Next, manually fix conflicts and complete the current cherry-pick" if [ "$i" -gt "0" ] >/dev/null 2>&1 ; then info "Then, cherry-pick the remaining commits from ${original_pr_url}, i.e.:" for ((j=i-1; j>=0; j--)) ; do info "-> missing commit: $(git log --oneline --max-count=1 --no-decorate "pr-${original_pr}~${j}")" done info "Finally, re-run the script" else info "Then re-run the script" fi false fi done info "Cherry picking completed without conflicts" } function clear_line { log overwrite " \r" } function clip_pr_body { local pr_body="$*" local clipped="" local last_line_was_blank="" local line="" local pr_json_tempfile=$(mktemp) echo "$pr_body" | sed -n '/<!--.*/q;p' > "$pr_json_tempfile" while IFS= read -r line; do if [ "$(trim_whitespace "$line")" ] ; then last_line_was_blank="" clipped="${clipped}${line}\n" else if [ "$last_line_was_blank" ] ; then true else clipped="${clipped}\n" fi fi done < "$pr_json_tempfile" rm "$pr_json_tempfile" echo "$clipped" } function debug { log debug "$@" } function display_version_message_and_exit { echo "$this_script: Ceph backporting script, version $SCRIPT_VERSION" exit 0 } function dump_flagged_prs { local url= clear_line if [ "${#flagged_pr_hash[@]}" -eq "0" ] ; then info "All backport PRs appear to have milestone set correctly" else warning "Some backport PRs had problematic milestone settings" log bare "===========" log bare "Flagged PRs" log bare "-----------" for url in "${!flagged_pr_hash[@]}" ; do log bare "$url - ${flagged_pr_hash[$url]}" done log bare "===========" fi } function eol { local mtt="$1" error "$mtt is EOL" false } function error { log error "$@" } function existing_pr_routine { local base_branch local clipped_pr_body local new_pr_body local new_pr_title local pr_body local pr_json_tempfile local remote_api_output local update_pr_body remote_api_output="$(curl -u ${github_user}:${github_token} --silent "https://api.github.com/repos/ceph/ceph/pulls/${backport_pr_number}")" backport_pr_title="$(echo "$remote_api_output" | jq -r '.title')" if [ "$backport_pr_title" = "null" ] ; then error "could not get PR title of existing PR ${backport_pr_number}" bail_out_github_api "$remote_api_output" fi existing_pr_milestone_number="$(echo "$remote_api_output" | jq -r '.milestone.number')" if [ "$existing_pr_milestone_number" = "null" ] ; then existing_pr_milestone_number="" fi backport_pr_labels="$(echo "$remote_api_output" | jq -r '.labels[].name')" pr_body="$(echo "$remote_api_output" | jq -r '.body')" if [ "$pr_body" = "null" ] ; then error "could not get PR body of existing PR ${backport_pr_number}" bail_out_github_api "$remote_api_output" fi base_branch=$(echo "${remote_api_output}" | jq -r '.base.label') base_branch="${base_branch#ceph:}" if [ -z "$(is_active_milestone "$base_branch")" ] ; then error "existing PR $backport_pr_url is targeting $base_branch which is not an active milestone" info "Cowardly refusing to work on a backport to $base_branch" false fi clipped_pr_body="$(clip_pr_body "$pr_body")" verbose_en "Clipped body of existing PR ${backport_pr_number}:\n${clipped_pr_body}" if [[ "$backport_pr_title" =~ ^${milestone}: ]] ; then verbose "Existing backport PR ${backport_pr_number} title has ${milestone} prepended" else warning "Existing backport PR ${backport_pr_number} title does NOT have ${milestone} prepended" new_pr_title="${milestone}: $backport_pr_title" if [[ "$new_pr_title" =~ \" ]] ; then new_pr_title="${new_pr_title//\"/\\\"}" fi verbose "New PR title: ${new_pr_title}" fi redmine_url_without_scheme="${redmine_url//http?:\/\//}" verbose "Redmine URL without scheme: $redmine_url_without_scheme" if [[ "$clipped_pr_body" =~ $redmine_url_without_scheme ]] ; then info "Existing backport PR ${backport_pr_number} already mentions $redmine_url" if [ "$FORCE" ] ; then warning "--force was given, so updating the PR body anyway" update_pr_body="yes" fi else warning "Existing backport PR ${backport_pr_number} does NOT mention $redmine_url - adding it" update_pr_body="yes" fi if [ "$update_pr_body" ] ; then new_pr_body="backport tracker: ${redmine_url}" if [ "${original_pr_url}" ] ; then new_pr_body="${new_pr_body} possibly a backport of ${original_pr_url}" fi if [ "${original_issue_url}" ] ; then new_pr_body="${new_pr_body} parent tracker: ${original_issue_url}" fi new_pr_body="${new_pr_body} --- original PR body: $clipped_pr_body --- updated using ceph-backport.sh version ${SCRIPT_VERSION}" fi maybe_update_pr_title_body "${new_pr_title}" "${new_pr_body}" } function failed_mandatory_var_check { local varname="$1" local error="$2" verbose "$varname $error" setup_ok="" } function flag_pr { local pr_num="$1" local pr_url="$2" local flag_reason="$3" warning "flagging PR#${pr_num} because $flag_reason" flagged_pr_hash["${pr_url}"]="$flag_reason" } function from_file { local what="$1" xargs 2>/dev/null < "$HOME/.${what}" || true } function get_user_input { local default_val="$1" local user_input= read -r user_input if [ "$user_input" ] ; then echo "$user_input" else echo "$default_val" fi } # takes a string and a substring - returns position of substring within string, # or -1 if not found # NOTE: position of first character in string is 0 function grep_for_substr { local str="$1" local look_for_in_str="$2" str="${str,,}" munged="${str%%${look_for_in_str}*}" if [ "$munged" = "$str" ] ; then echo "-1" else echo "${#munged}" fi } # takes PR title, attempts to guess component function guess_component { local comp= local pos="0" local pr_title="$1" local winning_comp= local winning_comp_pos="9999" for comp in "${!comp_hash[@]}" ; do pos=$(grep_for_substr "$pr_title" "$comp") # echo "$comp: $pos" [ "$pos" = "-1" ] && continue if [ "$pos" -lt "$winning_comp_pos" ] ; then winning_comp_pos="$pos" winning_comp="$comp" fi done [ "$winning_comp" ] && echo "${comp_hash["$winning_comp"]}" || echo "" } function info { log info "$@" } function init_endpoints { verbose "Initializing remote API endpoints" redmine_endpoint="${redmine_endpoint:-"https://tracker.ceph.com"}" github_endpoint="${github_endpoint:-"https://github.com/ceph/ceph"}" } function init_fork_remote { [ "$github_user" ] || assert_fail "github_user not set" [ "$EXPLICIT_FORK" ] && info "Using explicit fork ->$EXPLICIT_FORK<- instead of personal fork." fork_remote="${fork_remote:-$(maybe_deduce_remote fork)}" } function init_github_token { github_token="$(from_file github_token)" if [ "$github_token" ] ; then true else warning "$github_token_file not populated: initiating interactive setup routine" INTERACTIVE_SETUP_ROUTINE="yes" fi } function init_redmine_key { redmine_key="$(from_file redmine_key)" if [ "$redmine_key" ] ; then true else warning "$redmine_key_file not populated: initiating interactive setup routine" INTERACTIVE_SETUP_ROUTINE="yes" fi } function init_upstream_remote { upstream_remote="${upstream_remote:-$(maybe_deduce_remote upstream)}" } function interactive_setup_routine { local default_val local original_github_token local original_redmine_key local total_steps local yes_or_no_answer original_github_token="$github_token" original_redmine_key="$redmine_key" total_steps="4" if [ -e "$deprecated_backport_common" ] ; then github_token="" redmine_key="" # shellcheck disable=SC1090 source "$deprecated_backport_common" 2>/dev/null || true total_steps="$((total_steps+1))" fi echo echo "Welcome to the ${this_script} interactive setup routine!" echo echo "---------------------------------------------------------------------" echo "Setup step 1 of $total_steps - GitHub token" echo "---------------------------------------------------------------------" echo "For information on how to generate a GitHub personal access token" echo "to use with this script, go to https://github.com/settings/tokens" echo "then click on \"Generate new token\" and make sure the token has" echo "\"Full control of private repositories\" scope." echo echo "For more details, see:" echo "https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line" echo echo -n "What is your GitHub token? " default_val="$github_token" [ "$github_token" ] && echo "(default: ${default_val})" github_token="$(get_user_input "$default_val")" if [ "$github_token" ] ; then true else error "You must provide a valid GitHub personal access token" abort_due_to_setup_problem fi [ "$github_token" ] || assert_fail "github_token not set, even after completing Step 1 of interactive setup" echo echo "---------------------------------------------------------------------" echo "Setup step 2 of $total_steps - GitHub user" echo "---------------------------------------------------------------------" echo "The script will now attempt to determine your GitHub user (login)" echo "from the GitHub token provided in the previous step. If this is" echo "successful, there is a good chance that your GitHub token is OK." echo echo "Communicating with the GitHub API..." set_github_user_from_github_token [ "$github_user" ] || abort_due_to_setup_problem echo echo -n "Is the GitHub username (login) \"$github_user\" correct? " default_val="y" [ "$github_token" ] && echo "(default: ${default_val})" yes_or_no_answer="$(get_user_input "$default_val")" [ "$yes_or_no_answer" ] && yes_or_no_answer="${yes_or_no_answer:0:1}" if [ "$yes_or_no_answer" = "y" ] ; then if [ "$github_token" = "$original_github_token" ] ; then true else debug "GitHub personal access token changed" echo "$github_token" > "$github_token_file" chmod 0600 "$github_token_file" info "Wrote GitHub personal access token to $github_token_file" fi else error "GitHub user does not look right" abort_due_to_setup_problem fi [ "$github_token" ] || assert_fail "github_token not set, even after completing Steps 1 and 2 of interactive setup" [ "$github_user" ] || assert_fail "github_user not set, even after completing Steps 1 and 2 of interactive setup" echo echo "---------------------------------------------------------------------" echo "Setup step 3 of $total_steps - remote repos" echo "---------------------------------------------------------------------" echo "Searching \"git remote -v\" for remote repos" echo init_upstream_remote init_fork_remote vet_remotes echo "Upstream remote is \"$upstream_remote\"" echo "Fork remote is \"$fork_remote\"" [ "$setup_ok" ] || abort_due_to_setup_problem [ "$github_token" ] || assert_fail "github_token not set, even after completing Steps 1-3 of interactive setup" [ "$github_user" ] || assert_fail "github_user not set, even after completing Steps 1-3 of interactive setup" [ "$upstream_remote" ] || assert_fail "upstream_remote not set, even after completing Steps 1-3 of interactive setup" [ "$fork_remote" ] || assert_fail "fork_remote not set, even after completing Steps 1-3 of interactive setup" echo echo "---------------------------------------------------------------------" echo "Setup step 4 of $total_steps - Redmine key" echo "---------------------------------------------------------------------" echo "To generate a Redmine API access key, go to https://tracker.ceph.com" echo "After signing in, click: \"My account\"" echo "Now, find \"API access key\"." echo "Once you know the API access key, enter it below." echo echo -n "What is your Redmine key? " default_val="$redmine_key" [ "$redmine_key" ] && echo "(default: ${default_val})" redmine_key="$(get_user_input "$default_val")" if [ "$redmine_key" ] ; then set_redmine_user_from_redmine_key if [ "$setup_ok" ] ; then true else info "You must provide a valid Redmine API access key" abort_due_to_setup_problem fi if [ "$redmine_key" = "$original_redmine_key" ] ; then true else debug "Redmine API access key changed" echo "$redmine_key" > "$redmine_key_file" chmod 0600 "$redmine_key_file" info "Wrote Redmine API access key to $redmine_key_file" fi else error "You must provide a valid Redmine API access key" abort_due_to_setup_problem fi [ "$github_token" ] || assert_fail "github_token not set, even after completing Steps 1-4 of interactive setup" [ "$github_user" ] || assert_fail "github_user not set, even after completing Steps 1-4 of interactive setup" [ "$upstream_remote" ] || assert_fail "upstream_remote not set, even after completing Steps 1-4 of interactive setup" [ "$fork_remote" ] || assert_fail "fork_remote not set, even after completing Steps 1-4 of interactive setup" [ "$redmine_key" ] || assert_fail "redmine_key not set, even after completing Steps 1-4 of interactive setup" [ "$redmine_user_id" ] || assert_fail "redmine_user_id not set, even after completing Steps 1-4 of interactive setup" [ "$redmine_login" ] || assert_fail "redmine_login not set, even after completing Steps 1-4 of interactive setup" if [ "$total_steps" -gt "4" ] ; then echo echo "---------------------------------------------------------------------" echo "Step 5 of $total_steps - delete deprecated $deprecated_backport_common file" echo "---------------------------------------------------------------------" fi maybe_delete_deprecated_backport_common vet_setup --interactive } function is_active_milestone { local is_active= local milestone_under_test="$1" for m in $active_milestones ; do if [ "$milestone_under_test" = "$m" ] ; then verbose "Milestone $m is active" is_active="yes" break fi done echo "$is_active" } function log { local level="$1" local trailing_newline="yes" local in_hex="" shift local msg="$*" prefix="${this_script}: " verbose_only= case $level in bare) prefix= ;; debug) prefix="${prefix}DEBUG: " verbose_only="yes" ;; err*) prefix="${prefix}ERROR: " ;; hex) in_hex="yes" ;; info) : ;; overwrite) trailing_newline= prefix= ;; verbose) verbose_only="yes" ;; verbose_en) verbose_only="yes" trailing_newline= ;; warn|warning) prefix="${prefix}WARNING: " ;; esac if [ "$in_hex" ] ; then print_in_hex "$msg" elif [ "$verbose_only" ] && [ -z "$VERBOSE" ] ; then true else msg="${prefix}${msg}" if [ "$trailing_newline" ] ; then echo "${msg}" >&2 else echo -en "${msg}" >&2 fi fi } function maybe_deduce_remote { local remote_type="$1" local remote="" local url_component="" if [ "$remote_type" = "upstream" ] ; then url_component="ceph" elif [ "$remote_type" = "fork" ] ; then if [ "$EXPLICIT_FORK" ] ; then url_component="$EXPLICIT_FORK" else url_component="$github_user" fi else assert_fail "bad remote_type ->$remote_type<- in maybe_deduce_remote" fi remote=$(git remote -v | grep --extended-regexp --ignore-case '(://|@)github.com(/|:|:/)'${url_component}'/ceph(\s|\.|\/)' | head -n1 | cut -f 1) echo "$remote" } function maybe_delete_deprecated_backport_common { local default_val local user_inp if [ -e "$deprecated_backport_common" ] ; then echo "You still have a $deprecated_backport_common file," echo "which was used to store configuration parameters in version" echo "15.0.0.6270 and earlier versions of ${this_script}." echo echo "Since $deprecated_backport_common has been deprecated in favor" echo "of the interactive setup routine, which has been completed" echo "successfully, the file should be deleted now." echo echo -n "Delete it now? (default: y) " default_val="y" user_inp="$(get_user_input "$default_val")" user_inp="$(echo "$user_inp" | tr '[:upper:]' '[:lower:]' | xargs)" if [ "$user_inp" ] ; then user_inp="${user_inp:0:1}" if [ "$user_inp" = "y" ] ; then set -x rm -f "$deprecated_backport_common" set +x maybe_restore_set_x fi fi if [ -e "$deprecated_backport_common" ] ; then error "$deprecated_backport_common still exists. Bailing out!" false fi fi } function maybe_restore_set_x { if [ "$DEBUG" ] ; then set -x fi } function maybe_update_pr_milestone_labels { local component local data_binary local data_binary local label local needs_milestone if [ "$EXPLICIT_COMPONENT" ] ; then debug "Component given on command line: using it" component="$EXPLICIT_COMPONENT" else debug "Attempting to guess component" component=$(guess_component "$backport_pr_title") fi data_binary="{" needs_milestone="$(backport_pr_needs_milestone)" if [ "$needs_milestone" ] ; then debug "Attempting to set ${milestone} milestone in ${backport_pr_url}" data_binary="${data_binary}\"milestone\":${milestone_number}" else info "Backport PR ${backport_pr_url} already has ${milestone} milestone" fi if [ "$(backport_pr_needs_label "$component")" ] ; then debug "Attempting to add ${component} label to ${backport_pr_url}" if [ "$needs_milestone" ] ; then data_binary="${data_binary}," fi data_binary="${data_binary}\"labels\":[\"${component}\"" while read -r label ; do if [ "$label" ] ; then data_binary="${data_binary},\"${label}\"" fi done <<< "$backport_pr_labels" data_binary="${data_binary}]}" else info "Backport PR ${backport_pr_url} already has label ${component}" data_binary="${data_binary}}" fi if [ "$data_binary" = "{}" ] ; then true else blindly_set_pr_metadata "$backport_pr_number" "$data_binary" fi } function maybe_update_pr_title_body { local new_title="$1" local new_body="$2" local data_binary if [ "$new_title" ] && [ "$new_body" ] ; then data_binary="{\"title\":\"${new_title}\", \"body\":\"$(munge_body "${new_body}")\"}" elif [ "$new_title" ] ; then data_binary="{\"title\":\"${new_title}\"}" backport_pr_title="${new_title}" elif [ "$new_body" ] ; then data_binary="{\"body\":\"$(munge_body "${new_body}")\"}" #log hex "${data_binary}" #echo -n "${data_binary}" fi if [ "$data_binary" ] ; then blindly_set_pr_metadata "${backport_pr_number}" "$data_binary" fi } function milestone_number_from_remote_api { local mtt="$1" # milestone to try local mn="" # milestone number local milestones remote_api_output=$(curl -u ${github_user}:${github_token} --silent -X GET "https://api.github.com/repos/ceph/ceph/milestones") mn=$(echo "$remote_api_output" | jq --arg milestone "$mtt" '.[] | select(.title==$milestone) | .number') if [ "$mn" -gt "0" ] >/dev/null 2>&1 ; then echo "$mn" else error "Could not determine milestone number of ->$milestone<-" verbose_en "GitHub API said:\n${remote_api_output}\n" remote_api_output=$(curl -u ${github_user}:${github_token} --silent -X GET "https://api.github.com/repos/ceph/ceph/milestones") milestones=$(echo "$remote_api_output" | jq '.[].title') info "Valid values are ${milestones}" info "(This probably means the Release field of ${redmine_url} is populated with" info "an unexpected value - i.e. it does not match any of the GitHub milestones.)" false fi } function munge_body { echo "$new_body" | tr '\r' '\n' | sed 's/$/\\n/' | tr -d '\n' } function number_to_url { local number_type="$1" local number="$2" if [ "$number_type" = "github" ] ; then echo "${github_endpoint}/pull/${number}" elif [ "$number_type" = "redmine" ] ; then echo "${redmine_endpoint}/issues/${number}" else assert_fail "internal error in number_to_url: bad type ->$number_type<-" fi } function populate_original_issue { if [ -z "$original_issue" ] ; then original_issue=$(curl --silent "${redmine_url}.json?include=relations" | jq '.issue.relations[] | select(.relation_type | contains("copied_to")) | .issue_id') original_issue_url="$(number_to_url "redmine" "${original_issue}")" fi } function populate_original_pr { if [ "$original_issue" ] ; then if [ -z "$original_pr" ] ; then original_pr=$(curl --silent "${original_issue_url}.json" | jq -r '.issue.custom_fields[] | select(.id | contains(21)) | .value') original_pr_url="$(number_to_url "github" "${original_pr}")" fi fi } function print_in_hex { local str="$1" local c for (( i=0; i < ${#str}; i++ )) do c=${str:$i:1} if [[ $c == ' ' ]] then printf "[%s] 0x%X\n" " " \'\ \' >&2 else printf "[%s] 0x%X\n" "$c" \'"$c"\' >&2 fi done } function set_github_user_from_github_token { local quiet="$1" local api_error local curl_opts setup_ok="" [ "$github_token" ] || assert_fail "set_github_user_from_github_token: git_token not set" curl_opts="--silent -u :${github_token} https://api.github.com/user" [ "$quiet" ] || set -x remote_api_output="$(curl $curl_opts)" set +x github_user=$(echo "${remote_api_output}" | jq -r .login 2>/dev/null | grep -v null || true) api_error=$(echo "${remote_api_output}" | jq -r .message 2>/dev/null | grep -v null || true) if [ "$api_error" ] ; then info "GitHub API said: ->$api_error<-" info "If you can't figure out what's wrong by examining the curl command and its output, above," info "please also study https://developer.github.com/v3/users/#get-the-authenticated-user" github_user="" else [ "$github_user" ] || assert_fail "set_github_user_from_github_token: failed to set github_user" info "my GitHub username is $github_user" setup_ok="yes" fi } function set_redmine_user_from_redmine_key { [ "$redmine_key" ] || assert_fail "set_redmine_user_from_redmine_key was called, but redmine_key not set" local api_key_from_api remote_api_output="$(curl --silent "https://tracker.ceph.com/users/current.json?key=$redmine_key")" redmine_login="$(echo "$remote_api_output" | jq -r '.user.login')" redmine_user_id="$(echo "$remote_api_output" | jq -r '.user.id')" api_key_from_api="$(echo "$remote_api_output" | jq -r '.user.api_key')" if [ "$redmine_login" ] && [ "$redmine_user_id" ] && [ "$api_key_from_api" = "$redmine_key" ] ; then [ "$redmine_user_id" ] || assert_fail "set_redmine_user_from_redmine_key: failed to set redmine_user_id" [ "$redmine_login" ] || assert_fail "set_redmine_user_from_redmine_key: failed to set redmine_login" info "my Redmine username is $redmine_login (ID $redmine_user_id)" setup_ok="yes" else error "Redmine API access key $redmine_key is invalid" redmine_login="" redmine_user_id="" setup_ok="" fi } function tracker_component_is_in_desired_state { local comp="$1" local val_is="$2" local val_should_be="$3" local in_desired_state if [ "$val_is" = "$val_should_be" ] ; then debug "Tracker $comp is in the desired state" in_desired_state="yes" fi echo "$in_desired_state" } function tracker_component_was_updated { local comp="$1" local val_old="$2" local val_new="$3" local was_updated if [ "$val_old" = "$val_new" ] ; then true else debug "Tracker $comp was updated!" was_updated="yes" fi echo "$was_updated" } function trim_whitespace { local var="$*" # remove leading whitespace characters var="${var#"${var%%[![:space:]]*}"}" # remove trailing whitespace characters var="${var%"${var##*[![:space:]]}"}" echo -n "$var" } function troubleshooting_advice { cat <<EOM Troubleshooting notes --------------------- If the script inexplicably fails with: error: a cherry-pick or revert is already in progress hint: try "git cherry-pick (--continue | --quit | --abort)" fatal: cherry-pick failed This is because HEAD is not where git expects it to be: $ git cherry-pick --abort warning: You seem to have moved HEAD. Not rewinding, check your HEAD! This can be fixed by issuing the command: $ git cherry-pick --quit EOM } # to update known milestones, consult: # curl --verbose -X GET https://api.github.com/repos/ceph/ceph/milestones function try_known_milestones { local mtt=$1 # milestone to try local mn="" # milestone number case $mtt in cuttlefish) eol "$mtt" ;; dumpling) eol "$mtt" ;; emperor) eol "$mtt" ;; firefly) eol "$mtt" ;; giant) eol "$mtt" ;; hammer) eol "$mtt" ;; infernalis) eol "$mtt" ;; jewel) mn="8" ;; kraken) eol "$mtt" ;; luminous) mn="10" ;; mimic) mn="11" ;; nautilus) mn="12" ;; octopus) mn="13" ;; pacific) mn="14" ;; quincy) mn="15" ;; reef) mn="16" ;; esac echo "$mn" } function update_version_number_and_exit { set -x local raw_version local munge_first_hyphen # munge_first_hyphen will look like this: 15.0.0.5774-g4c2f2eda969 local script_version_number raw_version="$(git describe --long --match 'v*' | sed 's/^v//')" # example: "15.0.0-5774-g4c2f2eda969" munge_first_hyphen="${raw_version/-/.}" # example: "15.0.0.5774-g4c2f2eda969" script_version_number="${munge_first_hyphen%-*}" # example: "15.0.0.5774" sed -i -e "s/^SCRIPT_VERSION=.*/SCRIPT_VERSION=\"${script_version_number}\"/" "$full_path" exit 0 } function usage { cat <<EOM >&2 Setup: ${this_script} --setup Documentation: ${this_script} --help ${this_script} --usage | less ${this_script} --troubleshooting | less Usage: ${this_script} BACKPORT_TRACKER_ISSUE_NUMBER Options (not needed in normal operation): --cherry-pick-only (stop after cherry-pick phase) --component/-c COMPONENT (explicitly set the component label; if omitted, the script will try to guess the component) --debug (turns on "set -x") --existing-pr BACKPORT_PR_ID (use this when the backport PR is already open) --force (exercise caution!) --fork EXPLICIT_FORK (use EXPLICIT_FORK instead of personal GitHub fork) --milestones (vet all backport PRs for correct milestone setting) --setup/-s (run the interactive setup routine - NOTE: this can be done any number of times) --setup-report (check the setup and print a report) --update-version (this option exists as a convenience for the script maintainer only: not intended for day-to-day usage) --verbose/-v (produce more output than normal) --version (display version number and exit) Example: ${this_script} 31459 (if cherry-pick conflicts are present, finish cherry-picking phase manually and then run the script again with the same argument) CAVEAT: The script must be run from inside a local git clone. EOM } function usage_advice { cat <<EOM Usage advice ------------ Once you have completed --setup, you can run the script with the ID of a Backport tracker issue. For example, to stage the backport https://tracker.ceph.com/issues/41502, run: ${this_script} 41502 Provided the commits in the corresponding main PR cherry-pick cleanly, the script will automatically perform all steps required to stage the backport: Cherry-pick phase: 1. fetching the latest commits from the upstream remote 2. creating a wip branch for the backport 3. figuring out which upstream PR contains the commits to cherry-pick 4. cherry-picking the commits PR phase: 5. pushing the wip branch to your fork 6. opening the backport PR with compliant title and description describing the backport 7. (optionally) setting the milestone and label in the PR 8. updating the Backport tracker issue When run with --cherry-pick-only, the script will stop after the cherry-pick phase. If any of the commits do not cherry-pick cleanly, the script will abort in step 4. In this case, you can either finish the cherry-picking manually or abort the cherry-pick. In any case, when and if the local wip branch is ready (all commits cherry-picked), if you run the script again, like so: ${this_script} 41502 the script will detect that the wip branch already exists and skip over steps 1-4, starting from step 5 ("PR phase"). In other words, if the wip branch already exists for any reason, the script will assume that the cherry-pick phase (steps 1-4) is complete. As this implies, you can do steps 1-4 manually. Provided the wip branch name is in the format wip-\$TRACKER_ID-\$STABLE_RELEASE (e.g. "wip-41502-mimic"), the script will detect the wip branch and start from step 5. For details on all the options the script takes, run: ${this_script} --help For more information on Ceph backporting, see: https://github.com/ceph/ceph/tree/main/SubmittingPatches-backports.rst EOM } function verbose { log verbose "$@" } function verbose_en { log verbose_en "$@" } function vet_pr_milestone { local pr_number="$1" local pr_title="$2" local pr_url="$3" local milestone_stanza="$4" local milestone_title_should_be="$5" local milestone_number_should_be local milestone_number_is= local milestone_title_is= milestone_number_should_be="$(try_known_milestones "$milestone_title_should_be")" log overwrite "Vetting milestone of PR#${pr_number}\r" if [ "$milestone_stanza" = "null" ] ; then blindly_set_pr_metadata "$pr_number" "{\"milestone\": $milestone_number_should_be}" warning "$pr_url: set milestone to \"$milestone_title_should_be\"" flag_pr "$pr_number" "$pr_url" "milestone not set" else milestone_title_is=$(echo "$milestone_stanza" | jq -r '.title') milestone_number_is=$(echo "$milestone_stanza" | jq -r '.number') if [ "$milestone_number_is" -eq "$milestone_number_should_be" ] ; then true else blindly_set_pr_metadata "$pr_number" "{\"milestone\": $milestone_number_should_be}" warning "$pr_url: changed milestone from \"$milestone_title_is\" to \"$milestone_title_should_be\"" flag_pr "$pr_number" "$pr_url" "milestone set to wrong value \"$milestone_title_is\"" fi fi } function vet_prs_for_milestone { local milestone_title="$1" local pages_of_output= local pr_number= local pr_title= local pr_url= # determine last page (i.e., total number of pages) remote_api_output="$(curl -u ${github_user}:${github_token} --silent --head "https://api.github.com/repos/ceph/ceph/pulls?base=${milestone_title}" | grep -E '^Link' || true)" if [ "$remote_api_output" ] ; then # Link: <https://api.github.com/repositories/2310495/pulls?base=luminous&page=2>; rel="next", <https://api.github.com/repositories/2310495/pulls?base=luminous&page=2>; rel="last" # shellcheck disable=SC2001 pages_of_output="$(echo "$remote_api_output" | sed 's/^.*&page\=\([0-9]\+\)>; rel=\"last\".*$/\1/g')" else pages_of_output="1" fi verbose "GitHub has $pages_of_output pages of pull request data for \"base:${milestone_title}\"" for ((page=1; page<=pages_of_output; page++)) ; do verbose "Fetching PRs (page $page of ${pages_of_output})" remote_api_output="$(curl -u ${github_user}:${github_token} --silent -X GET "https://api.github.com/repos/ceph/ceph/pulls?base=${milestone_title}&page=${page}")" prs_in_page="$(echo "$remote_api_output" | jq -r '. | length')" verbose "Page $page of remote API output contains information on $prs_in_page PRs" for ((i=0; i<prs_in_page; i++)) ; do pr_number="$(echo "$remote_api_output" | jq -r ".[${i}].number")" pr_title="$(echo "$remote_api_output" | jq -r ".[${i}].title")" pr_url="$(number_to_url "github" "${pr_number}")" milestone_stanza="$(echo "$remote_api_output" | jq -r ".[${i}].milestone")" vet_pr_milestone "$pr_number" "$pr_title" "$pr_url" "$milestone_stanza" "$milestone_title" done clear_line done } function vet_remotes { if [ "$upstream_remote" ] ; then verbose "Upstream remote is $upstream_remote" else error "Cannot auto-determine upstream remote" "(Could not find any upstream remote in \"git remote -v\")" false fi if [ "$fork_remote" ] ; then verbose "Fork remote is $fork_remote" else error "Cannot auto-determine fork remote" if [ "$EXPLICIT_FORK" ] ; then info "(Could not find $EXPLICIT_FORK fork of ceph/ceph in \"git remote -v\")" else info "(Could not find GitHub user ${github_user}'s fork of ceph/ceph in \"git remote -v\")" fi setup_ok="" fi } function vet_setup { local argument="$1" local not_set="!!! NOT SET !!!" local invalid="!!! INVALID !!!" local redmine_endpoint_display local redmine_user_id_display local github_endpoint_display local github_user_display local upstream_remote_display local fork_remote_display local redmine_key_display local github_token_display debug "Entering vet_setup with argument $argument" if [ "$argument" = "--report" ] || [ "$argument" = "--normal-operation" ] ; then [ "$github_token" ] && [ "$setup_ok" ] && set_github_user_from_github_token quiet init_upstream_remote [ "$github_token" ] && [ "$setup_ok" ] && init_fork_remote vet_remotes [ "$redmine_key" ] && set_redmine_user_from_redmine_key fi if [ "$github_token" ] ; then if [ "$setup_ok" ] ; then github_token_display="(OK; value not shown)" else github_token_display="$invalid" fi else github_token_display="$not_set" fi if [ "$redmine_key" ] ; then if [ "$setup_ok" ] ; then redmine_key_display="(OK; value not shown)" else redmine_key_display="$invalid" fi else redmine_key_display="$not_set" fi redmine_endpoint_display="${redmine_endpoint:-$not_set}" redmine_user_id_display="${redmine_user_id:-$not_set}" github_endpoint_display="${github_endpoint:-$not_set}" github_user_display="${github_user:-$not_set}" upstream_remote_display="${upstream_remote:-$not_set}" fork_remote_display="${fork_remote:-$not_set}" test "$redmine_endpoint" || failed_mandatory_var_check redmine_endpoint "not set" test "$redmine_user_id" || failed_mandatory_var_check redmine_user_id "could not be determined" test "$redmine_key" || failed_mandatory_var_check redmine_key "not set" test "$github_endpoint" || failed_mandatory_var_check github_endpoint "not set" test "$github_user" || failed_mandatory_var_check github_user "could not be determined" test "$github_token" || failed_mandatory_var_check github_token "not set" test "$upstream_remote" || failed_mandatory_var_check upstream_remote "could not be determined" test "$fork_remote" || failed_mandatory_var_check fork_remote "could not be determined" if [ "$argument" = "--report" ] || [ "$argument" == "--interactive" ] ; then read -r -d '' setup_summary <<EOM || true > /dev/null 2>&1 redmine_endpoint $redmine_endpoint redmine_user_id $redmine_user_id_display redmine_key $redmine_key_display github_endpoint $github_endpoint github_user $github_user_display github_token $github_token_display upstream_remote $upstream_remote_display fork_remote $fork_remote_display EOM log bare log bare "=============================================" log bare " ${this_script} setup report" log bare "=============================================" log bare "variable name value" log bare "---------------------------------------------" log bare "$setup_summary" log bare "---------------------------------------------" else verbose "redmine_endpoint $redmine_endpoint_display" verbose "redmine_user_id $redmine_user_id_display" verbose "redmine_key $redmine_key_display" verbose "github_endpoint $github_endpoint_display" verbose "github_user $github_user_display" verbose "github_token $github_token_display" verbose "upstream_remote $upstream_remote_display" verbose "fork_remote $fork_remote_display" fi if [ "$argument" = "--report" ] || [ "$argument" = "--interactive" ] ; then if [ "$setup_ok" ] ; then info "setup is OK" else info "setup is NOT OK" fi log bare "==============================================" log bare fi } function warning { log warning "$@" } # # are we in a local git clone? # if git status >/dev/null 2>&1 ; then debug "In a local git clone. Good." else error "This script must be run from inside a local git clone" abort_due_to_setup_problem fi # # do we have jq available? # if type jq >/dev/null 2>&1 ; then debug "jq is available. Good." else error "This script uses jq, but it does not seem to be installed" abort_due_to_setup_problem fi # # is jq available? # if command -v jq >/dev/null ; then debug "jq is available. Good." else error "This script needs \"jq\" in order to work, and it is not available" abort_due_to_setup_problem fi # # process command-line arguments # munged_options=$(getopt -o c:dhsv --long "cherry-pick-only,component:,debug,existing-pr:,force,fork:,help,milestones,prepare,setup,setup-report,troubleshooting,update-version,usage,verbose,version" -n "$this_script" -- "$@") eval set -- "$munged_options" ADVICE="" CHECK_MILESTONES="" CHERRY_PICK_ONLY="" CHERRY_PICK_PHASE="yes" DEBUG="" EXISTING_PR="" EXPLICIT_COMPONENT="" EXPLICIT_FORK="" FORCE="" HELP="" INTERACTIVE_SETUP_ROUTINE="" ISSUE="" PR_PHASE="yes" SETUP_OPTION="" TRACKER_PHASE="yes" TROUBLESHOOTING_ADVICE="" USAGE_ADVICE="" VERBOSE="" while true ; do case "$1" in --cherry-pick-only) CHERRY_PICK_PHASE="yes" ; PR_PHASE="" ; TRACKER_PHASE="" ; shift ;; --component|-c) shift ; EXPLICIT_COMPONENT="$1" ; shift ;; --debug|-d) DEBUG="$1" ; shift ;; --existing-pr) shift ; EXISTING_PR="$1" ; CHERRY_PICK_PHASE="" ; PR_PHASE="" ; shift ;; --force) FORCE="$1" ; shift ;; --fork) shift ; EXPLICIT_FORK="$1" ; shift ;; --help|-h) ADVICE="1" ; HELP="$1" ; shift ;; --milestones) CHECK_MILESTONES="$1" ; shift ;; --prepare) CHERRY_PICK_PHASE="yes" ; PR_PHASE="" ; TRACKER_PHASE="" ; shift ;; --setup*|-s) SETUP_OPTION="$1" ; shift ;; --troubleshooting) ADVICE="$1" ; TROUBLESHOOTING_ADVICE="$1" ; shift ;; --update-version) update_version_number_and_exit ;; --usage) ADVICE="$1" ; USAGE_ADVICE="$1" ; shift ;; --verbose|-v) VERBOSE="$1" ; shift ;; --version) display_version_message_and_exit ;; --) shift ; ISSUE="$1" ; break ;; *) echo "Internal error" ; false ;; esac done if [ "$ADVICE" ] ; then [ "$HELP" ] && usage [ "$USAGE_ADVICE" ] && usage_advice [ "$TROUBLESHOOTING_ADVICE" ] && troubleshooting_advice exit 0 fi if [ "$SETUP_OPTION" ] || [ "$CHECK_MILESTONES" ] ; then ISSUE="0" fi if [[ $ISSUE =~ ^[0-9]+$ ]] ; then issue=$ISSUE else error "Invalid or missing argument" usage false fi if [ "$DEBUG" ]; then set -x VERBOSE="--verbose" fi if [ "$VERBOSE" ]; then info "Verbose mode ON" VERBOSE="--verbose" fi # # make sure setup has been completed # init_endpoints init_github_token init_redmine_key setup_ok="OK" if [ "$SETUP_OPTION" ] ; then vet_setup --report maybe_delete_deprecated_backport_common if [ "$setup_ok" ] ; then exit 0 else default_val="y" echo -n "Run the interactive setup routine now? (default: ${default_val}) " yes_or_no_answer="$(get_user_input "$default_val")" [ "$yes_or_no_answer" ] && yes_or_no_answer="${yes_or_no_answer:0:1}" if [ "$yes_or_no_answer" = "y" ] ; then INTERACTIVE_SETUP_ROUTINE="yes" else if [ "$FORCE" ] ; then warning "--force was given; proceeding with broken setup" else info "Bailing out!" exit 1 fi fi fi fi if [ "$INTERACTIVE_SETUP_ROUTINE" ] ; then interactive_setup_routine else vet_setup --normal-operation maybe_delete_deprecated_backport_common fi if [ "$INTERACTIVE_SETUP_ROUTINE" ] || [ "$SETUP_OPTION" ] ; then echo if [ "$setup_ok" ] ; then if [ "$ISSUE" ] && [ "$ISSUE" != "0" ] ; then true else exit 0 fi else exit 1 fi fi vet_remotes [ "$setup_ok" ] || abort_due_to_setup_problem # # query remote GitHub API for active milestones # verbose "Querying GitHub API for active milestones" remote_api_output="$(curl -u ${github_user}:${github_token} --silent -X GET "https://api.github.com/repos/ceph/ceph/milestones")" active_milestones="$(echo "$remote_api_output" | jq -r '.[] | .title')" if [ "$active_milestones" = "null" ] ; then error "Could not determine the active milestones" bail_out_github_api "$remote_api_output" fi if [ "$CHECK_MILESTONES" ] ; then check_milestones "$active_milestones" exit 0 fi # # query remote Redmine API for information about the Backport tracker issue # redmine_url="$(number_to_url "redmine" "${issue}")" debug "Considering Redmine issue: $redmine_url - is it in the Backport tracker?" remote_api_output="$(curl --silent "${redmine_url}.json")" tracker="$(echo "$remote_api_output" | jq -r '.issue.tracker.name')" if [ "$tracker" = "Backport" ]; then debug "Yes, $redmine_url is a Backport issue" else error "Issue $redmine_url is not a Backport" info "(This script only works with Backport tracker issues.)" false fi debug "Looking up release/milestone of $redmine_url" milestone="$(echo "$remote_api_output" | jq -r '.issue.custom_fields[0].value')" if [ "$milestone" ] ; then debug "Release/milestone: $milestone" else error "could not obtain release/milestone from ${redmine_url}" false fi debug "Looking up status of $redmine_url" tracker_status_id="$(echo "$remote_api_output" | jq -r '.issue.status.id')" tracker_status_name="$(echo "$remote_api_output" | jq -r '.issue.status.name')" if [ "$tracker_status_name" ] ; then debug "Tracker status: $tracker_status_name" if [ "$FORCE" ] || [ "$EXISTING_PR" ] ; then test "$(check_tracker_status "$tracker_status_name")" || true else test "$(check_tracker_status "$tracker_status_name")" fi else error "could not obtain status from ${redmine_url}" false fi tracker_title="$(echo "$remote_api_output" | jq -r '.issue.subject')" debug "Title of $redmine_url is ->$tracker_title<-" tracker_description="$(echo "$remote_api_output" | jq -r '.issue.description')" debug "Description of $redmine_url is ->$tracker_description<-" tracker_assignee_id="$(echo "$remote_api_output" | jq -r '.issue.assigned_to.id')" tracker_assignee_name="$(echo "$remote_api_output" | jq -r '.issue.assigned_to.name')" if [ "$tracker_assignee_id" = "null" ] || [ "$tracker_assignee_id" = "$redmine_user_id" ] ; then true else error_msg_1="$redmine_url is assigned to someone else: $tracker_assignee_name (ID $tracker_assignee_id)" error_msg_2="(my ID is $redmine_user_id)" if [ "$FORCE" ] || [ "$EXISTING_PR" ] ; then warning "$error_msg_1" info "$error_msg_2" info "--force and/or --existing-pr given: continuing execution" else error "$error_msg_1" info "$error_msg_2" info "Cowardly refusing to continue" false fi fi if [ -z "$(is_active_milestone "$milestone")" ] ; then error "$redmine_url is a backport to $milestone which is not an active milestone" info "Cowardly refusing to work on a backport to an inactive release" false fi milestone_number=$(try_known_milestones "$milestone") if [ "$milestone_number" -gt "0" ] >/dev/null 2>&1 ; then debug "Milestone ->$milestone<- is known to have number ->$milestone_number<-: skipping remote API call" else warning "Milestone ->$milestone<- is unknown to the script: falling back to GitHub API" milestone_number=$(milestone_number_from_remote_api "$milestone") fi target_branch="$milestone" info "milestone/release is $milestone" debug "milestone number is $milestone_number" if [ "$CHERRY_PICK_PHASE" ] ; then local_branch=wip-${issue}-${target_branch} if git show-ref --verify --quiet "refs/heads/$local_branch" ; then if [ "$FORCE" ] ; then warning "local branch $local_branch already exists" info "--force was given: will clobber $local_branch and attempt automated cherry-pick" cherry_pick_phase elif [ "$CHERRY_PICK_ONLY" ] ; then error "local branch $local_branch already exists" info "Cowardly refusing to clobber $local_branch as it might contain valuable data" info "(hint) run with --force to clobber it and attempt the cherry-pick" false fi if [ "$FORCE" ] || [ "$CHERRY_PICK_ONLY" ] ; then true else info "local branch $local_branch already exists: skipping cherry-pick phase" fi else info "$local_branch does not exist: will create it and attempt automated cherry-pick" cherry_pick_phase fi fi if [ "$PR_PHASE" ] ; then current_branch=$(git rev-parse --abbrev-ref HEAD) if [ "$current_branch" = "$local_branch" ] ; then true else set -x git checkout "$local_branch" set +x maybe_restore_set_x fi set -x git push -u "$fork_remote" "$local_branch" set +x maybe_restore_set_x original_issue="" original_pr="" original_pr_url="" debug "Generating backport PR description" populate_original_issue populate_original_pr desc="backport tracker: ${redmine_url}" if [ "$original_pr" ] || [ "$original_issue" ] ; then desc="${desc}\n\n---\n" [ "$original_pr" ] && desc="${desc}\nbackport of $(number_to_url "github" "${original_pr}")" [ "$original_issue" ] && desc="${desc}\nparent tracker: $(number_to_url "redmine" "${original_issue}")" fi desc="${desc}\n\nthis backport was staged using ceph-backport.sh version ${SCRIPT_VERSION}\nfind the latest version at ${github_endpoint}/blob/main/src/script/ceph-backport.sh" debug "Generating backport PR title" if [ "$original_pr" ] ; then backport_pr_title="${milestone}: $(curl --silent https://api.github.com/repos/ceph/ceph/pulls/${original_pr} | jq -r '.title')" else if [[ $tracker_title =~ ^${milestone}: ]] ; then backport_pr_title="${tracker_title}" else backport_pr_title="${milestone}: ${tracker_title}" fi fi if [[ "$backport_pr_title" =~ \" ]] ; then backport_pr_title="${backport_pr_title//\"/\\\"}" fi debug "Opening backport PR" if [ "$EXPLICIT_FORK" ] ; then source_repo="$EXPLICIT_FORK" else source_repo="$github_user" fi remote_api_output=$(curl -u ${github_user}:${github_token} --silent --data-binary "{\"title\":\"${backport_pr_title}\",\"head\":\"${source_repo}:${local_branch}\",\"base\":\"${target_branch}\",\"body\":\"${desc}\"}" "https://api.github.com/repos/ceph/ceph/pulls") backport_pr_number=$(echo "$remote_api_output" | jq -r .number) if [ -z "$backport_pr_number" ] || [ "$backport_pr_number" = "null" ] ; then error "failed to open backport PR" bail_out_github_api "$remote_api_output" fi backport_pr_url="$(number_to_url "github" "$backport_pr_number")" info "Opened backport PR ${backport_pr_url}" fi if [ "$EXISTING_PR" ] ; then populate_original_issue populate_original_pr backport_pr_number="$EXISTING_PR" backport_pr_url="$(number_to_url "github" "$backport_pr_number")" existing_pr_routine fi if [ "$PR_PHASE" ] || [ "$EXISTING_PR" ] ; then maybe_update_pr_milestone_labels pgrep firefox >/dev/null && firefox "${backport_pr_url}" fi if [ "$TRACKER_PHASE" ] ; then debug "Considering Backport tracker issue ${redmine_url}" status_should_be=2 # In Progress desc_should_be="${backport_pr_url}" assignee_should_be="${redmine_user_id}" if [ "$EXISTING_PR" ] ; then data_binary="{\"issue\":{\"description\":\"${desc_should_be}\",\"status_id\":${status_should_be}}}" else data_binary="{\"issue\":{\"description\":\"${desc_should_be}\",\"status_id\":${status_should_be},\"assigned_to_id\":${assignee_should_be}}}" fi remote_api_status_code="$(curl --write-out '%{http_code}' --output /dev/null --silent -X PUT --header "Content-type: application/json" --data-binary "${data_binary}" "${redmine_url}.json?key=$redmine_key")" if [ "$FORCE" ] || [ "$EXISTING_PR" ] ; then true else if [ "${remote_api_status_code:0:1}" = "2" ] ; then true elif [ "${remote_api_status_code:0:1}" = "4" ] ; then warning "remote API ${redmine_endpoint} returned status ${remote_api_status_code}" info "This merely indicates that you cannot modify issue fields at ${redmine_endpoint}" info "and does not limit your ability to do backports." else error "Remote API ${redmine_endpoint} returned unexpected response code ${remote_api_status_code}" fi fi # check if anything actually changed on the Redmine issue remote_api_output=$(curl --silent "${redmine_url}.json?include=journals") status_is="$(echo "$remote_api_output" | jq -r '.issue.status.id')" desc_is="$(echo "$remote_api_output" | jq -r '.issue.description')" assignee_is="$(echo "$remote_api_output" | jq -r '.issue.assigned_to.id')" tracker_was_updated="" tracker_is_in_desired_state="yes" [ "$(tracker_component_was_updated "status" "$tracker_status_id" "$status_is")" ] && tracker_was_updated="yes" [ "$(tracker_component_was_updated "desc" "$tracker_description" "$desc_is")" ] && tracker_was_updated="yes" if [ "$EXISTING_PR" ] ; then true else [ "$(tracker_component_was_updated "assignee" "$tracker_assignee_id" "$assignee_is")" ] && tracker_was_updated="yes" fi [ "$(tracker_component_is_in_desired_state "status" "$status_is" "$status_should_be")" ] || tracker_is_in_desired_state="" [ "$(tracker_component_is_in_desired_state "desc" "$desc_is" "$desc_should_be")" ] || tracker_is_in_desired_state="" if [ "$EXISTING_PR" ] ; then true else [ "$(tracker_component_is_in_desired_state "assignee" "$assignee_is" "$assignee_should_be")" ] || tracker_is_in_desired_state="" fi if [ "$tracker_is_in_desired_state" ] ; then [ "$tracker_was_updated" ] && info "Backport tracker ${redmine_url} was updated" info "Backport tracker ${redmine_url} is in the desired state" pgrep firefox >/dev/null && firefox "${redmine_url}" exit 0 fi if [ "$tracker_was_updated" ] ; then warning "backport tracker ${redmine_url} was updated, but is not in the desired state. Please check it." pgrep firefox >/dev/null && firefox "${redmine_url}" exit 1 else data_binary="{\"issue\":{\"notes\":\"please link this Backport tracker issue with GitHub PR ${desc_should_be}\nceph-backport.sh version ${SCRIPT_VERSION}\"}}" remote_api_status_code=$(curl --write-out '%{http_code}' --output /dev/null --silent -X PUT --header "Content-type: application/json" --data-binary "${data_binary}" "${redmine_url}.json?key=$redmine_key") if [ "${remote_api_status_code:0:1}" = "2" ] ; then info "Comment added to ${redmine_url}" fi exit 0 fi fi
64,260
34.211507
267
sh
null
ceph-main/src/script/ceph-debug-docker.sh
#!/usr/bin/env bash # This can be run from e.g. the senta machines which have docker available. You # may need to run this script with sudo. # # Once you have booted into the image, you should be able to debug the core file: # $ gdb -q /ceph/teuthology-archive/.../coredump/1500013578.8678.core # # You may want to install other packages (yum) as desired. # # Once you're finished, please delete old images in a timely fashion. set -e CACHE="" FLAVOR="default" SUDO="" PRIVILEGED="" function run { printf "%s\n" "$*" "$@" } function main { eval set -- $(getopt --name "$0" --options 'h' --longoptions 'help,no-cache,flavor:,sudo,privileged' -- "$@") while [ "$#" -gt 0 ]; do case "$1" in -h|--help) printf '%s: [--no-cache] <branch>[:sha1] <environment>\n' "$0" exit 0 ;; --no-cache) CACHE="--no-cache" shift ;; --flavor) FLAVOR=$2 shift 2 ;; --privileged) PRIVILEGED=--privileged shift 1 ;; --sudo) SUDO=sudo shift 1 ;; --) shift break ;; esac done if [ -z "$1" ]; then printf "specify the branch [default \"main:latest\"]: " read branch if [ -z "$branch" ]; then branch=main:latest fi else branch="$1" fi if [ "${branch%%:*}" != "${branch}" ]; then sha=${branch##*:} else sha=latest fi branch=${branch%%:*} printf "branch: %s\nsha1: %s\n" "$branch" "$sha" if [ -z "$2" ]; then printf "specify the build environment [default \"centos:8\"]: " read env if [ -z "$env" ]; then env=centos:8 fi else env="$2" fi printf "env: %s\n" "$env" if [ -n "$SUDO_USER" ]; then user="$SUDO_USER" elif [ -n "$USER" ]; then user="$USER" else user="$(whoami)" fi tag="${user}:ceph-ci-${branch}-${sha}-${env/:/-}" T=$(mktemp -d) pushd "$T" case "$env" in centos:stream) distro="centos/8" ;; *) distro="${env/://}" esac api_url="https://shaman.ceph.com/api/search/?status=ready&project=ceph&flavor=${FLAVOR}&distros=${distro}/$(arch)&ref=${branch}&sha1=${sha}" repo_url="$(wget -O - "$api_url" | jq -r '.[0].chacra_url')repo" # validate url: wget -O /dev/null "$repo_url" if grep ubuntu <<<"$env" > /dev/null 2>&1; then # Docker makes it impossible to access anything outside the CWD : / wget -O cephdev.asc 'https://download.ceph.com/keys/autobuild.asc' cat > Dockerfile <<EOF FROM ${env} WORKDIR /root RUN apt-get update --yes --quiet && \ apt-get install --yes --quiet screen gdb software-properties-common apt-transport-https curl COPY cephdev.asc cephdev.asc RUN apt-key add cephdev.asc && \ curl -L $repo_url | tee /etc/apt/sources.list.d/ceph_dev.list && \ cat /etc/apt/sources.list.d/ceph_dev.list|sed -e 's/^deb/deb-src/' >>/etc/apt/sources.list.d/ceph_dev.list && \ apt-get update --yes && \ DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical apt-get --assume-yes -q --no-install-recommends install -o Dpkg::Options::=--force-confnew --allow-unauthenticated ceph ceph-osd-dbg ceph-mds-dbg ceph-mgr-dbg ceph-mon-dbg ceph-common-dbg ceph-fuse-dbg ceph-test-dbg radosgw-dbg python3-cephfs python3-rados EOF time run $SUDO docker build $CACHE --tag "$tag" . else # try RHEL flavor case "$env" in centos:7) python_bindings="python36-rados python36-cephfs" base_debuginfo="" ceph_debuginfo="ceph-debuginfo" debuginfo=/etc/yum.repos.d/CentOS-Linux-Debuginfo.repo ;; centos:8) python_bindings="python3-rados python3-cephfs" base_debuginfo="glibc-debuginfo" ceph_debuginfo="ceph-base-debuginfo" debuginfo=/etc/yum.repos.d/CentOS-Linux-Debuginfo.repo base_url="s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g" ;; centos:stream) python_bindings="python3-rados python3-cephfs" base_debuginfo="glibc-debuginfo" ceph_debuginfo="ceph-base-debuginfo" debuginfo=/etc/yum.repos.d/CentOS-Stream-Debuginfo.repo ;; esac if [ "${FLAVOR}" = "crimson" ]; then ceph_debuginfo+=" ceph-crimson-osd-debuginfo ceph-crimson-osd" fi cat > Dockerfile <<EOF FROM ${env} WORKDIR /root RUN sed -i '${base_url}' /etc/yum.repos.d/CentOS-* && \ yum update -y && \ sed -i 's/enabled=0/enabled=1/' ${debuginfo} && \ yum update -y && \ yum install -y tmux epel-release wget psmisc ca-certificates gdb RUN wget -O /etc/yum.repos.d/ceph-dev.repo $repo_url && \ yum clean all && \ yum upgrade -y && \ yum install -y ceph ${base_debuginfo} ${ceph_debuginfo} ${python_bindings} EOF time run $SUDO docker build $CACHE --tag "$tag" . fi popd rm -rf -- "$T" printf "built image %s\n" "$tag" run $SUDO docker run $PRIVILEGED -ti -v /ceph:/ceph:ro -v /cephfs:/cephfs:ro -v /teuthology:/teuthology:ro "$tag" return 0 } main "$@"
5,570
30.653409
316
sh
null
ceph-main/src/script/check_commands.sh
#!/bin/sh git grep -e COMMAND\( -e COMMAND_WITH_FLAG\( | grep -o "(\"[a-zA-Z ]*\"" | grep -o "[a-zA-Z ]*" | sort | uniq > commands.txt missing_test=false good_tests="" bad_tests="" while read cmd; do if git grep -q "$cmd" -- src/test qa/; then good_tests="$good_tests '$cmd'" else echo "'$cmd' has no apparent tests" missing_test=true bad_tests="$bad_tests '$cmd'" fi done < commands.txt if [ "$missing_test" == true ]; then echo "Missing tests!" $bad_tests exit 1; fi
495
22.619048
124
sh
null
ceph-main/src/script/crash_bdev.sh
#!/usr/bin/env bash set -ex while true; do ./ceph daemon osd.0 config set bdev_inject_crash 2 sleep 5 tail -n 1000 out/osd.0.log | grep bdev_inject_crash || exit 1 ./init-ceph start osd.0 sleep 20 done
223
19.363636
65
sh
null
ceph-main/src/script/credits.sh
#!/usr/bin/env bash range="$1" TMP=/tmp/credits declare -A mail2author declare -A mail2organization remap="s/'/ /g" git log --pretty='%ae %aN <%aE>' $range | sed -e "$remap" | sort -u > $TMP while read mail who ; do author=$(echo $who | git -c mailmap.file=.peoplemap check-mailmap --stdin) mail2author[$mail]="$author" organization=$(echo $who | git -c mailmap.file=.organizationmap check-mailmap --stdin) mail2organization[$mail]="$organization" done < $TMP declare -A author2lines declare -A organization2lines git log --no-merges --pretty='%ae' $range | sed -e "$remap" | sort -u > $TMP while read mail ; do count=$(git log --numstat --author="$mail" --pretty='%h' $range | egrep -v 'package-lock\.json|\.xlf' | # generated files that should be excluded from line counting perl -e 'while(<STDIN>) { if(/(\d+)\t(\d+)/) { $added += $1; $deleted += $2 } }; print $added + $deleted;') (( author2lines["${mail2author[$mail]}"] += $count )) (( organization2lines["${mail2organization[$mail]}"] += $count )) done < $TMP echo echo "Number of lines added and removed, by authors" for author in "${!author2lines[@]}" ; do printf "%6s %s\n" ${author2lines["$author"]} "$author" done | sort -rn | nl echo echo "Number of lines added and removed, by organization" for organization in "${!organization2lines[@]}" ; do printf "%6s %s\n" ${organization2lines["$organization"]} "$organization" done | sort -rn | nl echo echo "Commits, by authors" git log --no-merges --pretty='%aN <%aE>' $range | git -c mailmap.file=.peoplemap check-mailmap --stdin | sort | uniq -c | sort -rn | nl echo echo "Commits, by organizations" git log --no-merges --pretty='%aN <%aE>' $range | git -c mailmap.file=.organizationmap check-mailmap --stdin | sort | uniq -c | sort -rn | nl echo echo "Reviews, by authors (one review spans multiple commits)" git log --pretty=%b $range | perl -n -e 'print "$_\n" if(s/^\s*Reviewed-by:\s*(.*<.*>)\s*$/\1/i)' | git check-mailmap --stdin | git -c mailmap.file=.peoplemap check-mailmap --stdin | sort | uniq -c | sort -rn | nl echo echo "Reviews, by organizations (one review spans multiple commits)" git log --pretty=%b $range | perl -n -e 'print "$_\n" if(s/^\s*Reviewed-by:\s*(.*<.*>)\s*$/\1/i)' | git check-mailmap --stdin | git -c mailmap.file=.organizationmap check-mailmap --stdin | sort | uniq -c | sort -rn | nl
2,379
49.638298
219
sh
null
ceph-main/src/script/extend_stretch_cluster.sh
#!/usr/bin/env bash set -ex ../src/script/add_osd.sh 4 'host=host1-1 datacenter=site1 root=default' ../src/script/add_osd.sh 5 'host=host1-2 datacenter=site1 root=default' ../src/script/add_osd.sh 6 'host=host2-1 datacenter=site2 root=default' ../src/script/add_osd.sh 7 'host=host2-2 datacenter=site2 root=default'
318
34.444444
71
sh
null
ceph-main/src/script/find_dups_in_pg_log.sh
#!/bin/sh # pipe output of grep for objectname in osd logs to me # # e.g., # # zgrep smithi01817880-936 remote/*/log/*osd* | ~/src/ceph/src/script/find_dups_in_pg_log.sh # # or # # zcat remote/*/log/*osd* | ~/src/ceph/src/script/find_dups_in_pg_log.sh # # output will be any requests that appear in the pg log >1 time (along with # their count) #grep append_log | sort -k 2 | sed 's/.*append_log//' | awk '{print $3 " " $8}' | sort | uniq | awk '{print $2}' | sort | uniq -c | grep -v ' 1 ' grep append_log | grep ' by ' | \ perl -pe 's/(.*) \[([^ ]*) (.*) by ([^ ]+) (.*)/$2 $4/' | \ sort | uniq | \ awk '{print $2}' | \ sort | uniq -c | grep -v ' 1 '
690
29.043478
145
sh
null
ceph-main/src/script/gen-corpus.sh
#!/usr/bin/env bash # -*- mode:sh; tab-width:4; sh-basic-offset:4; indent-tabs-mode:nil -*- # vim: softtabstop=4 shiftwidth=4 expandtab set -ex function get_jobs() { local jobs=$(nproc) if [ $jobs -ge 8 ] ; then echo 8 else echo $jobs fi } [ -z "$BUILD_DIR" ] && BUILD_DIR=build function build() { local encode_dump_path=$1 shift ./do_cmake.sh \ -DWITH_MGR_DASHBOARD_FRONTEND=OFF \ -DWITH_DPDK=OFF \ -DWITH_SPDK=OFF \ -DCMAKE_CXX_FLAGS="-DENCODE_DUMP_PATH=${encode_dump_path}" cd ${BUILD_DIR} cmake --build . -- -j$(get_jobs) } function run() { MON=3 MGR=2 OSD=3 MDS=3 RGW=1 ../src/vstart.sh -n -x local old_path="$PATH" export PATH="$PWD/bin:$PATH" export CEPH_CONF="$PWD/ceph.conf" ceph osd pool create mypool rados -p mypool bench 10 write -b 123 ceph osd out 0 ceph osd in 0 init-ceph restart osd.1 for f in ../qa/workunits/cls/*.sh ; do $f done ../qa/workunits/rados/test.sh ceph_test_librbd ceph_test_libcephfs init-ceph restart mds.a ../qa/workunits/rgw/run-s3tests.sh PATH="$old_path" ../src/stop.sh } function import_corpus() { local encode_dump_path=$1 shift local version=$1 shift # import the corpus ../src/test/encoding/import.sh \ ${encode_dump_path} \ ${version} \ ../ceph-object-corpus/archive ../src/test/encoding/import-generated.sh \ ../ceph-object-corpus/archive # prune it pushd ../ceph-object-corpus bin/prune-archive.sh popd } function verify() { ctest -R readable.sh } function commit_and_push() { local version=$1 shift pushd ../ceph-object-corpus git checkout -b wip-${version} git add archive/${version} git commit --signoff --message=${version} git remote add cc [email protected]:ceph/ceph-object-corpus.git git push cc wip-${version} popd } encode_dump_path=$(mktemp -d) build $encode_dump_path echo "generating corpus objects.." run version=$(bin/ceph-dencoder version) echo "importing corpus. it may take over 30 minutes.." import_corpus $encode_dump_path $version echo "verifying imported corpus.." verify echo "all good, pushing to remote repo.." commit_and_push ${version} rm -rf encode_dump_path
2,323
21.563107
71
sh
null
ceph-main/src/script/kcon_all.sh
#!/bin/sh -x p() { echo "$*" > /sys/kernel/debug/dynamic_debug/control } echo 9 > /proc/sysrq-trigger p 'module ceph +p' p 'module libceph +p' p 'module rbd +p'
164
14
52
sh