Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
ceph-main/src/rgw/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_header.pl
#!/usr/bin/perl use strict; my $fn = shift @ARGV; my $old = `cat $fn`; my $header = `cat doc/header.txt`; # strip existing header my $new = $old; if ($new =~ /^(.*)\* Ceph - scalable distributed file system/s) { my ($a,@b) = split(/\*\/\n/, $new); $new = join("*/\n",@b); } $new = $header . $new; if ($new ne $old) { open(O, ">$fn.new"); print O $new; close O; system "diff $fn $fn.new"; rename "$fn.new", $fn; #unlink "$fn.new"; }
446
15.555556
65
pl
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/bdev_grep.pl
#!/usr/bin/perl my $offset = shift @ARGV; while (<>) { # next unless / \d\d bdev /; my $rest = $_; my @hit; while ($rest =~ /([\da-f]+)[~\+]([\da-f]+)/) { my ($o, $l) = $rest =~ /([\da-f]+)[~\+]([\da-f]+)/; $rest = $'; if (hex($offset) >= hex($o) && hex($offset) < hex($o) + hex($l)) { my $rel = hex($offset) - hex($o); push(@hit, sprintf("%x",$rel)); } } print join(',',@hit) . "\t$_" if @hit; }
445
21.3
52
pl
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/ceph_dump_log.py
# Copyright (C) 2018 Red Hat Inc. # # Authors: Sergio Lopez Pascual <[email protected]> # Brad Hubbard <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Library Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Public License for more details. # # By default ceph daemons and clients maintain a list of log_max_recent (default # 10000) log entries at a high debug level. This script will attempt to dump out # that log from a ceph::log::Log* passed to the ceph-dump-log function or, if no # object is passed, default to the globally available 'g_ceph_context->_log' # (thanks Kefu). This pointer may be obtained via the _log member of a # CephContext object (i.e. *cct->_log) from any thread that contains such a # CephContext. Normally, you will find a thread waiting in # ceph::logging::Log::entry and the 'this' pointer from such a frame can also be # passed to ceph-dump-log. import gdb from datetime import datetime try: # Python 2 forward compatibility range = xrange except NameError: pass class CephDumpLog(gdb.Command): def __init__(self): super(CephDumpLog, self).__init__( 'ceph-dump-log', gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL, False) def invoke(self, args, from_tty): arg_list = gdb.string_to_argv(args) if len(arg_list) < 1: log = gdb.parse_and_eval('g_ceph_context->_log') else: log = gdb.parse_and_eval(arg_list[0]) luminous_mimic = None try: entry = log['m_recent']['m_head'] size = log['m_recent']['m_len'] luminous_mimic = True except gdb.error: entry = log['m_recent']['m_first'] size = log['m_recent']['m_size'] end = log['m_recent']['m_end'] buff = log['m_recent']['m_buff'] for i in range(size): if luminous_mimic: try: # early luminous stamp = int(str(entry['m_stamp']['tv']['tv_sec']) + str(entry['m_stamp']['tv']['tv_nsec'])) logline = entry['m_streambuf']['m_buf'] strlen = int(entry['m_streambuf']['m_buf_len']) except gdb.error: # mimic stamp = entry['m_stamp']['__d']['__r']['count'] pptr = entry['m_data']['m_pptr'] logline = entry['m_data']['m_buf'] strlen = int(pptr - logline) else: stamp = entry['m_stamp']['__d']['__r']['count'] logline = entry['str']['m_holder']['m_start'] strlen = int(entry['str']['m_holder']['m_size']) thread = entry['m_thread'] prio = entry['m_prio'] subsys = entry['m_subsys'] dt = datetime.fromtimestamp(int(stamp) / 1e9) # Giving up some precision gdb.write(dt.strftime('%Y-%m-%d %H:%M:%S.%f ')) gdb.write("thread: {0:#x} priority: {1} subsystem: {2} ". format(int(thread), prio, subsys)) gdb.write(logline.string("ascii", errors='ignore')[0:strlen]) gdb.write("\n") if luminous_mimic: entry = entry['m_next'].dereference() else: entry = entry + 1 if entry >= end: entry = buff CephDumpLog()
3,710
38.903226
111
py
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/fix_modeline.pl
#!/usr/bin/perl use strict; my $fn = shift @ARGV; my $old = `cat $fn`; my $header = `cat doc/modeline.txt`; # strip existing modeline my $new = $old; $new =~ s/^\/\/ \-\*\- ([^\n]+) \-\*\-([^\n]*)\n//s; # emacs $new =~ s/^\/\/ vim: ([^\n]*)\n//s; # vim; $new =~ s/^\/\/ \-\*\- ([^\n]+) \-\*\-([^\n]*)\n//s; # emacs $new =~ s/^\/\/ vim: ([^\n]*)\n//s; # vim; $new =~ s/^\/\/ \-\*\- ([^\n]+) \-\*\-([^\n]*)\n//s; # emacs $new =~ s/^\/\/ vim: ([^\n]*)\n//s; # vim; # add correct header $new = $header . $new; if ($new ne $old) { print "$fn\n"; open(O, ">$fn.new"); print O $new; close O; system "diff $fn $fn.new"; rename "$fn.new", $fn; #unlink "$fn.new"; }
668
21.3
60
pl
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
null
ceph-main/src/script/kcon_most.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' p 'file net/ceph/messenger.c -p' p 'file' `grep -- --- /sys/kernel/debug/dynamic_debug/control | grep ceph | awk '{print $1}' | sed 's/:/ line /'` '+p' p 'file' `grep -- === /sys/kernel/debug/dynamic_debug/control | grep ceph | awk '{print $1}' | sed 's/:/ line /'` '+p'
435
30.142857
118
sh
null
ceph-main/src/script/lib-build.sh
#!/usr/bin/env bash # # lib-build.sh - A library of build and test bash shell functions. # # There should be few, or none, globals in this file beyond function # definitions. # # This script should be `shellcheck`ed. Please run shellcheck when # making changes to this script and use ignore comments # (ref: https://www.shellcheck.net/wiki/Ignore ) to explicitly mark # where a line is intentionally ignoring a typical rule. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # The following global only exists to help detect if lib-build has already been # sourced. This is only needed because the scripts that are being migrated are # often sourcing (as opposed to exec'ing one another). # shellcheck disable=SC2034 _SOURCED_LIB_BUILD=1 function in_jenkins() { [ -n "$JENKINS_HOME" ] } function ci_debug() { if in_jenkins || [ "${FORCE_CI_DEBUG}" ]; then echo "CI_DEBUG: $*" fi } # get_processors returns 1/2 the value of the value returned by # the nproc program OR the value of the environment variable NPROC # allowing the user to tune the number of cores visible to the # build scripts. function get_processors() { # get_processors() depends on coreutils nproc. if [ -n "$NPROC" ]; then echo "$NPROC" else if [ "$(nproc)" -ge 2 ]; then echo "$(($(nproc) / 2))" else echo 1 fi fi } # discover_compiler takes one argument, purpose, which may be used # to adjust the results for a specific need. It sets three environment # variables `discovered_c_compiler`, `discovered_cxx_compiler` and # `discovered_compiler_env`. The `discovered_compiler_env` variable # may be blank. If not, it will contain a file that needs to be sourced # prior to using the compiler. function discover_compiler() { # nb: currently purpose is not used for detection local purpose="$1" ci_debug "Finding compiler for ${purpose}" local compiler_env="" local cxx_compiler=g++ local c_compiler=gcc # ubuntu/debian ci builds prefer clang for i in {14..10}; do if type -t "clang-$i" > /dev/null; then cxx_compiler="clang++-$i" c_compiler="clang-$i" break fi done # but if this is {centos,rhel} we need gcc-toolset if [ -f "/opt/rh/gcc-toolset-11/enable" ]; then ci_debug "Detected SCL gcc-toolset-11 environment file" compiler_env="/opt/rh/gcc-toolset-11/enable" # shellcheck disable=SC1090 cxx_compiler="$(. ${compiler_env} && command -v g++)" # shellcheck disable=SC1090 c_compiler="$(. ${compiler_env} && command -v gcc)" fi export discovered_c_compiler="${c_compiler}" export discovered_cxx_compiler="${cxx_compiler}" export discovered_compiler_env="${compiler_env}" return 0 }
3,031
33.067416
79
sh
null
ceph-main/src/script/ptl-tool.py
#!/usr/bin/python3 # README: # # This tool's purpose is to make it easier to merge PRs into test branches and # into main. Make sure you generate a Personal access token in GitHub and # add it your ~/.github.key. # # Because developers often have custom names for the ceph upstream remote # (https://github.com/ceph/ceph.git), You will probably want to export the # PTL_TOOL_BASE_PATH environment variable in your shell rc files before using # this script: # # export PTL_TOOL_BASE_PATH=refs/remotes/<remotename>/ # # and PTL_TOOL_BASE_REMOTE as the name of your Ceph upstream remote (default: "upstream"): # # export PTL_TOOL_BASE_REMOTE=<remotename> # # # ** Here are some basic exmples to get started: ** # # Merging all PRs labeled 'wip-pdonnell-testing' into a new test branch: # # $ src/script/ptl-tool.py --pr-label wip-pdonnell-testing # Adding labeled PR #18805 to PR list # Adding labeled PR #18774 to PR list # Adding labeled PR #18600 to PR list # Will merge PRs: [18805, 18774, 18600] # Detaching HEAD onto base: main # Merging PR #18805 # Merging PR #18774 # Merging PR #18600 # Checked out new branch wip-pdonnell-testing-20171108.054517 # Created tag testing/wip-pdonnell-testing-20171108.054517 # # # Merging all PRs labeled 'wip-pdonnell-testing' into main: # # $ src/script/ptl-tool.py --pr-label wip-pdonnell-testing --branch main # Adding labeled PR #18805 to PR list # Adding labeled PR #18774 to PR list # Adding labeled PR #18600 to PR list # Will merge PRs: [18805, 18774, 18600] # Detaching HEAD onto base: main # Merging PR #18805 # Merging PR #18774 # Merging PR #18600 # Checked out branch main # # Now push to main: # $ git push upstream main # ... # # # Merging PR #1234567 and #2345678 into a new test branch with a testing label added to the PR: # # $ src/script/ptl-tool.py 1234567 2345678 --label wip-pdonnell-testing # Detaching HEAD onto base: main # Merging PR #1234567 # Labeled PR #1234567 wip-pdonnell-testing # Merging PR #2345678 # Labeled PR #2345678 wip-pdonnell-testing # Deleted old test branch wip-pdonnell-testing-20170928 # Created branch wip-pdonnell-testing-20170928 # Created tag testing/wip-pdonnell-testing-20170928_03 # # # Merging PR #1234567 into main leaving a detached HEAD (i.e. do not update your repo's main branch) and do not label: # # $ src/script/ptl-tool.py --branch HEAD --merge-branch-name main 1234567 # Detaching HEAD onto base: main # Merging PR #1234567 # Leaving HEAD detached; no branch anchors your commits # # Now push to main: # $ git push upstream HEAD:main # # # Merging PR #12345678 into luminous leaving a detached HEAD (i.e. do not update your repo's main branch) and do not label: # # $ src/script/ptl-tool.py --base luminous --branch HEAD --merge-branch-name luminous 12345678 # Detaching HEAD onto base: luminous # Merging PR #12345678 # Leaving HEAD detached; no branch anchors your commits # # Now push to luminous: # $ git push upstream HEAD:luminous # # # Merging all PRs labelled 'wip-pdonnell-testing' into main leaving a detached HEAD: # # $ src/script/ptl-tool.py --base main --branch HEAD --merge-branch-name main --pr-label wip-pdonnell-testing # Adding labeled PR #18192 to PR list # Will merge PRs: [18192] # Detaching HEAD onto base: main # Merging PR #18192 # Leaving HEAD detached; no branch anchors your commit # TODO # Look for check failures? # redmine issue update: http://www.redmine.org/projects/redmine/wiki/Rest_Issues import argparse import codecs import datetime import getpass import git import itertools import json import logging import os import re import requests import sys from os.path import expanduser log = logging.getLogger(__name__) log.addHandler(logging.StreamHandler()) log.setLevel(logging.INFO) BASE_PROJECT = os.getenv("PTL_TOOL_BASE_PROJECT", "ceph") BASE_REPO = os.getenv("PTL_TOOL_BASE_REPO", "ceph") BASE_REMOTE = os.getenv("PTL_TOOL_BASE_REMOTE", "upstream") BASE_PATH = os.getenv("PTL_TOOL_BASE_PATH", "refs/remotes/upstream/") GITDIR = os.getenv("PTL_TOOL_GITDIR", ".") USER = os.getenv("PTL_TOOL_USER", getpass.getuser()) with open(expanduser("~/.github.key")) as f: PASSWORD = f.read().strip() TEST_BRANCH = os.getenv("PTL_TOOL_TEST_BRANCH", "wip-{user}-testing-%Y%m%d.%H%M%S") SPECIAL_BRANCHES = ('main', 'luminous', 'jewel', 'HEAD') INDICATIONS = [ re.compile("(Reviewed-by: .+ <[\[email protected]]+>)", re.IGNORECASE), re.compile("(Acked-by: .+ <[\[email protected]]+>)", re.IGNORECASE), re.compile("(Tested-by: .+ <[\[email protected]]+>)", re.IGNORECASE), ] # find containing git dir git_dir = GITDIR max_levels = 6 while not os.path.exists(git_dir + '/.git'): git_dir += '/..' max_levels -= 1 if max_levels < 0: break CONTRIBUTORS = {} NEW_CONTRIBUTORS = {} with codecs.open(git_dir + "/.githubmap", encoding='utf-8') as f: comment = re.compile("\s*#") patt = re.compile("([\w-]+)\s+(.*)") for line in f: if comment.match(line): continue m = patt.match(line) CONTRIBUTORS[m.group(1)] = m.group(2) BZ_MATCH = re.compile("(.*https?://bugzilla.redhat.com/.*)") TRACKER_MATCH = re.compile("(.*https?://tracker.ceph.com/.*)") def get(session, url, params=None, paging=True): if params is None: params = {} params['per_page'] = 100 log.debug(f"Fetching {url}") response = session.get(url, auth=(USER, PASSWORD), params=params) log.debug(f"Response = {response}; links = {response.headers.get('link', '')}") if response.status_code != 200: log.error(f"Failed to fetch {url}: {response}") sys.exit(1) j = response.json() yield j if paging: link = response.headers.get('link', None) page = 2 while link is not None and 'next' in link: log.debug(f"Fetching {url}") new_params = dict(params) new_params.update({'page': page}) response = session.get(url, auth=(USER, PASSWORD), params=new_params) log.debug(f"Response = {response}; links = {response.headers.get('link', '')}") if response.status_code != 200: log.error(f"Failed to fetch {url}: {response}") sys.exit(1) yield response.json() link = response.headers.get('link', None) page += 1 def get_credits(session, pr, pr_req): comments = [pr_req] log.debug(f"Getting comments for #{pr}") endpoint = f"https://api.github.com/repos/{BASE_PROJECT}/{BASE_REPO}/issues/{pr}/comments" for c in get(session, endpoint): comments.extend(c) log.debug(f"Getting reviews for #{pr}") endpoint = f"https://api.github.com/repos/{BASE_PROJECT}/{BASE_REPO}/pulls/{pr}/reviews" reviews = [] for c in get(session, endpoint): comments.extend(c) reviews.extend(c) log.debug(f"Getting review comments for #{pr}") endpoint = f"https://api.github.com/repos/{BASE_PROJECT}/{BASE_REPO}/pulls/{pr}/comments" for c in get(session, endpoint): comments.extend(c) credits = set() for comment in comments: body = comment["body"] if body: url = comment["html_url"] for m in BZ_MATCH.finditer(body): log.info("[ {url} ] BZ cited: {cite}".format(url=url, cite=m.group(1))) for m in TRACKER_MATCH.finditer(body): log.info("[ {url} ] Ceph tracker cited: {cite}".format(url=url, cite=m.group(1))) for indication in INDICATIONS: for cap in indication.findall(comment["body"]): credits.add(cap) new_new_contributors = {} for review in reviews: if review["state"] == "APPROVED": user = review["user"]["login"] try: credits.add("Reviewed-by: "+CONTRIBUTORS[user]) except KeyError as e: try: credits.add("Reviewed-by: "+NEW_CONTRIBUTORS[user]) except KeyError as e: try: name = input("Need name for contributor \"%s\" (use ^D to skip); Reviewed-by: " % user) name = name.strip() if len(name) == 0: continue NEW_CONTRIBUTORS[user] = name new_new_contributors[user] = name credits.add("Reviewed-by: "+name) except EOFError as e: continue return "\n".join(credits), new_new_contributors def build_branch(args): base = args.base branch = datetime.datetime.utcnow().strftime(args.branch).format(user=USER) label = args.label merge_branch_name = args.merge_branch_name if merge_branch_name is False: merge_branch_name = branch session = requests.Session() if label: # Check the label format if re.search(r'\bwip-(.*?)-testing\b', label) is None: log.error("Unknown Label '{lblname}'. Label Format: wip-<name>-testing".format(lblname=label)) sys.exit(1) # Check if the Label exist in the repo endpoint = f"https://api.github.com/repos/{BASE_PROJECT}/{BASE_REPO}/labels/{label}" get(session, endpoint, paging=False) G = git.Repo(args.git) # First get the latest base branch and PRs from BASE_REMOTE remote = getattr(G.remotes, BASE_REMOTE) remote.fetch() prs = args.prs if args.pr_label is not None: if args.pr_label == '' or args.pr_label.isspace(): log.error("--pr-label must have a non-space value") sys.exit(1) payload = {'labels': args.pr_label, 'sort': 'created', 'direction': 'desc'} endpoint = f"https://api.github.com/repos/{BASE_PROJECT}/{BASE_REPO}/issues" labeled_prs = [] for l in get(session, endpoint, params=payload): labeled_prs.extend(l) if len(labeled_prs) == 0: log.error("Search for PRs matching label '{}' returned no results!".format(args.pr_label)) sys.exit(1) for pr in labeled_prs: if pr['pull_request']: n = pr['number'] log.info("Adding labeled PR #{} to PR list".format(n)) prs.append(n) log.info("Will merge PRs: {}".format(prs)) if base == 'HEAD': log.info("Branch base is HEAD; not checking out!") else: log.info("Detaching HEAD onto base: {}".format(base)) try: base_path = args.base_path + base base = next(ref for ref in G.refs if ref.path == base_path) except StopIteration: log.error("Branch " + base + " does not exist!") sys.exit(1) # So we know that we're not on an old test branch, detach HEAD onto ref: base.checkout() for pr in prs: pr = int(pr) log.info("Merging PR #{pr}".format(pr=pr)) remote_ref = "refs/pull/{pr}/head".format(pr=pr) fi = remote.fetch(remote_ref) if len(fi) != 1: log.error("PR {pr} does not exist?".format(pr=pr)) sys.exit(1) tip = fi[0].ref.commit endpoint = f"https://api.github.com/repos/{BASE_PROJECT}/{BASE_REPO}/pulls/{pr}" response = next(get(session, endpoint, paging=False)) message = "Merge PR #%d into %s\n\n* %s:\n" % (pr, merge_branch_name, remote_ref) for commit in G.iter_commits(rev="HEAD.."+str(tip)): message = message + ("\t%s\n" % commit.message.split('\n', 1)[0]) # Get tracker issues / bzs cited so the PTL can do updates short = commit.hexsha[:8] for m in BZ_MATCH.finditer(commit.message): log.info("[ {sha1} ] BZ cited: {cite}".format(sha1=short, cite=m.group(1))) for m in TRACKER_MATCH.finditer(commit.message): log.info("[ {sha1} ] Ceph tracker cited: {cite}".format(sha1=short, cite=m.group(1))) message = message + "\n" if args.credits: (addendum, new_contributors) = get_credits(session, pr, response) message += addendum else: new_contributors = [] G.git.merge(tip.hexsha, '--no-ff', m=message) if new_contributors: # Check out the PR, add a commit adding to .githubmap log.info("adding new contributors to githubmap in merge commit") with open(git_dir + "/.githubmap", "a") as f: for c in new_contributors: f.write("%s %s\n" % (c, new_contributors[c])) G.index.add([".githubmap"]) G.git.commit("--amend", "--no-edit") if label: req = session.post("https://api.github.com/repos/{project}/{repo}/issues/{pr}/labels".format(pr=pr, project=BASE_PROJECT, repo=BASE_REPO), data=json.dumps([label]), auth=(USER, PASSWORD)) if req.status_code != 200: log.error("PR #%d could not be labeled %s: %s" % (pr, label, req)) sys.exit(1) log.info("Labeled PR #{pr} {label}".format(pr=pr, label=label)) # If the branch is 'HEAD', leave HEAD detached (but use "main" for commit message) if branch == 'HEAD': log.info("Leaving HEAD detached; no branch anchors your commits") else: created_branch = False try: G.head.reference = G.create_head(branch) log.info("Checked out new branch {branch}".format(branch=branch)) created_branch = True except: G.head.reference = G.create_head(branch, force=True) log.info("Checked out branch {branch}".format(branch=branch)) if created_branch: # tag it for future reference. tag = "testing/%s" % branch git.refs.tag.Tag.create(G, tag) log.info("Created tag %s" % tag) def main(): parser = argparse.ArgumentParser(description="Ceph PTL tool") default_base = 'main' default_branch = TEST_BRANCH default_label = '' if len(sys.argv) > 1 and sys.argv[1] in SPECIAL_BRANCHES: argv = sys.argv[2:] default_branch = 'HEAD' # Leave HEAD detached default_base = default_branch default_label = False else: argv = sys.argv[1:] parser.add_argument('--branch', dest='branch', action='store', default=default_branch, help='branch to create ("HEAD" leaves HEAD detached; i.e. no branch is made)') parser.add_argument('--merge-branch-name', dest='merge_branch_name', action='store', default=False, help='name of the branch for merge messages') parser.add_argument('--base', dest='base', action='store', default=default_base, help='base for branch') parser.add_argument('--base-path', dest='base_path', action='store', default=BASE_PATH, help='base for branch') parser.add_argument('--git-dir', dest='git', action='store', default=git_dir, help='git directory') parser.add_argument('--label', dest='label', action='store', default=default_label, help='label PRs for testing') parser.add_argument('--pr-label', dest='pr_label', action='store', help='label PRs for testing') parser.add_argument('--no-credits', dest='credits', action='store_false', help='skip indication search (Reviewed-by, etc.)') parser.add_argument('prs', metavar="PR", type=int, nargs='*', help='Pull Requests to merge') args = parser.parse_args(argv) return build_branch(args) if __name__ == "__main__": main()
15,439
37.123457
199
py
null
ceph-main/src/script/run-cbt.sh
#!/bin/sh usage() { prog_name=$1 shift cat <<EOF usage: $prog_name [options] <config-file>... options: -a,--archive-dir directory in which the test result is stored, default to $PWD/cbt-archive --build-dir directory where CMakeCache.txt is located, default to $PWD --cbt directory of cbt if you have already a copy of it. ceph/cbt:master will be cloned from github if not specified -h,--help print this help message --source-dir the path to the top level of Ceph source tree, default to $PWD/.. --use-existing do not setup/teardown a vstart cluster for testing example: $prog_name --cbt ~/dev/cbt -a /tmp ../src/test/crimson/cbt/radosbench_4K_read.yaml EOF } prog_name=$(basename $0) archive_dir=$PWD/cbt-archive build_dir=$PWD source_dir=$(dirname $PWD) use_existing=false classical=false opts=$(getopt --options "a:h" --longoptions "archive-dir:,build-dir:,source-dir:,cbt:,help,use-existing,classical" --name $prog_name -- "$@") eval set -- "$opts" while true; do case "$1" in -a|--archive-dir) archive_dir=$2 shift 2 ;; --build-dir) build_dir=$2 shift 2 ;; --source-dir) source_dir=$2 shift 2 ;; --cbt) cbt_dir=$2 shift 2 ;; --use-existing) use_existing=true shift ;; --classical) classical=true shift ;; -h|--help) usage $prog_name return 0 ;; --) shift break ;; *) echo "unexpected argument $1" 1>&2 return 1 ;; esac done if test $# -gt 0; then config_files="$@" else echo "$prog_name: please specify one or more .yaml files" 1>&2 usage $prog_name return 1 fi if test -z "$cbt_dir"; then cbt_dir=$PWD/cbt git clone --depth 1 -b master https://github.com/ceph/cbt.git $cbt_dir fi # store absolute path before changing cwd source_dir=$(readlink -f $source_dir) if ! $use_existing; then cd $build_dir || exit # seastar uses 128*8 aio in reactor for io and 10003 aio for events pooling # for each core, if it fails to enough aio context, the seastar application # bails out. and take other process into consideration, let's make it # 32768 per core max_io=$(expr 32768 \* "$(nproc)") if test "$(/sbin/sysctl --values fs.aio-max-nr)" -lt $max_io; then sudo /sbin/sysctl -q -w fs.aio-max-nr=$max_io fi if $classical; then MDS=0 MGR=1 OSD=3 MON=1 $source_dir/src/vstart.sh -n -X \ --without-dashboard else MDS=0 MGR=1 OSD=3 MON=1 $source_dir/src/vstart.sh -n -X \ --without-dashboard --cyanstore \ -o "memstore_device_bytes=34359738368" \ --crimson --nodaemon --redirect-output \ --osd-args "--memory 4G" fi cd - || exit fi # i need to read the performance events, # see https://www.kernel.org/doc/Documentation/sysctl/kernel.txt if /sbin/capsh --supports=cap_sys_admin; then perf_event_paranoid=$(/sbin/sysctl --values kernel.perf_event_paranoid) if test $perf_event_paranoid -gt 0; then sudo /sbin/sysctl -q -w kernel.perf_event_paranoid=0 fi else echo "without cap_sys_admin, $(whoami) cannot read the perf events" fi for config_file in $config_files; do echo "testing $config_file" cbt_config=$(mktemp $config_file.XXXX.yaml) python3 $source_dir/src/test/crimson/cbt/t2c.py \ --build-dir $build_dir \ --input $config_file \ --output $cbt_config python3 $cbt_dir/cbt.py \ --archive $archive_dir \ --conf $build_dir/ceph.conf \ $cbt_config rm -f $cbt_config done if test -n "$perf_event_paranoid"; then # restore the setting sudo /sbin/sysctl -q -w kernel.perf_event_paranoid=$perf_event_paranoid fi if ! $use_existing; then cd $build_dir || exit if $classical; then $source_dir/src/stop.sh else $source_dir/src/stop.sh --crimson fi fi
4,207
27.241611
141
sh
null
ceph-main/src/script/run-make.sh
#!/usr/bin/env bash set -e if ! [ "${_SOURCED_LIB_BUILD}" = 1 ]; then SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CEPH_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" . "${CEPH_ROOT}/src/script/lib-build.sh" || exit 2 fi trap clean_up_after_myself EXIT ORIGINAL_CCACHE_CONF="$HOME/.ccache/ccache.conf" SAVED_CCACHE_CONF="$HOME/.run-make-check-saved-ccache-conf" function save_ccache_conf() { test -f $ORIGINAL_CCACHE_CONF && cp $ORIGINAL_CCACHE_CONF $SAVED_CCACHE_CONF || true } function restore_ccache_conf() { test -f $SAVED_CCACHE_CONF && mv $SAVED_CCACHE_CONF $ORIGINAL_CCACHE_CONF || true } function clean_up_after_myself() { rm -fr ${CEPH_BUILD_VIRTUALENV:-/tmp}/*virtualenv* restore_ccache_conf } function detect_ceph_dev_pkgs() { local cmake_opts="-DWITH_FMT_VERSION=9.0.0" local boost_root=/opt/ceph if test -f $boost_root/include/boost/config.hpp; then cmake_opts+=" -DWITH_SYSTEM_BOOST=ON -DBOOST_ROOT=$boost_root" else cmake_opts+=" -DBOOST_J=$(get_processors)" fi source /etc/os-release if [[ "$ID" == "ubuntu" ]]; then case "$VERSION" in *Xenial*) cmake_opts+=" -DWITH_RADOSGW_KAFKA_ENDPOINT=OFF";; *Focal*) cmake_opts+=" -DWITH_SYSTEM_ZSTD=ON";; esac fi echo "$cmake_opts" } function prepare() { local which_pkg="which" if command -v apt-get > /dev/null 2>&1 ; then which_pkg="debianutils" fi if test -f ./install-deps.sh ; then ci_debug "Running install-deps.sh" INSTALL_EXTRA_PACKAGES="ccache git $which_pkg clang" $DRY_RUN source ./install-deps.sh || return 1 trap clean_up_after_myself EXIT fi if ! type ccache > /dev/null 2>&1 ; then echo "ERROR: ccache could not be installed" exit 1 fi } function configure() { cat <<EOM Note that the binaries produced by this script do not contain correct time and git version information, which may make them unsuitable for debugging and production use. EOM save_ccache_conf # remove the entropy generated by the date/time embedded in the build $DRY_RUN export SOURCE_DATE_EPOCH="946684800" $DRY_RUN ccache -o sloppiness=time_macros $DRY_RUN ccache -o run_second_cpp=true if in_jenkins; then # Build host has plenty of space available, let's use it to keep # various versions of the built objects. This could increase the cache hit # if the same or similar PRs are running several times $DRY_RUN ccache -o max_size=100G else echo "Current ccache max_size setting:" ccache -p | grep max_size fi $DRY_RUN ccache -sz # Reset the ccache statistics and show the current configuration if ! discover_compiler ci-build ; then ci_debug "Failed to discover a compiler" fi if [ "${discovered_compiler_env}" ]; then ci_debug "Enabling compiler environment file: ${discovered_compiler_env}" . "${discovered_compiler_env}" fi local cxx_compiler="${discovered_cxx_compiler}" local c_compiler="${discovered_c_compiler}" local cmake_opts cmake_opts+=" -DCMAKE_CXX_COMPILER=$cxx_compiler -DCMAKE_C_COMPILER=$c_compiler" cmake_opts+=" -DCMAKE_CXX_FLAGS_DEBUG=-Werror" cmake_opts+=" -DENABLE_GIT_VERSION=OFF" cmake_opts+=" -DWITH_GTEST_PARALLEL=ON" cmake_opts+=" -DWITH_FIO=ON" cmake_opts+=" -DWITH_CEPHFS_SHELL=ON" cmake_opts+=" -DWITH_GRAFANA=ON" cmake_opts+=" -DWITH_SPDK=ON" cmake_opts+=" -DWITH_RBD_MIRROR=ON" if [ $WITH_SEASTAR ]; then cmake_opts+=" -DWITH_SEASTAR=ON" fi if [ $WITH_ZBD ]; then cmake_opts+=" -DWITH_ZBD=ON" fi if [ $WITH_RBD_RWL ]; then cmake_opts+=" -DWITH_RBD_RWL=ON" fi cmake_opts+=" -DWITH_RBD_SSD_CACHE=ON" cmake_opts+=" $(detect_ceph_dev_pkgs)" ci_debug "Our cmake_opts are: $cmake_opts" ci_debug "Running ./configure" ci_debug "Running do_cmake.sh" $DRY_RUN ./do_cmake.sh $cmake_opts $@ || return 1 } function build() { local targets="$@" if test -n "$targets"; then targets="--target $targets" fi local bdir=build if [ "$BUILD_DIR" ]; then bdir="$BUILD_DIR" fi $DRY_RUN cd "${bdir}" BUILD_MAKEOPTS=${BUILD_MAKEOPTS:-$DEFAULT_MAKEOPTS} test "$BUILD_MAKEOPTS" && echo "make will run with option(s) $BUILD_MAKEOPTS" # older cmake does not support --parallel or -j, so pass it to underlying generator ci_debug "Running cmake" $DRY_RUN cmake --build . $targets -- $BUILD_MAKEOPTS || return 1 $DRY_RUN ccache -s # print the ccache statistics to evaluate the efficiency } DEFAULT_MAKEOPTS=${DEFAULT_MAKEOPTS:--j$(get_processors)} if [ "$0" = "$BASH_SOURCE" ]; then # not sourced if [ `uname` = FreeBSD ]; then GETOPT=/usr/local/bin/getopt else GETOPT=getopt fi options=$(${GETOPT} --name "$0" --options "" --longoptions "cmake-args:" -- "$@") if [ $? -ne 0 ]; then exit 2 fi eval set -- "${options}" while true; do case "$1" in --cmake-args) cmake_args=$2 shift 2;; --) shift break;; *) echo "bad option $1" >& 2 exit 2;; esac done prepare configure "$cmake_args" build "$@" fi
5,447
29.099448
88
sh
null
ceph-main/src/script/run_mypy.sh
#!/usr/bin/env bash # needs to be executed from the src directory. # generates a report at src/mypy_report.txt set -e python3 -m venv .mypy_venv . .mypy_venv/bin/activate ! pip install $(find -name requirements.txt -not -path './frontend/*' -printf '-r%p ') pip install mypy MYPY_INI="$PWD"/mypy.ini export MYPYPATH="$PWD/pybind/rados:$PWD/pybind/rbd:$PWD/pybind/cephfs" echo -n > mypy_report.txt pushd pybind mypy --config-file="$MYPY_INI" *.py | awk '{print "pybind/" $0}' >> ../mypy_report.txt popd pushd pybind/mgr mypy --config-file="$MYPY_INI" $(find * -name '*.py' | grep -v -e venv -e tox -e env -e gyp -e node_modules) | awk '{print "pybind/mgr/" $0}' >> ../../mypy_report.txt popd pushd ceph-volume/ceph_volume mypy --config-file="$MYPY_INI" $(find * -name '*.py' | grep -v -e venv -e tox -e env -e gyp -e node_modules -e tests) | awk '{print "ceph-volume/ceph_volume/" $0}' >> ../../mypy_report.txt popd SORT_MYPY=$(cat <<-EOF #!/bin/python3 import re from collections import namedtuple class Line(namedtuple('Line', 'prefix no rest')): @classmethod def parse(cls, l): if not l: return cls('', 0, '') if re.search('Found [0-9]+ errors in [0-9]+ files', l): return cls('', 0, '') p, *rest = l.split(':', 2) if len(rest) == 1: return cls(p, 0, rest[0]) elif len(rest) == 2: try: return cls(p, int(rest[0]), rest[1]) except ValueError: return cls(p, 0, rest[0] + ':' + rest[1]) assert False, rest class Group(object): def __init__(self, line): self.line = line self.lines = [] def matches(self, other): return Line.parse(self.line).prefix == Line.parse(other).prefix def __bool__(self): return bool(self.lines) or ': note: In' not in self.line def __str__(self): return '\n'.join([self.line] + self.lines) def key(self): l1 = Line.parse(self.line) if l1.no: return l1.prefix, int(l1.no) if not self.lines: return l1.prefix, None return l1.prefix, Line.parse(self.lines[0]).no def parse(text): groups = [] def group(): try: return groups[-1] except IndexError: groups.append(Group('')) return groups[-1] for l in text: l = l.strip() if ': note: In' in l or not group().matches(l): groups.append(Group(l)) elif not l: pass else: group().lines.append(l) return (g for g in groups if g) def render(groups): groups = sorted(groups, key=Group.key) return '\n'.join(map(str, groups)) with open('mypy_report.txt') as f: new = render(parse(f)) with open('mypy_report.txt', 'w') as f: f.write(new) EOF ) python <(echo "$SORT_MYPY")
2,880
25.431193
188
sh
null
ceph-main/src/script/run_tox.sh
#!/usr/bin/env bash set -e if [ `uname` = FreeBSD ]; then GETOPT=/usr/local/bin/getopt else GETOPT=getopt fi function usage() { local prog_name=$(basename $1) shift cat <<EOF $prog_name [options] ... [test_name] options: [-h|--help] display this help message [--source-dir dir] root source directory of Ceph. deduced by the path of this script by default. [--build-dir dir] build directory of Ceph. "\$source_dir/build" by default. [--tox-path dir] directory in which "tox.ini" is located. if "test_name" is not specified, it is the current directory by default, otherwise the script will try to find a directory with the name of specified \$test_name with a "tox.ini" under it. <--tox-envs envs> tox envlist. this option is required. [--venv-path] the python virtualenv path. \$build_dir/\$test_name by default. example: following command will run tox with envlist of "py3,mypy" using the "tox.ini" in current directory. $prog_name --tox-envs py3,mypy following command will run tox with envlist of "py3" using "/ceph/src/python-common/tox.ini" $prog_name --tox-envs py3 --tox-path /ceph/src/python-common EOF } function get_cmake_variable() { local cmake_cache=$1/CMakeCache.txt shift local variable=$1 shift if [ -e $cmake_cache ]; then grep "$variable" $cmake_cache | cut -d "=" -f 2 fi } function get_tox_path() { local test_name=$1 if [ -n "$test_name" ]; then local found=$(find $source_dir -path "*/$test_name/tox.ini") echo $(dirname $found) elif [ -e tox.ini ]; then echo $(pwd) fi } function main() { local tox_path local script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" local build_dir=$script_dir/../../build local source_dir=$(get_cmake_variable $build_dir ceph_SOURCE_DIR) local tox_envs local options options=$(${GETOPT} --name "$0" --options 'h' --longoptions "help,source-dir:,build-dir:,tox-path:,tox-envs:,venv-path:" -- "$@") if [ $? -ne 0 ]; then exit 2 fi eval set -- "${options}" while true; do case "$1" in -h|--help) usage $0 exit 0;; --source-dir) source_dir=$2 shift 2;; --build-dir) build_dir=$2 shift 2;; --tox-path) tox_path=$2 shift 2;; --tox-envs) tox_envs=$2 shift 2;; --venv-path) venv_path=$2 shift 2;; --) shift break;; *) echo "bad option $1" >& 2 exit 2;; esac done local test_name if [ -z "$tox_path" ]; then # try harder if [ $# -gt 0 ]; then test_name=$1 shift fi tox_path=$(get_tox_path $test_name) venv_path="$build_dir/$test_name" else test_name=$(basename $tox_path) fi if [ ! -f ${venv_path}/bin/activate ]; then if [ -d "$venv_path" ]; then cd $venv_path echo "$PWD already exists, but it's not a virtualenv. test_name empty?" exit 1 fi $source_dir/src/tools/setup-virtualenv.sh ${venv_path} fi source ${venv_path}/bin/activate pip install tox # tox.ini will take care of this. export CEPH_BUILD_DIR=$build_dir # use the wheelhouse prepared by install-deps.sh export PIP_FIND_LINKS="$tox_path/wheelhouse" tox -c $tox_path/tox.ini -e "$tox_envs" "$@" } main "$@"
3,696
27.007576
251
sh
null
ceph-main/src/script/run_uml.sh
#!/bin/bash -norc # Magic startup script for a UML instance. As long as unique # instances are started, more than one of them can be concurrently # in use on a single system. All their network interfaces are # bridged together onto the virtual bridge "virbr0" which is # supplied by the "libvirt" package. # # Note that a DHCP server is started for that interface. It's # configured in this file: # /etc/libvirt/qemu/networks/default.xml # Unfortunately what I see there serves all possible DHCP addresses, # so stealing them like we do here isn't really kosher. To fix # it, that configuration should change to serve a smaller subset # of the available address range. # # Each instance uses its own tun/tap device, created using the # "tunctl" command. The assigned tap device will correspond with # the guest id (a small integer representing the instance), i.e., # guest id 1 uses tap1, etc. The tap device is attached to the # virtual bridge, which will have its own subnet associated with it. # The guest side of that interface will have the same subnet as the # bridge interface, with the bottom bits representing (normally) 100 # more than the guest id. So for subnet 192.168.122.0/24, guest # id 1 will use ip 192.168.122.101, guest id 2 will use ip # 192.168.122.102, and so on. Because these interfaces are bridged, # they can all communicate with each other. # You will want to override this by setting and exporting the # "CEPH_TOP" environment variable to be the directory that contains # the "ceph-client" source tree. CEPH_TOP="${CEPH_TOP:-/home/elder/ceph}" # You may want to change this too, if you want guest UML instances # to have a diffeerent IP address range. The guest IP will be based # on this plus GUEST_ID (defined below). GUEST_IP_OFFSET="${GUEST_IP_OFFSET:-100}" ############################# if [ $# -gt 1 ]; then echo "" >&2 echo "Usage: $(basename $0) [guest_id]" >&2 echo "" >&2 echo " guest_id is a small integer (default 1)" >&2 echo " (each UML instance needs a distinct guest_id)" >&2 echo "" >&2 exit 1 elif [ $# -eq 1 ]; then GUEST_ID="$1" else GUEST_ID=1 fi # This will be what the guest host calls itself. GUEST_HOSTNAME="uml-${GUEST_ID}" # This is the path to the boot disk image used by UML. DISK_IMAGE_A="${CEPH_TOP}/ceph-client/uml.${GUEST_ID}" if [ ! -f "${DISK_IMAGE_A}" ]; then echo "root disk image not found (or not a file)" >&2 exit 2 fi # Hostid 1 uses tun/tap device tap1, hostid 2 uses tap2, etc. TAP_ID="${GUEST_ID}" # This is the tap device used for this UML instance TAP="tap${TAP_ID}" # This is just used to mount an image temporarily TMP_MNT="/tmp/m$$" # Where to put a config file generated for this tap device TAP_IFUPDOWN_CONFIG="/tmp/interface-${TAP}" # Compute the HOST_IP and BROADCAST address values to use, # and assign shell variables with those names to their values. # Also compute BITS, which is the network prefix length used. # The NETMASK is then computed using that BITS value. eval $( ip addr show virbr0 | awk ' /inet/ { split($2, a, "/") printf("HOST_IP=%s\n", a[1]); printf("BROADCAST=%s\n", $4); printf("BITS=%s\n", a[2]); exit(0); }') # Use bc to avoid 32-bit wrap when computing netmask eval $( echo -n "NETMASK=" bc <<! | fmt | sed 's/ /./g' m = 2 ^ 32 - 2 ^ (32 - ${BITS}) for (p = 24; p >= 0; p = p - 8) m / (2 ^ p) % 256 ! ) # Now use the netmask and the host IP to compute the subnet address # and from that the guest IP address to use. eval $( awk ' function from_quad(addr, a, val, i) { if (split(addr, a, ".") != 4) exit(1); # address not in dotted quad format val = 0; for (i = 1; i <= 4; i++) val = val * 256 + a[i]; return val; } function to_quad(val, addr, i) { addr = ""; for (i = 1; i <= 4; i++) { addr = sprintf("%u%s%s", val % 256, i > 1 ? "." : "", addr); val = int(val / 256); } if ((val + 0) != 0) exit(1); # value provided exceeded 32 bits return addr; } BEGIN { host_ip = from_quad("'${HOST_IP}'"); netmask = from_quad("'${NETMASK}'"); guest_net_ip = '${GUEST_IP_OFFSET}' + '${GUEST_ID}'; if (and(netmask, guest_net_ip)) exit(1); # address too big for subnet subnet = and(host_ip, netmask); guest_ip = or(subnet, guest_net_ip); if (guest_ip == host_ip) exit(1); # computed guest ip matches host ip printf("SUBNET=%s\n", to_quad(subnet)); printf("GUEST_IP=%s\n", to_quad(guest_ip)); } ' < /dev/null ) ############## OK, we now know all our network parameters... # There is a series of things that need to be done as superuser, # so group them all into one big (and sort of nested!) sudo request. sudo -s <<EnD_Of_sUdO # Mount the boot disk for the UML and set up some configuration # files there. mkdir -p "${TMP_MNT}" mount -o loop "${DISK_IMAGE_A}" "${TMP_MNT}" # Arrange for loopback and eth0 to load automatically, # and for eth0 to have our desired network parameters. cat > "${TMP_MNT}/etc/network/interfaces" <<! # Used by ifup(8) and ifdown(8). See the interfaces(5) manpage or # /usr/share/doc/ifupdown/examples for more information. auto lo iface lo inet loopback auto eth0 # iface eth0 inet dhcp iface eth0 inet static address ${GUEST_IP} netmask ${NETMASK} broadcast ${BROADCAST} gateway ${HOST_IP} ! # Have the guest start with an appropriate host name. # Also record an entry for it in its own hosts file. echo "${GUEST_HOSTNAME}" > "${TMP_MNT}/etc/hostname" echo "${GUEST_IP} ${GUEST_HOSTNAME}" >> "${TMP_MNT}/etc/hosts" # The host will serve as the name server also cat > "${TMP_MNT}/etc/resolv.conf" <<! nameserver ${HOST_IP} ! # OK, done tweaking the boot image. sync umount "${DISK_IMAGE_A}" rmdir "${TMP_MNT}" # Set up a config file for "ifup" and "ifdown" (on the host) to use. # All the backslashes below are needed because we're sitting inside # a double here-document... cat > "${TAP_IFUPDOWN_CONFIG}" <<! iface ${TAP} inet manual up brctl addif virbr0 "\\\${IFACE}" up ip link set dev "\\\${IFACE}" up pre-down brctl delif virbr0 "\\\${IFACE}" pre-down ip link del dev "\\\${IFACE}" tunctl_user $(whoami) ! # OK, bring up the tap device using our config file ifup -i "${TAP_IFUPDOWN_CONFIG}" "${TAP}" EnD_Of_sUdO # Finally ready to launch the UML instance. ./linux \ umid="${GUEST_HOSTNAME}" \ ubda="${DISK_IMAGE_A}" \ eth0="tuntap,${TAP}" \ mem=1024M # When we're done, clean up. Bring down the tap interface and # delete the config file. # # Note that if the above "./linux" crashes, you'll need to run the # following commands manually in order to clean up state. sudo ifdown -i "${TAP_IFUPDOWN_CONFIG}" "${TAP}" sudo rm -f "${TAP_IFUPDOWN_CONFIG}" exit 0
6,622
30.093897
68
sh
null
ceph-main/src/script/set_up_stretch_mode.sh
#!/usr/bin/env bash set -x ./bin/ceph config set osd osd_crush_update_on_start false ./bin/ceph osd crush move osd.0 host=host1-1 datacenter=site1 root=default ./bin/ceph osd crush move osd.1 host=host1-2 datacenter=site1 root=default ./bin/ceph osd crush move osd.2 host=host2-1 datacenter=site2 root=default ./bin/ceph osd crush move osd.3 host=host2-2 datacenter=site2 root=default ./bin/ceph osd getcrushmap > crush.map.bin ./bin/crushtool -d crush.map.bin -o crush.map.txt cat <<EOF >> crush.map.txt rule stretch_rule { id 1 type replicated step take site1 step chooseleaf firstn 2 type host step emit step take site2 step chooseleaf firstn 2 type host step emit } rule stretch_rule2 { id 2 type replicated step take site1 step chooseleaf firstn 2 type host step emit step take site2 step chooseleaf firstn 2 type host step emit } rule stretch_rule3 { id 3 type replicated step take site1 step chooseleaf firstn 2 type host step emit step take site2 step chooseleaf firstn 2 type host step emit } EOF ./bin/crushtool -c crush.map.txt -o crush2.map.bin ./bin/ceph osd setcrushmap -i crush2.map.bin ./bin/ceph mon set election_strategy connectivity ./bin/ceph mon set_location a datacenter=site1 ./bin/ceph mon set_location b datacenter=site2 ./bin/ceph mon set_location c datacenter=site3 ./bin/ceph osd pool create test_stretch1 1024 1024 replicated ./bin/ceph mon enable_stretch_mode c stretch_rule datacenter
1,613
28.345455
74
sh
null
ceph-main/src/script/strip_trailing_whitespace.sh
#!/bin/sh sed -i 's/[ \t]*$//' $1 sed -i 's/^ /\t/' $1
63
11.8
27
sh
null
ceph-main/src/script/kubejacker/kubejacker.sh
#!/bin/bash set -x set -e SCRIPT=$(readlink -f "$0") SCRIPTPATH=$(dirname "$SCRIPT") # Run me from your build dir! I look for binaries in bin/, lib/ etc. BUILDPATH=$(pwd) # PREREQUISITE: a repo that you can push to. You are probably running # a local docker registry that your kubelet nodes also have access to. REPO=${REPO:-"$1"} if [ -z "$REPO" ] then echo "ERROR: no \$REPO set!" echo "Run a docker repository and set REPO to <hostname>:<port>" exit -1 fi # The output image name: this should match whatever is configured as # the image name in your Rook cluster CRD object. IMAGE=ceph/ceph TAG=latest # The namespace where ceph containers are running in your # test cluster: used for bouncing the containers. NAMESPACE=rook-ceph mkdir -p kubejacker cp $SCRIPTPATH/Dockerfile kubejacker # TODO: let user specify which daemon they're interested # in -- doing all bins all the time is too slow and bloaty #BINS="ceph-mgr ceph-mon ceph-mds ceph-osd rados radosgw-admin radosgw" #pushd bin #strip $BINS #TODO: make stripping optional #tar czf $BUILDPATH/kubejacker/bin.tar.gz $BINS #popd # We need ceph-common to support the binaries # We need librados/rbd to support mgr modules # that import the python bindings #LIBS="libceph-common.so.0 libceph-common.so librados.so.2 librados.so librados.so.2.0.0 librbd.so librbd.so.1 librbd.so.1.12.0" #pushd lib #strip $LIBS #TODO: make stripping optional #tar czf $BUILDPATH/kubejacker/lib.tar.gz $LIBS #popd pushd ../src/python-common/ceph tar --exclude=__pycache__ --exclude=tests -czf $BUILDPATH/kubejacker/python_common.tar.gz * popd pushd ../src/pybind/mgr find ./ -name "*.pyc" -exec rm -f {} \; # Exclude node_modules because it's the huge sources in dashboard/frontend tar --exclude=node_modules --exclude=tests --exclude-backups -czf $BUILDPATH/kubejacker/mgr_plugins.tar.gz * popd #ECLIBS="libec_*.so*" #pushd lib #strip $ECLIBS #TODO: make stripping optional #tar czf $BUILDPATH/kubejacker/eclib.tar.gz $ECLIBS #popd #CLSLIBS="libcls_*.so*" #pushd lib #strip $CLSLIBS #TODO: make stripping optional #tar czf $BUILDPATH/kubejacker/clslib.tar.gz $CLSLIBS #popd pushd kubejacker docker build -t $REPO/ceph/ceph:latest . popd # Push the image to the repository #docker tag $REPO/$IMAGE:$TAG $REPO/$IMAGE:latest docker push $REPO/ceph/ceph:latest #docker push $REPO/$IMAGE:$TAG # With a plain HTTP registry #podman push $REPO/ceph/ceph:latest --tls-verify=false # Finally, bounce the containers to pick up the new image kubectl -n $NAMESPACE delete pod -l app=rook-ceph-mds kubectl -n $NAMESPACE delete pod -l app=rook-ceph-mgr kubectl -n $NAMESPACE delete pod -l app=rook-ceph-mon
2,665
28.955056
128
sh
null
ceph-main/src/script/smr_benchmark/linearCopy.sh
#!/usr/bin/env bash # copy a linear file from srcFile to destination disk in a loop until writeSize MBs is written # destinationDisk is a SMR Host Aware Disk eg. /dev/sdb if [ "$#" -lt 3 ]; then echo "Usage ./linearCopy.sh srcFile destinationDisk writeSize(MB)" exit fi if [ "$(id -u)" != "0" ]; then echo "Please run as sudo user" exit fi srcFile=$1 destDisk=$2 writeSize=$3 verbose=true if [ -f time ]; then rm -rf time fi #chunkSize=4096 # in bytes chunkSize=1048576 # in bytes fileSize=`stat --printf="%s" $srcFile` numChunksInFile=`echo "$fileSize * (1048576 / $chunkSize)" | bc` chunksLeft=$(( $(($writeSize * 1048576)) / $chunkSize)) echo "fileSize = $fileSize" if [ "$(($fileSize % 512))" -ne 0 ]; then echo "$srcFile not 512 byte aligned" exit fi if [ "$(($chunkSize % 512))" -ne 0 ]; then echo "$chunkSize not 512 byte aligned" exit fi if [ "$fileSize" -lt "$chunkSize" ]; then echo "filesize $fileSize should be greater than chunkSize $chunkSize" exit fi numFileChunks=$(($fileSize / $chunkSize)) if [ $verbose == true ]; then echo "numFileChunks = $numFileChunks" fi smrLBAStart=33554432 # TODO query from SMR Drive #smrLBAStart=37224448 offset=$(( $smrLBAStart / $(( $chunkSize / 512)) )) if [ $verbose == true ]; then echo "chunksLeft = $chunksLeft, offset = $offset" fi chunkNum=0 while [ "$chunksLeft" -gt 0 ]; do chunkNum=$(($chunkNum + 1)) if [ $verbose == true ]; then echo "CHUNK $chunkNum `date +%H:%M:%S`" >> time fi dd if=$srcFile of=$destDisk seek=$offset bs=$chunkSize 2> tmp cat tmp | grep MB >> time # > /dev/null 2>&1 if [ $verbose == true ]; then echo "chunksLeft = $chunksLeft, offset = $offset" fi chunksLeft=$(($chunksLeft - $numFileChunks)) offset=$(($offset + $numFileChunks)) done if [ -f tmp ]; then rm tmp fi if [ $verbose == false ]; then rm time else echo "Time Stamp for Chunk Writes" cat time rm time fi
1,898
19.641304
94
sh
null
ceph-main/src/script/smr_benchmark/linearSMRCopy.sh
#! /usr/bin/env bash # copy a linear file from srcFile to destination SMRDisk in a loop until writeSize MBs is written # SMRDisk is the SMR Host Aware / Host Managed Disk eg. /dev/sdb usage(){ echo "linearSMRCopy.sh <srcFile> <SMRDisk> <writeSize (MB)>" } if [ "$#" -lt 3 ]; then usage exit fi if [ "$(id -u)" != "0" ]; then echo "Please run as sudo user" exit fi if which zbc_open_zone > /dev/null 2>&1 && which zbc_read_zone > /dev/null 2>&1 && which zbc_write_zone > /dev/null 2>&1 ; then echo "libzbc commands present... refreshing zones" # reset all write pointers before starting to write sudo zbc_reset_write_ptr /dev/sdb -1 else echo "libzbc commands not detected. Please install libzbc" exit fi srcFile=$1 SMRDisk=$2 writeSize=$3 iosize=10240 numberOfSectors=$(($writeSize * 2048)) smrZoneStart=33554432 # TODO query this from SMR drive #dd if=$srcFile of=$destDisk seek=$smrZoneStart bs=512 fileSize=`stat --printf="%s" $srcFile` if [ "$(($fileSize % 512))" -ne 0 ]; then echo "$srcFile not 512 byte aligned" exit fi sectorsLeftToWrite=$(($fileSize / 512)) znum=64 # TODO query this from SMR Drive zoneLength=524288 # number of sectors in each zone TODO query from SMR drive writeOffset=$smrZoneStart sectorsLeftToWrite=$numberOfSectors echo "write begin sectors Left = $sectorsLeftToWrite, writeOffset = $writeOffset zone Num = $znum" while [ "$sectorsLeftToWrite" -gt 0 ]; do sudo zbc_open_zone $SMRDisk $znum sudo time zbc_write_zone -f $srcFile -loop $SMRDisk $znum $iosize sudo zbc_close_zone /dev/sdb $znum writeOffset=$(($writeOffset+$zoneLength)) znum=$(($znum+1)) sectorsLeftToWrite=$(($sectorsLeftToWrite - $zoneLength)) done echo "write end sectors Left = $sectorsLeftToWrite, writeOffset = $writeOffset zone Num = $znum"
1,789
24.571429
127
sh
null
ceph-main/src/test/TestSignalHandlers.cc
// -*- 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) 2010 Dreamhost * * 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. * */ /* * TestSignalHandlers * * Test the Ceph signal handlers */ #include "common/ceph_argparse.h" #include "global/global_init.h" #include "common/errno.h" #include "common/debug.h" #include "common/config.h" #include <errno.h> #include <iostream> #include <sstream> #include <string> #define dout_context g_ceph_context using namespace std; // avoid compiler warning about dereferencing NULL pointer static int* get_null() { return 0; } static void simple_segv_test() { generic_dout(-1) << "triggering SIGSEGV..." << dendl; // cppcheck-suppress nullPointer int i = *get_null(); std::cout << "i = " << i << std::endl; } // Given the name of the function, we can be pretty sure this is intentional. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winfinite-recursion" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winfinite-recursion" static void infinite_recursion_test_impl() { infinite_recursion_test_impl(); } #pragma GCC diagnostic pop #pragma clang diagnostic pop static void infinite_recursion_test() { generic_dout(0) << "triggering SIGSEGV with infinite recursion..." << dendl; infinite_recursion_test_impl(); } static void usage() { cout << "usage: TestSignalHandlers [test]" << std::endl; cout << "--simple_segv: run simple_segv test" << std::endl; cout << "--infinite_recursion: run infinite_recursion test" << std::endl; generic_client_usage(); } typedef void (*test_fn_t)(void); int main(int argc, const char **argv) { auto args = argv_to_vec(argc, argv); if (args.empty()) { cerr << argv[0] << ": -h or --help for usage" << std::endl; exit(1); } if (ceph_argparse_need_usage(args)) { usage(); exit(0); } auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); test_fn_t fn = NULL; for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) { if (ceph_argparse_double_dash(args, i)) { break; } else if (ceph_argparse_flag(args, i, "--infinite_recursion", (char*)NULL)) { fn = infinite_recursion_test; } else if (ceph_argparse_flag(args, i, "-s", "--simple_segv", (char*)NULL)) { fn = simple_segv_test; } else { cerr << "unrecognized argument: " << *i << std::endl; exit(1); } } if (!fn) { std::cerr << "Please select a test to run. Type -h for help." << std::endl; exit(1); } fn(); return 0; }
2,911
23.677966
82
cc
null
ceph-main/src/test/TestTimers.cc
#include "common/ceph_argparse.h" #include "common/ceph_mutex.h" #include "common/Timer.h" #include "global/global_init.h" #include "include/Context.h" #include <iostream> /* * TestTimers * * Tests the timer classes */ #define MAX_TEST_CONTEXTS 5 using namespace std; class TestContext; namespace { int test_array[MAX_TEST_CONTEXTS]; int array_idx; TestContext* test_contexts[MAX_TEST_CONTEXTS]; ceph::mutex array_lock = ceph::make_mutex("test_timers_mutex"); } class TestContext : public Context { public: explicit TestContext(int num_) : num(num_) { } void finish(int r) override { std::lock_guard locker{array_lock}; cout << "TestContext " << num << std::endl; test_array[array_idx++] = num; } ~TestContext() override { } protected: int num; }; class StrictOrderTestContext : public TestContext { public: explicit StrictOrderTestContext (int num_) : TestContext(num_) { } void finish(int r) override { std::lock_guard locker{array_lock}; cout << "StrictOrderTestContext " << num << std::endl; test_array[num] = num; } ~StrictOrderTestContext() override { } }; static void print_status(const char *str, int ret) { cout << str << ": "; cout << ((ret == 0) ? "SUCCESS" : "FAILURE"); cout << std::endl; } template <typename T> static int basic_timer_test(T &timer, ceph::mutex *lock) { int ret = 0; memset(&test_array, 0, sizeof(test_array)); array_idx = 0; memset(&test_contexts, 0, sizeof(test_contexts)); cout << __PRETTY_FUNCTION__ << std::endl; for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { test_contexts[i] = new TestContext(i); } for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { if (lock) lock->lock(); auto t = ceph::real_clock::now() + std::chrono::seconds(2 * i); timer.add_event_at(t, test_contexts[i]); if (lock) lock->unlock(); } bool done = false; do { sleep(1); std::lock_guard locker{array_lock}; done = (array_idx == MAX_TEST_CONTEXTS); } while (!done); for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { if (test_array[i] != i) { ret = 1; cout << "error: expected test_array[" << i << "] = " << i << "; got " << test_array[i] << " instead." << std::endl; } } return ret; } static int test_out_of_order_insertion(SafeTimer &timer, ceph::mutex *lock) { int ret = 0; memset(&test_array, 0, sizeof(test_array)); array_idx = 0; memset(&test_contexts, 0, sizeof(test_contexts)); cout << __PRETTY_FUNCTION__ << std::endl; test_contexts[0] = new StrictOrderTestContext(0); test_contexts[1] = new StrictOrderTestContext(1); { auto t = ceph::real_clock::now() + 100s; std::lock_guard locker{*lock}; timer.add_event_at(t, test_contexts[0]); } { auto t = ceph::real_clock::now() + 2s; std::lock_guard locker{*lock}; timer.add_event_at(t, test_contexts[1]); } int secs = 0; for (; secs < 100 ; ++secs) { sleep(1); array_lock.lock(); int a = test_array[1]; array_lock.unlock(); if (a == 1) break; } if (secs == 100) { ret = 1; cout << "error: expected test_array[" << 1 << "] = " << 1 << "; got " << test_array[1] << " instead." << std::endl; } return ret; } static int safe_timer_cancel_all_test(SafeTimer &safe_timer, ceph::mutex& safe_timer_lock) { cout << __PRETTY_FUNCTION__ << std::endl; int ret = 0; memset(&test_array, 0, sizeof(test_array)); array_idx = 0; memset(&test_contexts, 0, sizeof(test_contexts)); for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { test_contexts[i] = new TestContext(i); } safe_timer_lock.lock(); for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { auto t = ceph::real_clock::now() + std::chrono::seconds(4 * i); safe_timer.add_event_at(t, test_contexts[i]); } safe_timer_lock.unlock(); sleep(10); safe_timer_lock.lock(); safe_timer.cancel_all_events(); safe_timer_lock.unlock(); for (int i = 0; i < array_idx; ++i) { if (test_array[i] != i) { ret = 1; cout << "error: expected test_array[" << i << "] = " << i << "; got " << test_array[i] << " instead." << std::endl; } } return ret; } static int safe_timer_cancellation_test(SafeTimer &safe_timer, ceph::mutex& safe_timer_lock) { cout << __PRETTY_FUNCTION__ << std::endl; int ret = 0; memset(&test_array, 0, sizeof(test_array)); array_idx = 0; memset(&test_contexts, 0, sizeof(test_contexts)); for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { test_contexts[i] = new StrictOrderTestContext(i); } safe_timer_lock.lock(); for (int i = 0; i < MAX_TEST_CONTEXTS; ++i) { auto t = ceph::real_clock::now() + std::chrono::seconds(4 * i); safe_timer.add_event_at(t, test_contexts[i]); } safe_timer_lock.unlock(); // cancel the even-numbered events for (int i = 0; i < MAX_TEST_CONTEXTS; i += 2) { safe_timer_lock.lock(); safe_timer.cancel_event(test_contexts[i]); safe_timer_lock.unlock(); } sleep(20); safe_timer_lock.lock(); safe_timer.cancel_all_events(); safe_timer_lock.unlock(); for (int i = 1; i < array_idx; i += 2) { if (test_array[i] != i) { ret = 1; cout << "error: expected test_array[" << i << "] = " << i << "; got " << test_array[i] << " instead." << std::endl; } } return ret; } int main(int argc, const char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(nullptr, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); int ret; ceph::mutex safe_timer_lock = ceph::make_mutex("safe_timer_lock"); SafeTimer safe_timer(g_ceph_context, safe_timer_lock); safe_timer.init(); ret = basic_timer_test <SafeTimer>(safe_timer, &safe_timer_lock); if (ret) goto done; ret = safe_timer_cancel_all_test(safe_timer, safe_timer_lock); if (ret) goto done; ret = safe_timer_cancellation_test(safe_timer, safe_timer_lock); if (ret) goto done; ret = test_out_of_order_insertion(safe_timer, &safe_timer_lock); if (ret) goto done; done: safe_timer.shutdown(); print_status(argv[0], ret); return ret; }
6,307
21.368794
75
cc
null
ceph-main/src/test/admin_socket.cc
// -*- 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) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/ceph_mutex.h" #include "common/Cond.h" #include "common/admin_socket.h" #include "common/admin_socket_client.h" #include "common/ceph_argparse.h" #include "gtest/gtest.h" #include <stdint.h> #include <string.h> #include <string> #include <sys/un.h> using namespace std; class AdminSocketTest { public: explicit AdminSocketTest(AdminSocket *asokc) : m_asokc(asokc) { } bool init(const std::string &uri) { return m_asokc->init(uri); } string bind_and_listen(const std::string &sock_path, int *fd) { return m_asokc->bind_and_listen(sock_path, fd); } bool shutdown() { m_asokc->shutdown(); return true; } AdminSocket *m_asokc; }; TEST(AdminSocket, Teardown) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, TeardownSetup) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, SendHelp) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); { string help; ASSERT_EQ("", client.do_request("{\"prefix\":\"help\"}", &help)); ASSERT_NE(string::npos, help.find("\"list available commands\"")); } { string help; ASSERT_EQ("", client.do_request("{" " \"prefix\":\"help\"," " \"format\":\"xml\"," "}", &help)); ASSERT_NE(string::npos, help.find(">list available commands<")); } { string help; ASSERT_EQ("", client.do_request("{" " \"prefix\":\"help\"," " \"format\":\"UNSUPPORTED\"," "}", &help)); ASSERT_NE(string::npos, help.find("\"list available commands\"")); } ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, SendNoOp) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); string version; ASSERT_EQ("", client.do_request("{\"prefix\":\"0\"}", &version)); ASSERT_EQ(CEPH_ADMIN_SOCK_VERSION, version); ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, SendTooLongRequest) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); string version; string request(16384, 'a'); //if admin_socket cannot handle it, segfault will happened. ASSERT_NE("", client.do_request(request, &version)); ASSERT_EQ(true, asoct.shutdown()); } class MyTest : public AdminSocketHook { int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& result) override { std::vector<std::string> args; TOPNSPC::common::cmd_getval(cmdmap, "args", args); result.append(command); result.append("|"); string resultstr; for (std::vector<std::string>::iterator it = args.begin(); it != args.end(); ++it) { if (it != args.begin()) resultstr += ' '; resultstr += *it; } result.append(resultstr); return 0; } }; TEST(AdminSocket, RegisterCommand) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); std::unique_ptr<AdminSocketHook> my_test_asok = std::make_unique<MyTest>(); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); ASSERT_EQ(0, asoct.m_asokc->register_command("test", my_test_asok.get(), "")); string result; ASSERT_EQ("", client.do_request("{\"prefix\":\"test\"}", &result)); ASSERT_EQ("test|", result); ASSERT_EQ(true, asoct.shutdown()); } class MyTest2 : public AdminSocketHook { int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& result) override { std::vector<std::string> args; TOPNSPC::common::cmd_getval(cmdmap, "args", args); result.append(command); result.append("|"); string resultstr; for (std::vector<std::string>::iterator it = args.begin(); it != args.end(); ++it) { if (it != args.begin()) resultstr += ' '; resultstr += *it; } result.append(resultstr); ss << "error stream"; return 0; } }; TEST(AdminSocket, RegisterCommandPrefixes) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); std::unique_ptr<AdminSocketHook> my_test_asok = std::make_unique<MyTest>(); std::unique_ptr<AdminSocketHook> my_test2_asok = std::make_unique<MyTest2>(); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); ASSERT_EQ(0, asoct.m_asokc->register_command("test name=args,type=CephString,n=N", my_test_asok.get(), "")); ASSERT_EQ(0, asoct.m_asokc->register_command("test command name=args,type=CephString,n=N", my_test2_asok.get(), "")); string result; ASSERT_EQ("", client.do_request("{\"prefix\":\"test\"}", &result)); ASSERT_EQ("test|", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test command\"}", &result)); ASSERT_EQ("test command|", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test command\",\"args\":[\"post\"]}", &result)); ASSERT_EQ("test command|post", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test command\",\"args\":[\" post\"]}", &result)); ASSERT_EQ("test command| post", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test\",\"args\":[\"this thing\"]}", &result)); ASSERT_EQ("test|this thing", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test\",\"args\":[\" command post\"]}", &result)); ASSERT_EQ("test| command post", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test\",\"args\":[\" this thing\"]}", &result)); ASSERT_EQ("test| this thing", result); ASSERT_EQ(true, asoct.shutdown()); } class BlockingHook : public AdminSocketHook { public: ceph::mutex _lock = ceph::make_mutex("BlockingHook::_lock"); ceph::condition_variable _cond; BlockingHook() = default; int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& result) override { std::unique_lock l{_lock}; _cond.wait(l); return 0; } }; TEST(AdminSocketClient, Ping) { string path = get_rand_socket_path(); std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketClient client(path); // no socket { bool ok; std::string result = client.ping(&ok); #ifndef _WIN32 // TODO: convert WSA errors. EXPECT_NE(std::string::npos, result.find("No such file or directory")); #endif ASSERT_FALSE(ok); } // file exists but does not allow connections (no process, wrong type...) int fd = ::creat(path.c_str(), 0777); ASSERT_TRUE(fd); // On Windows, we won't be able to remove the file unless we close it // first. ASSERT_FALSE(::close(fd)); { bool ok; std::string result = client.ping(&ok); #ifndef _WIN32 #if defined(__APPLE__) || defined(__FreeBSD__) const char* errmsg = "Socket operation on non-socket"; #else const char* errmsg = "Connection refused"; #endif EXPECT_NE(std::string::npos, result.find(errmsg)); #endif /* _WIN32 */ ASSERT_FALSE(ok); } // a daemon is connected to the socket { AdminSocketTest asoct(asokc.get()); ASSERT_TRUE(asoct.init(path)); bool ok; std::string result = client.ping(&ok); EXPECT_EQ("", result); ASSERT_TRUE(ok); ASSERT_TRUE(asoct.shutdown()); } // hardcoded five seconds timeout prevents infinite blockage { AdminSocketTest asoct(asokc.get()); BlockingHook *blocking = new BlockingHook(); ASSERT_EQ(0, asoct.m_asokc->register_command("0", blocking, "")); ASSERT_TRUE(asoct.init(path)); bool ok; std::string result = client.ping(&ok); #ifndef _WIN32 EXPECT_NE(std::string::npos, result.find("Resource temporarily unavailable")); #endif ASSERT_FALSE(ok); { std::lock_guard l{blocking->_lock}; blocking->_cond.notify_all(); } ASSERT_TRUE(asoct.shutdown()); delete blocking; } } TEST(AdminSocket, bind_and_listen) { string path = get_rand_socket_path(); std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); // successfull bind { int fd = 0; string message; message = asoct.bind_and_listen(path, &fd); ASSERT_NE(0, fd); ASSERT_EQ("", message); ASSERT_EQ(0, ::compat_closesocket(fd)); ASSERT_EQ(0, ::unlink(path.c_str())); } // silently discard an existing file { int fd = 0; string message; int fd2 = ::creat(path.c_str(), 0777); ASSERT_TRUE(fd2); // On Windows, we won't be able to remove the file unless we close it // first. ASSERT_FALSE(::close(fd2)); message = asoct.bind_and_listen(path, &fd); ASSERT_NE(0, fd); ASSERT_EQ("", message); ASSERT_EQ(0, ::compat_closesocket(fd)); ASSERT_EQ(0, ::unlink(path.c_str())); } // do not take over a live socket { ASSERT_TRUE(asoct.init(path)); int fd = 0; string message; message = asoct.bind_and_listen(path, &fd); std::cout << "message: " << message << std::endl; EXPECT_NE(std::string::npos, message.find("File exists")); ASSERT_TRUE(asoct.shutdown()); } } /* * Local Variables: * compile-command: "cd .. ; * make unittest_admin_socket && * valgrind \ * --max-stackframe=20000000 --tool=memcheck \ * ./unittest_admin_socket --debug-asok 20 # --gtest_filter=AdminSocket*.* * " * End: */
10,771
30.497076
119
cc
null
ceph-main/src/test/admin_socket_output.cc
// -*- 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) 2017 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <regex> // For regex, regex_search #include "common/admin_socket_client.h" // For AdminSocketClient #include "common/ceph_json.h" // For JSONParser, JSONObjIter #include "include/buffer.h" // For bufferlist #include "admin_socket_output.h" using namespace std; void AdminSocketOutput::add_target(const std::string& target) { if (target == "all") { add_target("osd"); add_target("mon"); add_target("mgr"); add_target("mds"); add_target("client"); return; } targets.insert(target); } void AdminSocketOutput::add_command(const std::string& target, const std::string& command) { auto seek = custom_commands.find(target); if (seek != custom_commands.end()) { seek->second.push_back(command); } else { std::vector<std::string> vec; vec.push_back(command); custom_commands.insert(std::make_pair(target, vec)); } } void AdminSocketOutput::add_test(const std::string &target, const std::string &command, bool (*test)(std::string &)) { auto seek = tests.find(target); if (seek != tests.end()) { seek->second.push_back(std::make_pair(command, test)); } else { std::vector<std::pair<std::string, bool (*)(std::string &)>> vec; vec.push_back(std::make_pair(command, test)); tests.insert(std::make_pair(target, vec)); } } void AdminSocketOutput::postpone(const std::string &target, const std::string& command) { auto seek = postponed_commands.find(target); if (seek != postponed_commands.end()) { seek->second.push_back(command); } else { std::vector<string> vec; vec.push_back(command); postponed_commands.insert(std::make_pair(target, vec)); } } bool AdminSocketOutput::init_sockets() { std::cout << "Initialising sockets" << std::endl; std::string socket_regex = R"(\..*\.asok)"; for (const auto &x : fs::recursive_directory_iterator(socketdir)) { std::cout << x.path() << std::endl; if (x.path().extension() == ".asok") { for (auto target = targets.cbegin(); target != targets.cend();) { std::regex reg(prefix + *target + socket_regex); if (std::regex_search(x.path().filename().string(), reg)) { std::cout << "Found " << *target << " socket " << x.path() << std::endl; sockets.insert(std::make_pair(*target, x.path().string())); target = targets.erase(target); } else { ++target; } } if (targets.empty()) { std::cout << "Found all required sockets" << std::endl; break; } } } return !sockets.empty() && targets.empty(); } std::pair<std::string, std::string> AdminSocketOutput::run_command(AdminSocketClient &client, const std::string &raw_command, bool send_untouched) { std::cout << "Sending command \"" << raw_command << "\"" << std::endl; std::string command; std::string output; if (send_untouched) { command = raw_command; } else { command = "{\"prefix\":\"" + raw_command + "\"}"; } std::string err = client.do_request(command, &output); if (!err.empty()) { std::cerr << __func__ << " AdminSocketClient::do_request errored with: " << err << std::endl; ceph_abort(); } return std::make_pair(command, output); } bool AdminSocketOutput::gather_socket_output() { std::cout << "Gathering socket output" << std::endl; for (const auto& socket : sockets) { std::string response; AdminSocketClient client(socket.second); std::cout << std::endl << "Sending request to " << socket << std::endl << std::endl; std::string err = client.do_request("{\"prefix\":\"help\"}", &response); if (!err.empty()) { std::cerr << __func__ << " AdminSocketClient::do_request errored with: " << err << std::endl; return false; } std::cout << response << '\n'; JSONParser parser; bool ret = parser.parse(response.c_str(), response.size()); if (!ret) { cerr << "parse error" << std::endl; return false; } socket_results sresults; JSONObjIter iter = parser.find_first(); const auto postponed_iter = postponed_commands.find(socket.first); std::vector<std::string> postponed; if (postponed_iter != postponed_commands.end()) { postponed = postponed_iter->second; } std::cout << "Sending commands to " << socket.first << " socket" << std::endl; for (; !iter.end(); ++iter) { if (std::find(postponed.begin(), postponed.end(), (*iter)->get_name()) != std::end(postponed)) { std::cout << "Command \"" << (*iter)->get_name() << "\" postponed" << std::endl; continue; } sresults.insert(run_command(client, (*iter)->get_name())); } if (sresults.empty()) { return false; } // Custom commands const auto seek = custom_commands.find(socket.first); if (seek != custom_commands.end()) { std::cout << std::endl << "Sending custom commands:" << std::endl; for (const auto& raw_command : seek->second) { sresults.insert(run_command(client, raw_command, true)); } } // Postponed commands if (!postponed.empty()) std::cout << std::endl << "Sending postponed commands" << std::endl; for (const auto& command : postponed) { sresults.insert(run_command(client, command)); } results.insert( std::pair<std::string, socket_results>(socket.first, sresults)); } return true; } std::string AdminSocketOutput::get_result(const std::string &target, const std::string &command) const { const auto& target_results = results.find(target); if (target_results == results.end()) return std::string(""); else { const auto& result = target_results->second.find(command); if (result == target_results->second.end()) return std::string(""); else return result->second; } } bool AdminSocketOutput::run_tests() const { for (const auto& socket : sockets) { const auto& seek = tests.find(socket.first); if (seek != tests.end()) { std::cout << std::endl; std::cout << "Running tests for " << socket.first << " socket" << std::endl; for (const auto& test : seek->second) { auto result = get_result(socket.first, test.first); if(result.empty()) { std::cout << "Failed to find result for command: " << test.first << std::endl; return false; } else { std::cout << "Running test for command: " << test.first << std::endl; const auto& test_func = test.second; bool res = test_func(result); if (res == false) return false; else std::cout << "Test passed" << std::endl; } } } } return true; } void AdminSocketOutput::exec() { ceph_assert(init_directories()); ceph_assert(init_sockets()); ceph_assert(gather_socket_output()); ceph_assert(run_tests()); }
7,700
30.691358
90
cc
null
ceph-main/src/test/admin_socket_output.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) 2017 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_ADMIN_SOCKET_OUTPUT_H #define CEPH_ADMIN_SOCKET_OUTPUT_H #include <filesystem> #include <string> #include <map> #include <set> #include <vector> namespace fs = std::filesystem; using socket_results = std::map<std::string, std::string>; using test_functions = std::vector<std::pair<std::string, bool (*)(std::string &)>>; class AdminSocketClient; class AdminSocketOutput { public: AdminSocketOutput() {} void add_target(const std::string &target); void add_command(const std::string &target, const std::string &command); void add_test(const std::string &target, const std::string &command, bool (*test)(std::string &)); void postpone(const std::string &target, const std::string &command); void exec(); void mod_for_vstart(const std::string& dir) { socketdir = dir; prefix = ""; } private: bool init_directories() const { std::cout << "Checking " << socketdir << std::endl; return exists(socketdir) && is_directory(socketdir); } bool init_sockets(); bool gather_socket_output(); std::string get_result(const std::string &target, const std::string &command) const; std::pair<std::string, std::string> run_command(AdminSocketClient &client, const std::string &raw_command, bool send_untouched = false); bool run_tests() const; std::set<std::string> targets; std::map<std::string, std::string> sockets; std::map<std::string, socket_results> results; std::map<std::string, std::vector<std::string>> custom_commands; std::map<std::string, std::vector<std::string>> postponed_commands; std::map<std::string, test_functions> tests; std::string prefix = "ceph-"; fs::path socketdir = "/var/run/ceph"; }; #endif // CEPH_ADMIN_SOCKET_OUTPUT_H
2,157
27.025974
86
h
null
ceph-main/src/test/admin_socket_output_tests.cc
// -*- 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) 2017 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <string> #include <iostream> #include "common/ceph_json.h" // Test functions // Example test function /* bool test_config_get_admin_socket(std::string& output) { return std::string::npos != output.find("admin_socket") && std::string::npos != output.rfind(".asok"); } */ bool test_dump_pgstate_history(std::string &output) { JSONParser parser; bool ret = parser.parse(output.c_str(), output.size()); if (!ret) { std::cerr << "test_dump_pgstate_history: parse error" << std::endl; return false; } JSONObjIter iterone = parser.find_first(); if (iterone.end()) { //Empty std::cerr << "test_dump_pgstate_history: command output empty, failing" << std::endl; return false; } unsigned int total = 0; if ((*iterone)->get_name() == "pgs") { JSONObjIter iter = (*(*iterone)->find_first())->find_first(); for (; !iter.end(); ++iter) { if ((*iter)->get_name() == "pg") { ret = !(*iter)->get_data().empty(); if (ret == false) { std::cerr << "test_dump_pgstate_history: pg value empty, failing" << std::endl; std::cerr << "Dumping full output: " << std::endl; std::cerr << output << std::endl; break; } total++; } else if ((*iter)->get_name() == "history") { ret = std::string::npos != (*iter)->get_data().find("epoch") && std::string::npos != (*iter)->get_data().find("state") && std::string::npos != (*iter)->get_data().find("enter") && std::string::npos != (*iter)->get_data().find("exit"); if (ret == false) { std::cerr << "test_dump_pgstate_history: Can't find expected values in " "history object, failing" << std::endl; std::cerr << "Problem output was:" << std::endl; std::cerr << (*iter)->get_data() << std::endl; break; } total++; } else if ((*iter)->get_name() == "currently") { ret = !(*iter)->get_data().empty(); if (ret == false) { std::cerr << "test_dump_pgstate_history: currently value empty, failing" << std::endl; std::cerr << "Dumping full output: " << std::endl; std::cerr << output << std::endl; break; } total++; } else { std::cerr << "test_dump_pgstate_history: unrecognised field " << (*iter)->get_name() << ", failing" << std::endl; std::cerr << "Dumping full output: " << std::endl; std::cerr << output << std::endl; break; } } } else { std::cerr << "test_dump_pgstate_history: unrecognised format, failing" << std::endl; std::cerr << "Dumping full output: " << std::endl; std::cerr << output << std::endl; return false; } if (total != 3) { std::cerr << "Could not find required elements, failing" << std::endl; std::cerr << "Dumping full output: " << std::endl; std::cerr << output << std::endl; return false; } return ret; }
3,504
31.453704
92
cc
null
ceph-main/src/test/admin_socket_output_tests.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) 2017 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_ADMIN_SOCKET_OUTPUT_TESTS_H #define CEPH_ADMIN_SOCKET_OUTPUT_TESTS_H // Test function declarations, definitions in admin_socket_output_tests.cc // Example test function /* bool test_config_get_admin_socket(std::string& output); */ bool test_dump_pgstate_history(std::string& output); #endif // CEPH_ADMIN_SOCKET_OUTPUT_TESTS_H
744
24.689655
74
h
null
ceph-main/src/test/barclass.cc
#include <iostream> #include <string.h> #include <stdlib.h> #include "objclass/objclass.h" CLS_VER(1,0) CLS_NAME(bar) cls_handle_t h_class; cls_method_handle_t h_foo; int foo_method(cls_method_context_t ctx, char *indata, int datalen, char **outdata, int *outdatalen) { int i; cls_log("hello world, this is bar"); cls_log("indata=%s", indata); *outdata = (char *)malloc(128); for (i=0; i<strlen(indata) + 1; i++) { if (indata[i] == '0') { (*outdata)[i] = '*'; } else { (*outdata)[i] = indata[i]; } } *outdatalen = strlen(*outdata) + 1; cls_log("outdata=%s", *outdata); return 0; } void class_init() { cls_log("Loaded bar class!"); cls_register("bar", &h_class); cls_register_method(h_class, "bar", foo_method, &h_foo); return; }
817
15.693878
67
cc
null
ceph-main/src/test/base64.cc
// -*- 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) 2011 Dreamhost * * 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/armor.h" #include "common/config.h" #include "include/buffer.h" #include "include/encoding.h" #include "gtest/gtest.h" using namespace std; TEST(RoundTrip, SimpleRoundTrip) { static const int OUT_LEN = 4096; const char * const original = "abracadabra"; const char * const correctly_encoded = "YWJyYWNhZGFicmE="; char out[OUT_LEN]; memset(out, 0, sizeof(out)); int alen = ceph_armor(out, out + OUT_LEN, original, original + strlen(original)); ASSERT_STREQ(correctly_encoded, out); char out2[OUT_LEN]; memset(out2, 0, sizeof(out2)); ceph_unarmor(out2, out2 + OUT_LEN, out, out + alen); ASSERT_STREQ(original, out2); } TEST(RoundTrip, RandomRoundTrips) { static const int IN_MAX = 1024; static const int OUT_MAX = 4096; static const int ITERS = 1000; for (int i = 0; i < ITERS; ++i) { unsigned int seed = i; int in_len = rand_r(&seed) % IN_MAX; char in[IN_MAX]; memset(in, 0, sizeof(in)); for (int j = 0; j < in_len; ++j) { in[j] = rand_r(&seed) % 0xff; } char out[OUT_MAX]; memset(out, 0, sizeof(out)); int alen = ceph_armor(out, out + OUT_MAX, in, in + in_len); ASSERT_GE(alen, 0); char decoded[IN_MAX]; memset(decoded, 0, sizeof(decoded)); int blen = ceph_unarmor(decoded, decoded + IN_MAX, out, out + alen); ASSERT_GE(blen, 0); ASSERT_EQ(memcmp(in, decoded, in_len), 0); } } TEST(EdgeCase, EndsInNewline) { static const int OUT_MAX = 4096; char b64[] = "aaaa\n"; char decoded[OUT_MAX]; memset(decoded, 0, sizeof(decoded)); int blen = ceph_unarmor(decoded, decoded + OUT_MAX, b64, b64 + sizeof(b64)-1); ASSERT_GE(blen, 0); } TEST(FuzzEncoding, BadDecode1) { static const int OUT_LEN = 4096; const char * const bad_encoded = "FAKEBASE64 foo"; char out[OUT_LEN]; memset(out, 0, sizeof(out)); int alen = ceph_unarmor(out, out + OUT_LEN, bad_encoded, bad_encoded + strlen(bad_encoded)); ASSERT_LT(alen, 0); } TEST(FuzzEncoding, BadDecode2) { string str("FAKEBASE64 foo"); bool failed = false; try { bufferlist bl; bl.append(str); bufferlist cl; cl.decode_base64(bl); cl.hexdump(std::cerr); } catch (const buffer::error &err) { failed = true; } ASSERT_EQ(failed, true); }
2,671
24.941748
94
cc
null
ceph-main/src/test/bench_journald_logger.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "common/Journald.h" #include "log/Entry.h" #include "log/SubsystemMap.h" using namespace ceph::logging; int main() { SubsystemMap subs; JournaldLogger journald(&subs); for (int i = 0; i < 100000; i++) { MutableEntry entry(0, 0); entry.get_ostream() << "This is log message " << i << ", which is a little bit looooooooo********ooooooooog and may contains multiple\nlines."; journald.log_entry(entry); } }
535
24.52381
147
cc
null
ceph-main/src/test/bench_log.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "common/Thread.h" #include "common/debug.h" #include "common/Clock.h" #include "common/config.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #define dout_context g_ceph_context using namespace std; struct T : public Thread { int num; set<int> myset; map<int,string> mymap; explicit T(int n) : num(n) { myset.insert(123); myset.insert(456); mymap[1] = "foo"; mymap[10] = "bar"; } void *entry() override { while (num-- > 0) generic_dout(0) << "this is a typical log line. set " << myset << " and map " << mymap << dendl; return 0; } }; void usage(const char *name) { cout << name << " <threads> <lines>\n" << "\t threads: the number of threads for this test.\n" << "\t lines: the number of log entries per thread.\n"; } int main(int argc, const char **argv) { if (argc < 3) { usage(argv[0]); return EXIT_FAILURE; } int threads = atoi(argv[1]); int num = atoi(argv[2]); cout << threads << " threads, " << num << " lines per thread" << std::endl; auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_OSD, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); utime_t start = ceph_clock_now(); list<T*> ls; for (int i=0; i<threads; i++) { T *t = new T(num); t->create("t"); ls.push_back(t); } for (int i=0; i<threads; i++) { T *t = ls.front(); ls.pop_front(); t->join(); delete t; } utime_t t = ceph_clock_now(); t -= start; cout << " flushing.. " << t << " so far ..." << std::endl; g_ceph_context->_log->flush(); utime_t end = ceph_clock_now(); utime_t dur = end - start; cout << dur << std::endl; return 0; }
1,880
20.62069
77
cc
null
ceph-main/src/test/bufferlist.cc
// -*- 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) 2013 Cloudwatt <[email protected]> * * Author: Loic Dachary <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library Public License for more details. * */ #include <limits.h> #include <errno.h> #include <sys/uio.h> #include "include/buffer.h" #include "include/buffer_raw.h" #include "include/compat.h" #include "include/utime.h" #include "include/coredumpctl.h" #include "include/encoding.h" #include "common/buffer_instrumentation.h" #include "common/environment.h" #include "common/Clock.h" #include "common/safe_io.h" #include "gtest/gtest.h" #include "stdlib.h" #include "fcntl.h" #include "sys/stat.h" #include "include/crc32c.h" #include "common/sctp_crc32.h" #define MAX_TEST 1000000 #define FILENAME "bufferlist" using namespace std; static char cmd[128]; using ceph::buffer_instrumentation::instrumented_bptr; TEST(Buffer, constructors) { unsigned len = 17; // // buffer::create // { bufferptr ptr(buffer::create(len)); EXPECT_EQ(len, ptr.length()); } // // buffer::claim_char // { char* str = new char[len]; ::memset(str, 'X', len); bufferptr ptr(buffer::claim_char(len, str)); EXPECT_EQ(len, ptr.length()); EXPECT_EQ(str, ptr.c_str()); EXPECT_EQ(0, ::memcmp(str, ptr.c_str(), len)); delete [] str; } // // buffer::create_static // { char* str = new char[len]; bufferptr ptr(buffer::create_static(len, str)); EXPECT_EQ(len, ptr.length()); EXPECT_EQ(str, ptr.c_str()); delete [] str; } // // buffer::create_malloc // { bufferptr ptr(buffer::create_malloc(len)); EXPECT_EQ(len, ptr.length()); // this doesn't throw on my x86_64 wheezy box --sage //EXPECT_THROW(buffer::create_malloc((unsigned)ULLONG_MAX), buffer::bad_alloc); } // // buffer::claim_malloc // { char* str = (char*)malloc(len); ::memset(str, 'X', len); bufferptr ptr(buffer::claim_malloc(len, str)); EXPECT_EQ(len, ptr.length()); EXPECT_EQ(str, ptr.c_str()); EXPECT_EQ(0, ::memcmp(str, ptr.c_str(), len)); } // // buffer::copy // { const std::string expected(len, 'X'); bufferptr ptr(buffer::copy(expected.c_str(), expected.size())); EXPECT_NE(expected.c_str(), ptr.c_str()); EXPECT_EQ(0, ::memcmp(expected.c_str(), ptr.c_str(), len)); } // // buffer::create_page_aligned // { bufferptr ptr(buffer::create_page_aligned(len)); ::memset(ptr.c_str(), 'X', len); // doesn't throw on my x86_64 wheezy box --sage //EXPECT_THROW(buffer::create_page_aligned((unsigned)ULLONG_MAX), buffer::bad_alloc); #ifndef DARWIN ASSERT_TRUE(ptr.is_page_aligned()); #endif // DARWIN } } void bench_buffer_alloc(int size, int num) { utime_t start = ceph_clock_now(); for (int i=0; i<num; ++i) { bufferptr p = buffer::create(size); p.zero(); } utime_t end = ceph_clock_now(); cout << num << " alloc of size " << size << " in " << (end - start) << std::endl; } TEST(Buffer, BenchAlloc) { bench_buffer_alloc(16384, 1000000); bench_buffer_alloc(4096, 1000000); bench_buffer_alloc(1024, 1000000); bench_buffer_alloc(256, 1000000); bench_buffer_alloc(32, 1000000); bench_buffer_alloc(4, 1000000); } TEST(BufferRaw, ostream) { bufferptr ptr(1); std::ostringstream stream; stream << *static_cast<instrumented_bptr&>(ptr).get_raw(); EXPECT_GT(stream.str().size(), stream.str().find("buffer::raw(")); EXPECT_GT(stream.str().size(), stream.str().find("len 1 nref 1)")); } // // +-----------+ +-----+ // | | | | // | offset +----------------+ | // | | | | // | length +---- | | // | | \------- | | // +-----------+ \---+ | // | ptr | +-----+ // +-----------+ | raw | // +-----+ // TEST(BufferPtr, constructors) { unsigned len = 17; // // ptr::ptr() // { buffer::ptr ptr; EXPECT_FALSE(ptr.have_raw()); EXPECT_EQ((unsigned)0, ptr.offset()); EXPECT_EQ((unsigned)0, ptr.length()); } // // ptr::ptr(raw *r) // { bufferptr ptr(buffer::create(len)); EXPECT_TRUE(ptr.have_raw()); EXPECT_EQ((unsigned)0, ptr.offset()); EXPECT_EQ(len, ptr.length()); EXPECT_EQ(ptr.raw_length(), ptr.length()); EXPECT_EQ(1, ptr.raw_nref()); } // // ptr::ptr(unsigned l) // { bufferptr ptr(len); EXPECT_TRUE(ptr.have_raw()); EXPECT_EQ((unsigned)0, ptr.offset()); EXPECT_EQ(len, ptr.length()); EXPECT_EQ(1, ptr.raw_nref()); } // // ptr(const char *d, unsigned l) // { const std::string str(len, 'X'); bufferptr ptr(str.c_str(), len); EXPECT_TRUE(ptr.have_raw()); EXPECT_EQ((unsigned)0, ptr.offset()); EXPECT_EQ(len, ptr.length()); EXPECT_EQ(1, ptr.raw_nref()); EXPECT_EQ(0, ::memcmp(str.c_str(), ptr.c_str(), len)); } // // ptr(const ptr& p) // { const std::string str(len, 'X'); bufferptr original(str.c_str(), len); bufferptr ptr(original); EXPECT_TRUE(ptr.have_raw()); EXPECT_EQ(static_cast<instrumented_bptr&>(original).get_raw(), static_cast<instrumented_bptr&>(ptr).get_raw()); EXPECT_EQ(2, ptr.raw_nref()); EXPECT_EQ(0, ::memcmp(original.c_str(), ptr.c_str(), len)); } // // ptr(const ptr& p, unsigned o, unsigned l) // { const std::string str(len, 'X'); bufferptr original(str.c_str(), len); bufferptr ptr(original, 0, 0); EXPECT_TRUE(ptr.have_raw()); EXPECT_EQ(static_cast<instrumented_bptr&>(original).get_raw(), static_cast<instrumented_bptr&>(ptr).get_raw()); EXPECT_EQ(2, ptr.raw_nref()); EXPECT_EQ(0, ::memcmp(original.c_str(), ptr.c_str(), len)); PrCtl unset_dumpable; EXPECT_DEATH(bufferptr(original, 0, original.length() + 1), ""); EXPECT_DEATH(bufferptr(bufferptr(), 0, 0), ""); } // // ptr(ptr&& p) // { const std::string str(len, 'X'); bufferptr original(str.c_str(), len); bufferptr ptr(std::move(original)); EXPECT_TRUE(ptr.have_raw()); EXPECT_FALSE(original.have_raw()); EXPECT_EQ(0, ::memcmp(str.c_str(), ptr.c_str(), len)); EXPECT_EQ(1, ptr.raw_nref()); } } TEST(BufferPtr, operator_assign) { // // ptr& operator= (const ptr& p) // bufferptr ptr(10); ptr.copy_in(0, 3, "ABC"); char dest[1]; { bufferptr copy = ptr; copy.copy_out(1, 1, dest); ASSERT_EQ('B', dest[0]); } // // ptr& operator= (ptr&& p) // bufferptr move = std::move(ptr); { move.copy_out(1, 1, dest); ASSERT_EQ('B', dest[0]); } EXPECT_FALSE(ptr.have_raw()); } TEST(BufferPtr, assignment) { unsigned len = 17; // // override a bufferptr set with the same raw // { bufferptr original(len); bufferptr same_raw(original); unsigned offset = 5; unsigned length = len - offset; original.set_offset(offset); original.set_length(length); same_raw = original; ASSERT_EQ(2, original.raw_nref()); ASSERT_EQ(static_cast<instrumented_bptr&>(same_raw).get_raw(), static_cast<instrumented_bptr&>(original).get_raw()); ASSERT_EQ(same_raw.offset(), original.offset()); ASSERT_EQ(same_raw.length(), original.length()); } // // self assignment is a noop // { bufferptr original(len); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wself-assign-overloaded" original = original; #pragma clang diagnostic pop ASSERT_EQ(1, original.raw_nref()); ASSERT_EQ((unsigned)0, original.offset()); ASSERT_EQ(len, original.length()); } // // a copy points to the same raw // { bufferptr original(len); unsigned offset = 5; unsigned length = len - offset; original.set_offset(offset); original.set_length(length); bufferptr ptr; ptr = original; ASSERT_EQ(2, original.raw_nref()); ASSERT_EQ(static_cast<instrumented_bptr&>(ptr).get_raw(), static_cast<instrumented_bptr&>(original).get_raw()); ASSERT_EQ(original.offset(), ptr.offset()); ASSERT_EQ(original.length(), ptr.length()); } } TEST(BufferPtr, swap) { unsigned len = 17; bufferptr ptr1(len); ::memset(ptr1.c_str(), 'X', len); unsigned ptr1_offset = 4; ptr1.set_offset(ptr1_offset); unsigned ptr1_length = 3; ptr1.set_length(ptr1_length); bufferptr ptr2(len); ::memset(ptr2.c_str(), 'Y', len); unsigned ptr2_offset = 5; ptr2.set_offset(ptr2_offset); unsigned ptr2_length = 7; ptr2.set_length(ptr2_length); ptr1.swap(ptr2); EXPECT_EQ(ptr2_length, ptr1.length()); EXPECT_EQ(ptr2_offset, ptr1.offset()); EXPECT_EQ('Y', ptr1[0]); EXPECT_EQ(ptr1_length, ptr2.length()); EXPECT_EQ(ptr1_offset, ptr2.offset()); EXPECT_EQ('X', ptr2[0]); } TEST(BufferPtr, release) { unsigned len = 17; bufferptr ptr1(len); { bufferptr ptr2(ptr1); EXPECT_EQ(2, ptr1.raw_nref()); } EXPECT_EQ(1, ptr1.raw_nref()); } TEST(BufferPtr, have_raw) { { bufferptr ptr; EXPECT_FALSE(ptr.have_raw()); } { bufferptr ptr(1); EXPECT_TRUE(ptr.have_raw()); } } TEST(BufferPtr, is_n_page_sized) { { bufferptr ptr(CEPH_PAGE_SIZE); EXPECT_TRUE(ptr.is_n_page_sized()); } { bufferptr ptr(1); EXPECT_FALSE(ptr.is_n_page_sized()); } } TEST(BufferPtr, is_partial) { bufferptr a; EXPECT_FALSE(a.is_partial()); bufferptr b(10); EXPECT_FALSE(b.is_partial()); bufferptr c(b, 1, 9); EXPECT_TRUE(c.is_partial()); bufferptr d(b, 0, 9); EXPECT_TRUE(d.is_partial()); } TEST(BufferPtr, accessors) { unsigned len = 17; bufferptr ptr(len); ptr.c_str()[0] = 'X'; ptr[1] = 'Y'; const bufferptr const_ptr(ptr); EXPECT_NE((void*)nullptr, (void*)static_cast<instrumented_bptr&>(ptr).get_raw()); EXPECT_EQ('X', ptr.c_str()[0]); { bufferptr ptr; PrCtl unset_dumpable; EXPECT_DEATH(ptr.c_str(), ""); EXPECT_DEATH(ptr[0], ""); } EXPECT_EQ('X', const_ptr.c_str()[0]); { const bufferptr const_ptr; PrCtl unset_dumpable; EXPECT_DEATH(const_ptr.c_str(), ""); EXPECT_DEATH(const_ptr[0], ""); } EXPECT_EQ(len, const_ptr.length()); EXPECT_EQ((unsigned)0, const_ptr.offset()); EXPECT_EQ((unsigned)0, const_ptr.start()); EXPECT_EQ(len, const_ptr.end()); EXPECT_EQ(len, const_ptr.end()); { bufferptr ptr(len); unsigned unused = 1; ptr.set_length(ptr.length() - unused); EXPECT_EQ(unused, ptr.unused_tail_length()); } { bufferptr ptr; EXPECT_EQ((unsigned)0, ptr.unused_tail_length()); } { PrCtl unset_dumpable; EXPECT_DEATH(ptr[len], ""); EXPECT_DEATH(const_ptr[len], ""); } { const bufferptr const_ptr; PrCtl unset_dumpable; EXPECT_DEATH(const_ptr.raw_c_str(), ""); EXPECT_DEATH(const_ptr.raw_length(), ""); EXPECT_DEATH(const_ptr.raw_nref(), ""); } EXPECT_NE((const char *)NULL, const_ptr.raw_c_str()); EXPECT_EQ(len, const_ptr.raw_length()); EXPECT_EQ(2, const_ptr.raw_nref()); { bufferptr ptr(len); unsigned wasted = 1; ptr.set_length(ptr.length() - wasted * 2); ptr.set_offset(wasted); EXPECT_EQ(wasted * 2, ptr.wasted()); } } TEST(BufferPtr, cmp) { bufferptr empty; bufferptr a("A", 1); bufferptr ab("AB", 2); bufferptr af("AF", 2); bufferptr acc("ACC", 3); EXPECT_GE(-1, empty.cmp(a)); EXPECT_LE(1, a.cmp(empty)); EXPECT_GE(-1, a.cmp(ab)); EXPECT_LE(1, ab.cmp(a)); EXPECT_EQ(0, ab.cmp(ab)); EXPECT_GE(-1, ab.cmp(af)); EXPECT_LE(1, af.cmp(ab)); EXPECT_GE(-1, acc.cmp(af)); EXPECT_LE(1, af.cmp(acc)); } TEST(BufferPtr, is_zero) { char str[2] = { '\0', 'X' }; { const bufferptr ptr(buffer::create_static(2, str)); EXPECT_FALSE(ptr.is_zero()); } { const bufferptr ptr(buffer::create_static(1, str)); EXPECT_TRUE(ptr.is_zero()); } } TEST(BufferPtr, copy_out) { { const bufferptr ptr; PrCtl unset_dumpable; EXPECT_DEATH(ptr.copy_out((unsigned)0, (unsigned)0, NULL), ""); } { char in[] = "ABC"; const bufferptr ptr(buffer::create_static(strlen(in), in)); EXPECT_THROW(ptr.copy_out((unsigned)0, strlen(in) + 1, NULL), buffer::end_of_buffer); EXPECT_THROW(ptr.copy_out(strlen(in) + 1, (unsigned)0, NULL), buffer::end_of_buffer); char out[1] = { 'X' }; ptr.copy_out((unsigned)1, (unsigned)1, out); EXPECT_EQ('B', out[0]); } } TEST(BufferPtr, copy_out_bench) { for (int s=1; s<=8; s*=2) { utime_t start = ceph_clock_now(); int buflen = 1048576; int count = 1000; uint64_t v; for (int i=0; i<count; ++i) { bufferptr bp(buflen); for (int64_t j=0; j<buflen; j += s) { bp.copy_out(j, s, (char *)&v); } } utime_t end = ceph_clock_now(); cout << count << " fills of buffer len " << buflen << " with " << s << " byte copy_out in " << (end - start) << std::endl; } } TEST(BufferPtr, copy_in) { { bufferptr ptr; PrCtl unset_dumpable; EXPECT_DEATH(ptr.copy_in((unsigned)0, (unsigned)0, NULL), ""); } { char in[] = "ABCD"; bufferptr ptr(2); { PrCtl unset_dumpable; EXPECT_DEATH(ptr.copy_in((unsigned)0, strlen(in) + 1, NULL), ""); EXPECT_DEATH(ptr.copy_in(strlen(in) + 1, (unsigned)0, NULL), ""); } ptr.copy_in((unsigned)0, (unsigned)2, in); EXPECT_EQ(in[0], ptr[0]); EXPECT_EQ(in[1], ptr[1]); } } TEST(BufferPtr, copy_in_bench) { for (int s=1; s<=8; s*=2) { utime_t start = ceph_clock_now(); int buflen = 1048576; int count = 1000; for (int i=0; i<count; ++i) { bufferptr bp(buflen); for (int64_t j=0; j<buflen; j += s) { bp.copy_in(j, s, (char *)&j, false); } } utime_t end = ceph_clock_now(); cout << count << " fills of buffer len " << buflen << " with " << s << " byte copy_in in " << (end - start) << std::endl; } } TEST(BufferPtr, append) { { bufferptr ptr; PrCtl unset_dumpable; EXPECT_DEATH(ptr.append('A'), ""); EXPECT_DEATH(ptr.append("B", (unsigned)1), ""); } { bufferptr ptr(2); { PrCtl unset_dumpable; EXPECT_DEATH(ptr.append('A'), ""); EXPECT_DEATH(ptr.append("B", (unsigned)1), ""); } ptr.set_length(0); ptr.append('A'); EXPECT_EQ((unsigned)1, ptr.length()); EXPECT_EQ('A', ptr[0]); ptr.append("B", (unsigned)1); EXPECT_EQ((unsigned)2, ptr.length()); EXPECT_EQ('B', ptr[1]); } } TEST(BufferPtr, append_bench) { char src[1048576]; memset(src, 0, sizeof(src)); for (int s=4; s<=16384; s*=4) { utime_t start = ceph_clock_now(); int buflen = 1048576; int count = 4000; for (int i=0; i<count; ++i) { bufferptr bp(buflen); bp.set_length(0); for (int64_t j=0; j<buflen; j += s) { bp.append(src + j, s); } } utime_t end = ceph_clock_now(); cout << count << " fills of buffer len " << buflen << " with " << s << " byte appends in " << (end - start) << std::endl; } } TEST(BufferPtr, zero) { char str[] = "XXXX"; bufferptr ptr(buffer::create_static(strlen(str), str)); { PrCtl unset_dumpable; EXPECT_DEATH(ptr.zero(ptr.length() + 1, 0), ""); } ptr.zero(1, 1); EXPECT_EQ('X', ptr[0]); EXPECT_EQ('\0', ptr[1]); EXPECT_EQ('X', ptr[2]); ptr.zero(); EXPECT_EQ('\0', ptr[0]); } TEST(BufferPtr, ostream) { { bufferptr ptr; std::ostringstream stream; stream << ptr; EXPECT_GT(stream.str().size(), stream.str().find("buffer:ptr(0~0 no raw")); } { char str[] = "XXXX"; bufferptr ptr(buffer::create_static(strlen(str), str)); std::ostringstream stream; stream << ptr; EXPECT_GT(stream.str().size(), stream.str().find("len 4 nref 1)")); } } // // +---------+ // | +-----+ | // list ptr | | | | // +----------+ +-----+ | | | | // | append_ >-------> >--------------------> | | // | buffer | +-----+ | | | | // +----------+ ptr | | | | // | _len | list +-----+ | | | | // +----------+ +------+ ,--->+ >-----> | | // | _buffers >----> >----- +-----+ | +-----+ | // +----------+ +----^-+ \ ptr | raw | // | last_p | / `-->+-----+ | +-----+ | // +--------+-+ / + >-----> | | // | ,- ,--->+-----+ | | | | // | / ,--- | | | | // | / ,--- | | | | // +-v--+-^--+--^+-------+ | | | | // | bl | ls | p | p_off >--------------->| | | // +----+----+-----+-----+ | +-----+ | // | | off >------------->| raw | // +---------------+-----+ | | // iterator +---------+ // TEST(BufferListIterator, constructors) { // // iterator() // { buffer::list::iterator i; EXPECT_EQ((unsigned)0, i.get_off()); } // // iterator(list *l, unsigned o=0) // { bufferlist bl; bl.append("ABC", 3); { bufferlist::iterator i(&bl); EXPECT_EQ((unsigned)0, i.get_off()); EXPECT_EQ('A', *i); } { bufferlist::iterator i(&bl, 1); EXPECT_EQ('B', *i); EXPECT_EQ((unsigned)2, i.get_remaining()); } } // // iterator(list *l, unsigned o, std::list<ptr>::iterator ip, unsigned po) // not tested because of http://tracker.ceph.com/issues/4101 // // iterator(const iterator& other) // { bufferlist bl; bl.append("ABC", 3); bufferlist::iterator i(&bl, 1); bufferlist::iterator j(i); EXPECT_EQ(*i, *j); ++j; EXPECT_NE(*i, *j); EXPECT_EQ('B', *i); EXPECT_EQ('C', *j); bl.c_str()[1] = 'X'; } // // const_iterator(const iterator& other) // { bufferlist bl; bl.append("ABC", 3); bufferlist::iterator i(&bl); bufferlist::const_iterator ci(i); EXPECT_EQ(0u, ci.get_off()); EXPECT_EQ('A', *ci); } } TEST(BufferListIterator, empty_create_append_copy) { bufferlist bl, bl2, bl3, out; bl2.append("bar"); bl.swap(bl2); bl2.append("xxx"); bl.append(bl2); bl.rebuild(); bl.begin().copy(6, out); ASSERT_TRUE(out.contents_equal(bl)); } TEST(BufferListIterator, operator_assign) { bufferlist bl; bl.append("ABC", 3); bufferlist::iterator i(&bl, 1); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wself-assign-overloaded" i = i; #pragma clang diagnostic pop EXPECT_EQ('B', *i); bufferlist::iterator j; j = i; EXPECT_EQ('B', *j); } TEST(BufferListIterator, get_off) { bufferlist bl; bl.append("ABC", 3); bufferlist::iterator i(&bl, 1); EXPECT_EQ((unsigned)1, i.get_off()); } TEST(BufferListIterator, get_remaining) { bufferlist bl; bl.append("ABC", 3); bufferlist::iterator i(&bl, 1); EXPECT_EQ((unsigned)2, i.get_remaining()); } TEST(BufferListIterator, end) { bufferlist bl; { bufferlist::iterator i(&bl); EXPECT_TRUE(i.end()); } bl.append("ABC", 3); { bufferlist::iterator i(&bl); EXPECT_FALSE(i.end()); } } static void bench_bufferlistiter_deref(const size_t step, const size_t bufsize, const size_t bufnum) { const std::string buf(bufsize, 'a'); ceph::bufferlist bl; for (size_t i = 0; i < bufnum; i++) { bl.append(ceph::bufferptr(buf.c_str(), buf.size())); } utime_t start = ceph_clock_now(); bufferlist::iterator iter = bl.begin(); while (iter != bl.end()) { iter += step; } utime_t end = ceph_clock_now(); cout << bufsize * bufnum << " derefs over bl with " << bufnum << " buffers, each " << bufsize << " bytes long" << " in " << (end - start) << std::endl; } TEST(BufferListIterator, BenchDeref) { bench_bufferlistiter_deref(1, 1, 4096000); bench_bufferlistiter_deref(1, 10, 409600); bench_bufferlistiter_deref(1, 100, 40960); bench_bufferlistiter_deref(1, 1000, 4096); bench_bufferlistiter_deref(4, 1, 1024000); bench_bufferlistiter_deref(4, 10, 102400); bench_bufferlistiter_deref(4, 100, 10240); bench_bufferlistiter_deref(4, 1000, 1024); } TEST(BufferListIterator, advance) { bufferlist bl; const std::string one("ABC"); bl.append(bufferptr(one.c_str(), one.size())); const std::string two("DEF"); bl.append(bufferptr(two.c_str(), two.size())); { bufferlist::iterator i(&bl); EXPECT_THROW(i += 200u, buffer::end_of_buffer); } { bufferlist::iterator i(&bl); EXPECT_EQ('A', *i); i += 1u; EXPECT_EQ('B', *i); i += 3u; EXPECT_EQ('E', *i); } } TEST(BufferListIterator, iterate_with_empties) { ceph::bufferlist bl; EXPECT_EQ(bl.get_num_buffers(), 0u); bl.push_back(ceph::buffer::create(0)); EXPECT_EQ(bl.length(), 0u); EXPECT_EQ(bl.get_num_buffers(), 1u); encode(int64_t(42), bl); EXPECT_EQ(bl.get_num_buffers(), 2u); bl.push_back(ceph::buffer::create(0)); EXPECT_EQ(bl.get_num_buffers(), 3u); // append bufferlist with single, 0-sized ptr inside { ceph::bufferlist bl_with_empty_ptr; bl_with_empty_ptr.push_back(ceph::buffer::create(0)); EXPECT_EQ(bl_with_empty_ptr.length(), 0u); EXPECT_EQ(bl_with_empty_ptr.get_num_buffers(), 1u); bl.append(bl_with_empty_ptr); } encode(int64_t(24), bl); EXPECT_EQ(bl.get_num_buffers(), 5u); auto i = bl.cbegin(); int64_t val; decode(val, i); EXPECT_EQ(val, 42l); decode(val, i); EXPECT_EQ(val, 24l); val = 0; i.seek(sizeof(val)); decode(val, i); EXPECT_EQ(val, 24l); EXPECT_TRUE(i == bl.end()); i.seek(0); decode(val, i); EXPECT_EQ(val, 42); EXPECT_FALSE(i == bl.end()); } TEST(BufferListIterator, get_ptr_and_advance) { bufferptr a("one", 3); bufferptr b("two", 3); bufferptr c("three", 5); bufferlist bl; bl.append(a); bl.append(b); bl.append(c); const char *ptr; bufferlist::iterator p = bl.begin(); ASSERT_EQ(3u, p.get_ptr_and_advance(11u, &ptr)); ASSERT_EQ(bl.length() - 3u, p.get_remaining()); ASSERT_EQ(0, memcmp(ptr, "one", 3)); ASSERT_EQ(2u, p.get_ptr_and_advance(2u, &ptr)); ASSERT_EQ(0, memcmp(ptr, "tw", 2)); ASSERT_EQ(1u, p.get_ptr_and_advance(4u, &ptr)); ASSERT_EQ(0, memcmp(ptr, "o", 1)); ASSERT_EQ(5u, p.get_ptr_and_advance(5u, &ptr)); ASSERT_EQ(0, memcmp(ptr, "three", 5)); ASSERT_EQ(0u, p.get_remaining()); } TEST(BufferListIterator, iterator_crc32c) { bufferlist bl1; bufferlist bl2; bufferlist bl3; string s1(100, 'a'); string s2(50, 'b'); string s3(7, 'c'); string s; bl1.append(s1); bl1.append(s2); bl1.append(s3); s = s1 + s2 + s3; bl2.append(s); bufferlist::iterator it = bl2.begin(); ASSERT_EQ(bl1.crc32c(0), it.crc32c(it.get_remaining(), 0)); ASSERT_EQ(0u, it.get_remaining()); it = bl1.begin(); ASSERT_EQ(bl2.crc32c(0), it.crc32c(it.get_remaining(), 0)); bl3.append(s.substr(98, 55)); it = bl1.begin(); it += 98u; ASSERT_EQ(bl3.crc32c(0), it.crc32c(55, 0)); ASSERT_EQ(4u, it.get_remaining()); bl3.clear(); bl3.append(s.substr(98 + 55)); it = bl1.begin(); it += 98u + 55u; ASSERT_EQ(bl3.crc32c(0), it.crc32c(10, 0)); ASSERT_EQ(0u, it.get_remaining()); } TEST(BufferListIterator, seek) { bufferlist bl; bl.append("ABC", 3); bufferlist::iterator i(&bl, 1); EXPECT_EQ('B', *i); i.seek(2); EXPECT_EQ('C', *i); } TEST(BufferListIterator, operator_star) { bufferlist bl; { bufferlist::iterator i(&bl); EXPECT_THROW(*i, buffer::end_of_buffer); } bl.append("ABC", 3); { bufferlist::iterator i(&bl); EXPECT_EQ('A', *i); EXPECT_THROW(i += 200u, buffer::end_of_buffer); EXPECT_THROW(*i, buffer::end_of_buffer); } } TEST(BufferListIterator, operator_equal) { bufferlist bl; bl.append("ABC", 3); { bufferlist::iterator i(&bl); bufferlist::iterator j(&bl); EXPECT_EQ(i, j); } { bufferlist::const_iterator ci = bl.begin(); bufferlist::iterator i = bl.begin(); EXPECT_EQ(i, ci); EXPECT_EQ(ci, i); } } TEST(BufferListIterator, operator_nequal) { bufferlist bl; bl.append("ABC", 3); { bufferlist::iterator i(&bl); bufferlist::iterator j(&bl); EXPECT_NE(++i, j); } { bufferlist::const_iterator ci = bl.begin(); bufferlist::const_iterator cj = bl.begin(); ++ci; EXPECT_NE(ci, cj); bufferlist::iterator i = bl.begin(); EXPECT_NE(i, ci); EXPECT_NE(ci, i); } { // tests begin(), end(), operator++() also string s("ABC"); int i = 0; for (auto c : bl) { EXPECT_EQ(s[i++], c); } } } TEST(BufferListIterator, operator_plus_plus) { bufferlist bl; { bufferlist::iterator i(&bl); EXPECT_THROW(++i, buffer::end_of_buffer); } bl.append("ABC", 3); { bufferlist::iterator i(&bl); ++i; EXPECT_EQ('B', *i); } } TEST(BufferListIterator, get_current_ptr) { bufferlist bl; { bufferlist::iterator i(&bl); EXPECT_THROW(++i, buffer::end_of_buffer); } bl.append("ABC", 3); { bufferlist::iterator i(&bl, 1); const buffer::ptr ptr = i.get_current_ptr(); EXPECT_EQ('B', ptr[0]); EXPECT_EQ((unsigned)1, ptr.offset()); EXPECT_EQ((unsigned)2, ptr.length()); } } TEST(BufferListIterator, copy) { bufferlist bl; const char *expected = "ABC"; bl.append(expected, 3); // // void copy(unsigned len, char *dest); // { char* copy = (char*)malloc(3); ::memset(copy, 'X', 3); bufferlist::iterator i(&bl); // // demonstrates that it seeks back to offset if p == ls->end() // EXPECT_THROW(i += 200u, buffer::end_of_buffer); i.copy(2, copy); EXPECT_EQ(0, ::memcmp(copy, expected, 2)); EXPECT_EQ('X', copy[2]); i.seek(0); i.copy(3, copy); EXPECT_EQ(0, ::memcmp(copy, expected, 3)); free(copy); } // // void copy(unsigned len, char *dest) via begin(size_t offset) // { bufferlist bl; EXPECT_THROW(bl.begin((unsigned)100).copy((unsigned)100, (char*)0), buffer::end_of_buffer); const char *expected = "ABC"; bl.append(expected); char *dest = new char[2]; bl.begin(1).copy(2, dest); EXPECT_EQ(0, ::memcmp(expected + 1, dest, 2)); delete [] dest; } // // void buffer::list::iterator::copy_deep(unsigned len, ptr &dest) // { bufferptr ptr; bufferlist::iterator i(&bl); i.copy_deep(2, ptr); EXPECT_EQ((unsigned)2, ptr.length()); EXPECT_EQ('A', ptr[0]); EXPECT_EQ('B', ptr[1]); } // // void buffer::list::iterator::copy_shallow(unsigned len, ptr &dest) // { bufferptr ptr; bufferlist::iterator i(&bl); i.copy_shallow(2, ptr); EXPECT_EQ((unsigned)2, ptr.length()); EXPECT_EQ('A', ptr[0]); EXPECT_EQ('B', ptr[1]); } // // void buffer::list::iterator::copy(unsigned len, list &dest) // { bufferlist copy; bufferlist::iterator i(&bl); // // demonstrates that it seeks back to offset if p == ls->end() // EXPECT_THROW(i += 200u, buffer::end_of_buffer); i.copy(2, copy); EXPECT_EQ(0, ::memcmp(copy.c_str(), expected, 2)); i.seek(0); i.copy(3, copy); EXPECT_EQ('A', copy[0]); EXPECT_EQ('B', copy[1]); EXPECT_EQ('A', copy[2]); EXPECT_EQ('B', copy[3]); EXPECT_EQ('C', copy[4]); EXPECT_EQ((unsigned)(2 + 3), copy.length()); } // // void buffer::list::iterator::copy(unsigned len, list &dest) via begin(size_t offset) // { bufferlist bl; bufferlist dest; EXPECT_THROW(bl.begin((unsigned)100).copy((unsigned)100, dest), buffer::end_of_buffer); const char *expected = "ABC"; bl.append(expected); bl.begin(1).copy(2, dest); EXPECT_EQ(0, ::memcmp(expected + 1, dest.c_str(), 2)); } // // void buffer::list::iterator::copy_all(list &dest) // { bufferlist copy; bufferlist::iterator i(&bl); // // demonstrates that it seeks back to offset if p == ls->end() // EXPECT_THROW(i += 200u, buffer::end_of_buffer); i.copy_all(copy); EXPECT_EQ('A', copy[0]); EXPECT_EQ('B', copy[1]); EXPECT_EQ('C', copy[2]); EXPECT_EQ((unsigned)3, copy.length()); } // // void copy(unsigned len, std::string &dest) // { std::string copy; bufferlist::iterator i(&bl); // // demonstrates that it seeks back to offset if p == ls->end() // EXPECT_THROW(i += 200u, buffer::end_of_buffer); i.copy(2, copy); EXPECT_EQ(0, ::memcmp(copy.c_str(), expected, 2)); i.seek(0); i.copy(3, copy); EXPECT_EQ('A', copy[0]); EXPECT_EQ('B', copy[1]); EXPECT_EQ('A', copy[2]); EXPECT_EQ('B', copy[3]); EXPECT_EQ('C', copy[4]); EXPECT_EQ((unsigned)(2 + 3), copy.length()); } // // void copy(unsigned len, std::string &dest) via begin(size_t offset) // { bufferlist bl; std::string dest; EXPECT_THROW(bl.begin((unsigned)100).copy((unsigned)100, dest), buffer::end_of_buffer); const char *expected = "ABC"; bl.append(expected); bl.begin(1).copy(2, dest); EXPECT_EQ(0, ::memcmp(expected + 1, dest.c_str(), 2)); } } TEST(BufferListIterator, copy_in) { bufferlist bl; const char *existing = "XXX"; bl.append(existing, 3); // // void buffer::list::iterator::copy_in(unsigned len, const char *src) // { bufferlist::iterator i(&bl); // // demonstrates that it seeks back to offset if p == ls->end() // EXPECT_THROW(i += 200u, buffer::end_of_buffer); const char *expected = "ABC"; i.copy_in(3, expected); EXPECT_EQ(0, ::memcmp(bl.c_str(), expected, 3)); EXPECT_EQ('A', bl[0]); EXPECT_EQ('B', bl[1]); EXPECT_EQ('C', bl[2]); EXPECT_EQ((unsigned)3, bl.length()); } // // void copy_in(unsigned len, const char *src) via begin(size_t offset) // { bufferlist bl; bl.append("XXX"); EXPECT_THROW(bl.begin((unsigned)100).copy_in((unsigned)100, (char*)0), buffer::end_of_buffer); bl.begin(1).copy_in(2, "AB"); EXPECT_EQ(0, ::memcmp("XAB", bl.c_str(), 3)); } // // void buffer::list::iterator::copy_in(unsigned len, const list& otherl) // { bufferlist::iterator i(&bl); // // demonstrates that it seeks back to offset if p == ls->end() // EXPECT_THROW(i += 200u, buffer::end_of_buffer); bufferlist expected; expected.append("ABC", 3); i.copy_in(3, expected); EXPECT_EQ(0, ::memcmp(bl.c_str(), expected.c_str(), 3)); EXPECT_EQ('A', bl[0]); EXPECT_EQ('B', bl[1]); EXPECT_EQ('C', bl[2]); EXPECT_EQ((unsigned)3, bl.length()); } // // void copy_in(unsigned len, const list& src) via begin(size_t offset) // { bufferlist bl; bl.append("XXX"); bufferlist src; src.append("ABC"); EXPECT_THROW(bl.begin((unsigned)100).copy_in((unsigned)100, src), buffer::end_of_buffer); bl.begin(1).copy_in(2, src); EXPECT_EQ(0, ::memcmp("XAB", bl.c_str(), 3)); } } // iterator& buffer::list::const_iterator::operator++() TEST(BufferListConstIterator, operator_plus_plus) { bufferlist bl; { bufferlist::const_iterator i(&bl); EXPECT_THROW(++i, buffer::end_of_buffer); } bl.append("ABC", 3); { const bufferlist const_bl(bl); bufferlist::const_iterator i(const_bl.begin()); ++i; EXPECT_EQ('B', *i); } } TEST(BufferList, constructors) { // // list() // { bufferlist bl; ASSERT_EQ((unsigned)0, bl.length()); } // // list(unsigned prealloc) // { bufferlist bl(1); ASSERT_EQ((unsigned)0, bl.length()); bl.append('A'); ASSERT_EQ('A', bl[0]); } // // list(const list& other) // { bufferlist bl(1); bl.append('A'); ASSERT_EQ('A', bl[0]); bufferlist copy(bl); ASSERT_EQ('A', copy[0]); } // // list(list&& other) // { bufferlist bl(1); bl.append('A'); bufferlist copy = std::move(bl); ASSERT_EQ(0U, bl.length()); ASSERT_EQ(1U, copy.length()); ASSERT_EQ('A', copy[0]); } } TEST(BufferList, append_after_move) { bufferlist bl(6); bl.append("ABC", 3); EXPECT_EQ(1, bl.get_num_buffers()); bufferlist moved_to_bl(std::move(bl)); moved_to_bl.append("123", 3); // it's expected that the list(list&&) ctor will preserve the _carriage EXPECT_EQ(1, moved_to_bl.get_num_buffers()); EXPECT_EQ(0, ::memcmp("ABC123", moved_to_bl.c_str(), 6)); } void bench_bufferlist_alloc(int size, int num, int per) { utime_t start = ceph_clock_now(); for (int i=0; i<num; ++i) { bufferlist bl; for (int j=0; j<per; ++j) bl.push_back(buffer::ptr_node::create(buffer::create(size))); } utime_t end = ceph_clock_now(); cout << num << " alloc of size " << size << " in " << (end - start) << std::endl; } TEST(BufferList, BenchAlloc) { bench_bufferlist_alloc(32768, 100000, 16); bench_bufferlist_alloc(25000, 100000, 16); bench_bufferlist_alloc(16384, 100000, 16); bench_bufferlist_alloc(10000, 100000, 16); bench_bufferlist_alloc(8192, 100000, 16); bench_bufferlist_alloc(6000, 100000, 16); bench_bufferlist_alloc(4096, 100000, 16); bench_bufferlist_alloc(1024, 100000, 16); bench_bufferlist_alloc(256, 100000, 16); bench_bufferlist_alloc(32, 100000, 16); bench_bufferlist_alloc(4, 100000, 16); } /* * append_bench tests now have multiple variants: * * Version 1 tests allocate a single bufferlist during loop iteration. * Ultimately very little memory is utilized since the bufferlist immediately * drops out of scope. This was the original variant of these tests but showed * unexpected performance characteristics that appears to be tied to tcmalloc * and/or kernel behavior depending on the bufferlist size and step size. * * Version 2 tests allocate a configurable number of bufferlists that are * replaced round-robin during loop iteration. Version 2 tests are designed * to better mimic performance when multiple bufferlists are in memory at the * same time. During testing this showed more consistent and seemingly * accurate behavior across bufferlist and step sizes. */ TEST(BufferList, append_bench_with_size_hint) { std::array<char, 1048576> src = { 0, }; for (size_t step = 4; step <= 16384; step *= 4) { const utime_t start = ceph_clock_now(); constexpr size_t rounds = 4000; for (size_t r = 0; r < rounds; ++r) { ceph::bufferlist bl(std::size(src)); for (auto iter = std::begin(src); iter != std::end(src); iter = std::next(iter, step)) { bl.append(&*iter, step); } } cout << rounds << " fills of buffer len " << src.size() << " with " << step << " byte appends in " << (ceph_clock_now() - start) << std::endl; } } TEST(BufferList, append_bench_with_size_hint2) { std::array<char, 1048576> src = { 0, }; constexpr size_t rounds = 4000; constexpr int conc_bl = 400; std::vector<ceph::bufferlist*> bls(conc_bl); for (int i = 0; i < conc_bl; i++) { bls[i] = new ceph::bufferlist; } for (size_t step = 4; step <= 16384; step *= 4) { const utime_t start = ceph_clock_now(); for (size_t r = 0; r < rounds; ++r) { delete bls[r % conc_bl]; bls[r % conc_bl] = new ceph::bufferlist(std::size(src)); for (auto iter = std::begin(src); iter != std::end(src); iter = std::next(iter, step)) { bls[r % conc_bl]->append(&*iter, step); } } cout << rounds << " fills of buffer len " << src.size() << " with " << step << " byte appends in " << (ceph_clock_now() - start) << std::endl; } for (int i = 0; i < conc_bl; i++) { delete bls[i]; } } TEST(BufferList, append_bench) { std::array<char, 1048576> src = { 0, }; for (size_t step = 4; step <= 16384; step *= 4) { const utime_t start = ceph_clock_now(); constexpr size_t rounds = 4000; for (size_t r = 0; r < rounds; ++r) { ceph::bufferlist bl; for (auto iter = std::begin(src); iter != std::end(src); iter = std::next(iter, step)) { bl.append(&*iter, step); } } cout << rounds << " fills of buffer len " << src.size() << " with " << step << " byte appends in " << (ceph_clock_now() - start) << std::endl; } } TEST(BufferList, append_bench2) { std::array<char, 1048576> src = { 0, }; constexpr size_t rounds = 4000; constexpr int conc_bl = 400; std::vector<ceph::bufferlist*> bls(conc_bl); for (int i = 0; i < conc_bl; i++) { bls[i] = new ceph::bufferlist; } for (size_t step = 4; step <= 16384; step *= 4) { const utime_t start = ceph_clock_now(); for (size_t r = 0; r < rounds; ++r) { delete bls[r % conc_bl]; bls[r % conc_bl] = new ceph::bufferlist; for (auto iter = std::begin(src); iter != std::end(src); iter = std::next(iter, step)) { bls[r % conc_bl]->append(&*iter, step); } } cout << rounds << " fills of buffer len " << src.size() << " with " << step << " byte appends in " << (ceph_clock_now() - start) << std::endl; } for (int i = 0; i < conc_bl; i++) { delete bls[i]; } } TEST(BufferList, append_hole_bench) { constexpr size_t targeted_bl_size = 1048576; for (size_t step = 512; step <= 65536; step *= 2) { const utime_t start = ceph_clock_now(); constexpr size_t rounds = 80000; for (size_t r = 0; r < rounds; ++r) { ceph::bufferlist bl; while (bl.length() < targeted_bl_size) { bl.append_hole(step); } } cout << rounds << " fills of buffer len " << targeted_bl_size << " with " << step << " byte long append_hole in " << (ceph_clock_now() - start) << std::endl; } } TEST(BufferList, append_hole_bench2) { constexpr size_t targeted_bl_size = 1048576; constexpr size_t rounds = 80000; constexpr int conc_bl = 400; std::vector<ceph::bufferlist*> bls(conc_bl); for (int i = 0; i < conc_bl; i++) { bls[i] = new ceph::bufferlist; } for (size_t step = 512; step <= 65536; step *= 2) { const utime_t start = ceph_clock_now(); for (size_t r = 0; r < rounds; ++r) { delete bls[r % conc_bl]; bls[r % conc_bl] = new ceph::bufferlist; while (bls[r % conc_bl]->length() < targeted_bl_size) { bls[r % conc_bl]->append_hole(step); } } cout << rounds << " fills of buffer len " << targeted_bl_size << " with " << step << " byte long append_hole in " << (ceph_clock_now() - start) << std::endl; } for (int i = 0; i < conc_bl; i++) { delete bls[i]; } } TEST(BufferList, operator_assign_rvalue) { bufferlist from; { bufferptr ptr(2); from.append(ptr); } bufferlist to; { bufferptr ptr(4); to.append(ptr); } EXPECT_EQ((unsigned)4, to.length()); EXPECT_EQ((unsigned)1, to.get_num_buffers()); to = std::move(from); EXPECT_EQ((unsigned)2, to.length()); EXPECT_EQ((unsigned)1, to.get_num_buffers()); EXPECT_EQ((unsigned)0, from.get_num_buffers()); EXPECT_EQ((unsigned)0, from.length()); } TEST(BufferList, operator_equal) { // // list& operator= (const list& other) // bufferlist bl; bl.append("ABC", 3); { std::string dest; bl.begin(1).copy(1, dest); ASSERT_EQ('B', dest[0]); } { bufferlist copy = bl; std::string dest; copy.begin(1).copy(1, dest); ASSERT_EQ('B', dest[0]); } // // list& operator= (list&& other) // bufferlist move; move = std::move(bl); { std::string dest; move.begin(1).copy(1, dest); ASSERT_EQ('B', dest[0]); } EXPECT_TRUE(move.length()); EXPECT_TRUE(!bl.length()); } TEST(BufferList, buffers) { bufferlist bl; ASSERT_EQ((unsigned)0, bl.get_num_buffers()); bl.append('A'); ASSERT_EQ((unsigned)1, bl.get_num_buffers()); } TEST(BufferList, to_str) { { bufferlist bl; bl.append("foo"); ASSERT_EQ(bl.to_str(), string("foo")); } { bufferptr a("foobarbaz", 9); bufferptr b("123456789", 9); bufferptr c("ABCDEFGHI", 9); bufferlist bl; bl.append(a); bl.append(b); bl.append(c); ASSERT_EQ(bl.to_str(), string("foobarbaz123456789ABCDEFGHI")); } } TEST(BufferList, swap) { bufferlist b1; b1.append('A'); bufferlist b2; b2.append('B'); b1.swap(b2); std::string s1; b1.begin().copy(1, s1); ASSERT_EQ('B', s1[0]); std::string s2; b2.begin().copy(1, s2); ASSERT_EQ('A', s2[0]); } TEST(BufferList, length) { bufferlist bl; ASSERT_EQ((unsigned)0, bl.length()); bl.append('A'); ASSERT_EQ((unsigned)1, bl.length()); } TEST(BufferList, contents_equal) { // // A BB // AB B // bufferlist bl1; bl1.append("A"); bl1.append("BB"); bufferlist bl2; ASSERT_FALSE(bl1.contents_equal(bl2)); // different length bl2.append("AB"); bl2.append("B"); ASSERT_TRUE(bl1.contents_equal(bl2)); // same length same content // // ABC // bufferlist bl3; bl3.append("ABC"); ASSERT_FALSE(bl1.contents_equal(bl3)); // same length different content } TEST(BufferList, is_aligned) { const int SIMD_ALIGN = 32; { bufferlist bl; EXPECT_TRUE(bl.is_aligned(SIMD_ALIGN)); } { bufferlist bl; bufferptr ptr(buffer::create_aligned(2, SIMD_ALIGN)); ptr.set_offset(1); ptr.set_length(1); bl.append(ptr); EXPECT_FALSE(bl.is_aligned(SIMD_ALIGN)); bl.rebuild_aligned(SIMD_ALIGN); EXPECT_TRUE(bl.is_aligned(SIMD_ALIGN)); } { bufferlist bl; bufferptr ptr(buffer::create_aligned(SIMD_ALIGN + 1, SIMD_ALIGN)); ptr.set_offset(1); ptr.set_length(SIMD_ALIGN); bl.append(ptr); EXPECT_FALSE(bl.is_aligned(SIMD_ALIGN)); bl.rebuild_aligned(SIMD_ALIGN); EXPECT_TRUE(bl.is_aligned(SIMD_ALIGN)); } } TEST(BufferList, is_n_align_sized) { const int SIMD_ALIGN = 32; { bufferlist bl; EXPECT_TRUE(bl.is_n_align_sized(SIMD_ALIGN)); } { bufferlist bl; bl.append_zero(1); EXPECT_FALSE(bl.is_n_align_sized(SIMD_ALIGN)); } { bufferlist bl; bl.append_zero(SIMD_ALIGN); EXPECT_TRUE(bl.is_n_align_sized(SIMD_ALIGN)); } } TEST(BufferList, is_page_aligned) { { bufferlist bl; EXPECT_TRUE(bl.is_page_aligned()); } { bufferlist bl; bufferptr ptr(buffer::create_page_aligned(2)); ptr.set_offset(1); ptr.set_length(1); bl.append(ptr); EXPECT_FALSE(bl.is_page_aligned()); bl.rebuild_page_aligned(); EXPECT_TRUE(bl.is_page_aligned()); } { bufferlist bl; bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE + 1)); ptr.set_offset(1); ptr.set_length(CEPH_PAGE_SIZE); bl.append(ptr); EXPECT_FALSE(bl.is_page_aligned()); bl.rebuild_page_aligned(); EXPECT_TRUE(bl.is_page_aligned()); } } TEST(BufferList, is_n_page_sized) { { bufferlist bl; EXPECT_TRUE(bl.is_n_page_sized()); } { bufferlist bl; bl.append_zero(1); EXPECT_FALSE(bl.is_n_page_sized()); } { bufferlist bl; bl.append_zero(CEPH_PAGE_SIZE); EXPECT_TRUE(bl.is_n_page_sized()); } } TEST(BufferList, page_aligned_appender) { bufferlist bl; { auto a = bl.get_page_aligned_appender(5); a.append("asdf", 4); cout << bl << std::endl; ASSERT_EQ(1u, bl.get_num_buffers()); ASSERT_TRUE(bl.contents_equal("asdf", 4)); a.append("asdf", 4); for (unsigned n = 0; n < 3 * CEPH_PAGE_SIZE; ++n) { a.append("x", 1); } cout << bl << std::endl; ASSERT_EQ(1u, bl.get_num_buffers()); // verify the beginning { bufferlist t; t.substr_of(bl, 0, 10); ASSERT_TRUE(t.contents_equal("asdfasdfxx", 10)); } for (unsigned n = 0; n < 3 * CEPH_PAGE_SIZE; ++n) { a.append("y", 1); } cout << bl << std::endl; ASSERT_EQ(2u, bl.get_num_buffers()); a.append_zero(42); // ensure append_zero didn't introduce a fragmentation ASSERT_EQ(2u, bl.get_num_buffers()); // verify the end is actually zeroed { bufferlist t; t.substr_of(bl, bl.length() - 42, 42); ASSERT_TRUE(t.is_zero()); } // let's check whether appending a bufferlist directly to `bl` // doesn't fragment further C string appends via appender. { const auto& initial_back = bl.back(); { bufferlist src; src.append("abc", 3); bl.claim_append(src); // surely the extra `ptr_node` taken from `src` must get // reflected in the `bl` instance ASSERT_EQ(3u, bl.get_num_buffers()); } // moreover, the next C string-taking `append()` had to // create anoter `ptr_node` instance but... a.append("xyz", 3); ASSERT_EQ(4u, bl.get_num_buffers()); // ... it should point to the same `buffer::raw` instance // (to the same same block of memory). ASSERT_EQ(bl.back().raw_c_str(), initial_back.raw_c_str()); } // check whether it'll take the first byte only and whether // the auto-flushing works. for (unsigned n = 0; n < 10 * CEPH_PAGE_SIZE - 3; ++n) { a.append("zasdf", 1); } } { cout << bl << std::endl; ASSERT_EQ(6u, bl.get_num_buffers()); } // Verify that `page_aligned_appender` does respect the carrying // `_carriage` over multiple allocations. Although `append_zero()` // is used here, this affects other members of the append family. // This part would be crucial for e.g. `encode()`. { bl.append_zero(42); cout << bl << std::endl; ASSERT_EQ(6u, bl.get_num_buffers()); } } TEST(BufferList, rebuild_aligned_size_and_memory) { const unsigned SIMD_ALIGN = 32; const unsigned BUFFER_SIZE = 67; bufferlist bl; // These two must be concatenated into one memory + size aligned // bufferptr { bufferptr ptr(buffer::create_aligned(2, SIMD_ALIGN)); ptr.set_offset(1); ptr.set_length(1); bl.append(ptr); } { bufferptr ptr(buffer::create_aligned(BUFFER_SIZE - 1, SIMD_ALIGN)); bl.append(ptr); } // This one must be left alone { bufferptr ptr(buffer::create_aligned(BUFFER_SIZE, SIMD_ALIGN)); bl.append(ptr); } // These two must be concatenated into one memory + size aligned // bufferptr { bufferptr ptr(buffer::create_aligned(2, SIMD_ALIGN)); ptr.set_offset(1); ptr.set_length(1); bl.append(ptr); } { bufferptr ptr(buffer::create_aligned(BUFFER_SIZE - 1, SIMD_ALIGN)); bl.append(ptr); } EXPECT_FALSE(bl.is_aligned(SIMD_ALIGN)); EXPECT_FALSE(bl.is_n_align_sized(BUFFER_SIZE)); EXPECT_EQ(BUFFER_SIZE * 3, bl.length()); EXPECT_FALSE(bl.front().is_aligned(SIMD_ALIGN)); EXPECT_FALSE(bl.front().is_n_align_sized(BUFFER_SIZE)); EXPECT_EQ(5U, bl.get_num_buffers()); bl.rebuild_aligned_size_and_memory(BUFFER_SIZE, SIMD_ALIGN); EXPECT_TRUE(bl.is_aligned(SIMD_ALIGN)); EXPECT_TRUE(bl.is_n_align_sized(BUFFER_SIZE)); EXPECT_EQ(3U, bl.get_num_buffers()); { /* bug replicator, to test rebuild_aligned_size_and_memory() in the * scenario where the first bptr is both size and memory aligned and * the second is 0-length */ bl.clear(); bl.append(bufferptr{buffer::create_aligned(4096, 4096)}); bufferptr ptr(buffer::create_aligned(42, 4096)); /* bl.back().length() must be 0. offset set to 42 guarantees * the entire list is unaligned. */ bl.append(ptr, 42, 0); EXPECT_EQ(bl.get_num_buffers(), 2); EXPECT_EQ(bl.back().length(), 0); EXPECT_FALSE(bl.is_aligned(4096)); /* rebuild_aligned() calls rebuild_aligned_size_and_memory(). * we assume the rebuild always happens. */ EXPECT_TRUE(bl.rebuild_aligned(4096)); EXPECT_EQ(bl.get_num_buffers(), 1); } } TEST(BufferList, is_zero) { { bufferlist bl; EXPECT_TRUE(bl.is_zero()); } { bufferlist bl; bl.append('A'); EXPECT_FALSE(bl.is_zero()); } { bufferlist bl; bl.append_zero(1); EXPECT_TRUE(bl.is_zero()); } for (size_t i = 1; i <= 256; ++i) { bufferlist bl; bl.append_zero(i); EXPECT_TRUE(bl.is_zero()); bl.append('A'); // ensure buffer is a single, contiguous before testing bl.rebuild(); EXPECT_FALSE(bl.is_zero()); } } TEST(BufferList, clear) { bufferlist bl; unsigned len = 17; bl.append_zero(len); bl.clear(); EXPECT_EQ((unsigned)0, bl.length()); EXPECT_EQ((unsigned)0, bl.get_num_buffers()); } TEST(BufferList, push_back) { // // void push_back(ptr& bp) // { bufferlist bl; bufferptr ptr; bl.push_back(ptr); EXPECT_EQ((unsigned)0, bl.length()); EXPECT_EQ((unsigned)0, bl.get_num_buffers()); } unsigned len = 17; { bufferlist bl; bl.append('A'); bufferptr ptr(len); ptr.c_str()[0] = 'B'; bl.push_back(ptr); EXPECT_EQ((unsigned)(1 + len), bl.length()); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ('B', bl.back()[0]); const bufferptr& back_bp = bl.back(); EXPECT_EQ(static_cast<instrumented_bptr&>(ptr).get_raw(), static_cast<const instrumented_bptr&>(back_bp).get_raw()); } // // void push_back(ptr&& bp) // { bufferlist bl; bufferptr ptr; bl.push_back(std::move(ptr)); EXPECT_EQ((unsigned)0, bl.length()); EXPECT_EQ((unsigned)0, bl.get_num_buffers()); } { bufferlist bl; bl.append('A'); bufferptr ptr(len); ptr.c_str()[0] = 'B'; bl.push_back(std::move(ptr)); EXPECT_EQ((unsigned)(1 + len), bl.length()); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ('B', bl.buffers().back()[0]); EXPECT_FALSE(static_cast<instrumented_bptr&>(ptr).get_raw()); } } TEST(BufferList, is_contiguous) { bufferlist bl; EXPECT_TRUE(bl.is_contiguous()); EXPECT_EQ((unsigned)0, bl.get_num_buffers()); bl.append('A'); EXPECT_TRUE(bl.is_contiguous()); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); bufferptr ptr(1); bl.push_back(ptr); EXPECT_FALSE(bl.is_contiguous()); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); } TEST(BufferList, rebuild) { { bufferlist bl; bufferptr ptr(buffer::create_page_aligned(2)); ptr[0] = 'X'; ptr[1] = 'Y'; ptr.set_offset(1); ptr.set_length(1); bl.append(ptr); EXPECT_FALSE(bl.is_page_aligned()); bl.rebuild(); EXPECT_EQ(1U, bl.length()); EXPECT_EQ('Y', *bl.begin()); } { bufferlist bl; const std::string str(CEPH_PAGE_SIZE, 'X'); bl.append(str.c_str(), str.size()); bl.append(str.c_str(), str.size()); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); //EXPECT_TRUE(bl.is_aligned(CEPH_BUFFER_APPEND_SIZE)); bl.rebuild(); EXPECT_TRUE(bl.is_page_aligned()); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); } { bufferlist bl; char t1[] = "X"; bufferlist a2; a2.append(t1, 1); bl.rebuild(); bl.append(a2); EXPECT_EQ((unsigned)1, bl.length()); bufferlist::iterator p = bl.begin(); char dst[1]; p.copy(1, dst); EXPECT_EQ(0, memcmp(dst, "X", 1)); } } TEST(BufferList, rebuild_page_aligned) { { bufferlist bl; { bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE + 1)); ptr.set_offset(1); ptr.set_length(CEPH_PAGE_SIZE); bl.append(ptr); } EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_FALSE(bl.is_page_aligned()); bl.rebuild_page_aligned(); EXPECT_TRUE(bl.is_page_aligned()); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); } { bufferlist bl; bufferptr ptr(buffer::create_page_aligned(1)); char *p = ptr.c_str(); bl.append(ptr); bl.rebuild_page_aligned(); EXPECT_EQ(p, bl.front().c_str()); } { bufferlist bl; { bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE)); EXPECT_TRUE(ptr.is_page_aligned()); EXPECT_TRUE(ptr.is_n_page_sized()); bl.append(ptr); } { bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE + 1)); EXPECT_TRUE(ptr.is_page_aligned()); EXPECT_FALSE(ptr.is_n_page_sized()); bl.append(ptr); } { bufferptr ptr(buffer::create_page_aligned(2)); ptr.set_offset(1); ptr.set_length(1); EXPECT_FALSE(ptr.is_page_aligned()); EXPECT_FALSE(ptr.is_n_page_sized()); bl.append(ptr); } { bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE - 2)); EXPECT_TRUE(ptr.is_page_aligned()); EXPECT_FALSE(ptr.is_n_page_sized()); bl.append(ptr); } { bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE)); EXPECT_TRUE(ptr.is_page_aligned()); EXPECT_TRUE(ptr.is_n_page_sized()); bl.append(ptr); } { bufferptr ptr(buffer::create_page_aligned(CEPH_PAGE_SIZE + 1)); ptr.set_offset(1); ptr.set_length(CEPH_PAGE_SIZE); EXPECT_FALSE(ptr.is_page_aligned()); EXPECT_TRUE(ptr.is_n_page_sized()); bl.append(ptr); } EXPECT_EQ((unsigned)6, bl.get_num_buffers()); EXPECT_TRUE((bl.length() & ~CEPH_PAGE_MASK) == 0); EXPECT_FALSE(bl.is_page_aligned()); bl.rebuild_page_aligned(); EXPECT_TRUE(bl.is_page_aligned()); EXPECT_EQ((unsigned)4, bl.get_num_buffers()); } } TEST(BufferList, claim_append) { bufferlist from; { bufferptr ptr(2); from.append(ptr); } bufferlist to; { bufferptr ptr(4); to.append(ptr); } EXPECT_EQ((unsigned)4, to.length()); EXPECT_EQ((unsigned)1, to.get_num_buffers()); to.claim_append(from); EXPECT_EQ((unsigned)(4 + 2), to.length()); EXPECT_EQ((unsigned)4, to.front().length()); EXPECT_EQ((unsigned)2, to.back().length()); EXPECT_EQ((unsigned)2, to.get_num_buffers()); EXPECT_EQ((unsigned)0, from.get_num_buffers()); EXPECT_EQ((unsigned)0, from.length()); } TEST(BufferList, begin) { bufferlist bl; bl.append("ABC"); bufferlist::iterator i = bl.begin(); EXPECT_EQ('A', *i); } TEST(BufferList, end) { bufferlist bl; bl.append("AB"); bufferlist::iterator i = bl.end(); bl.append("C"); EXPECT_EQ('C', bl[i.get_off()]); } TEST(BufferList, append) { // // void append(char c); // { bufferlist bl; EXPECT_EQ((unsigned)0, bl.get_num_buffers()); bl.append('A'); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); //EXPECT_TRUE(bl.is_aligned(CEPH_BUFFER_APPEND_SIZE)); } // // void append(const char *data, unsigned len); // { bufferlist bl(CEPH_PAGE_SIZE); std::string str(CEPH_PAGE_SIZE * 2, 'X'); bl.append(str.c_str(), str.size()); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ(CEPH_PAGE_SIZE, bl.front().length()); EXPECT_EQ(CEPH_PAGE_SIZE, bl.back().length()); } // // void append(const std::string& s); // { bufferlist bl(CEPH_PAGE_SIZE); std::string str(CEPH_PAGE_SIZE * 2, 'X'); bl.append(str); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ(CEPH_PAGE_SIZE, bl.front().length()); EXPECT_EQ(CEPH_PAGE_SIZE, bl.back().length()); } // // void append(const ptr& bp); // { bufferlist bl; EXPECT_EQ((unsigned)0, bl.get_num_buffers()); EXPECT_EQ((unsigned)0, bl.length()); { bufferptr ptr; bl.append(ptr); EXPECT_EQ((unsigned)0, bl.get_num_buffers()); EXPECT_EQ((unsigned)0, bl.length()); } { bufferptr ptr(3); bl.append(ptr); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)3, bl.length()); } } // // void append(const ptr& bp, unsigned off, unsigned len); // { bufferlist bl; bl.append('A'); bufferptr back(bl.back()); bufferptr in(back); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)1, bl.length()); { PrCtl unset_dumpable; EXPECT_DEATH(bl.append(in, (unsigned)100, (unsigned)100), ""); } EXPECT_LT((unsigned)0, in.unused_tail_length()); in.append('B'); bl.append(in, back.end(), 1); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)2, bl.length()); EXPECT_EQ('B', bl[1]); } { bufferlist bl; EXPECT_EQ((unsigned)0, bl.get_num_buffers()); EXPECT_EQ((unsigned)0, bl.length()); bufferptr ptr(2); ptr.set_length(0); ptr.append("AB", 2); bl.append(ptr, 1, 1); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)1, bl.length()); } // // void append(const list& bl); // { bufferlist bl; bl.append('A'); bufferlist other; other.append('B'); bl.append(other); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ('B', bl[1]); } // // void append(std::istream& in); // { bufferlist bl; std::string expected("ABC\nDEF\n"); std::istringstream is("ABC\n\nDEF"); bl.append(is); EXPECT_EQ(0, ::memcmp(expected.c_str(), bl.c_str(), expected.size())); EXPECT_EQ(expected.size(), bl.length()); } // // void append(ptr&& bp); // { bufferlist bl; EXPECT_EQ((unsigned)0, bl.get_num_buffers()); EXPECT_EQ((unsigned)0, bl.length()); { bufferptr ptr; bl.append(std::move(ptr)); EXPECT_EQ((unsigned)0, bl.get_num_buffers()); EXPECT_EQ((unsigned)0, bl.length()); } { bufferptr ptr(3); bl.append(std::move(ptr)); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)3, bl.length()); EXPECT_FALSE(static_cast<instrumented_bptr&>(ptr).get_raw()); } } } TEST(BufferList, append_hole) { { bufferlist bl; auto filler = bl.append_hole(1); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)1, bl.length()); bl.append("BC", 2); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)3, bl.length()); const char a = 'A'; filler.copy_in((unsigned)1, &a); EXPECT_EQ((unsigned)3, bl.length()); EXPECT_EQ(0, ::memcmp("ABC", bl.c_str(), 3)); } { bufferlist bl; bl.append('A'); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)1, bl.length()); auto filler = bl.append_hole(1); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)2, bl.length()); bl.append('C'); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)3, bl.length()); const char b = 'B'; filler.copy_in((unsigned)1, &b); EXPECT_EQ((unsigned)3, bl.length()); EXPECT_EQ(0, ::memcmp("ABC", bl.c_str(), 3)); } } TEST(BufferList, append_zero) { bufferlist bl; bl.append('A'); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)1, bl.length()); bl.append_zero(1); EXPECT_EQ((unsigned)1, bl.get_num_buffers()); EXPECT_EQ((unsigned)2, bl.length()); EXPECT_EQ('\0', bl[1]); } TEST(BufferList, operator_brackets) { bufferlist bl; EXPECT_THROW(bl[1], buffer::end_of_buffer); bl.append('A'); bufferlist other; other.append('B'); bl.append(other); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ('B', bl[1]); } TEST(BufferList, c_str) { bufferlist bl; EXPECT_EQ((const char*)NULL, bl.c_str()); bl.append('A'); bufferlist other; other.append('B'); bl.append(other); EXPECT_EQ((unsigned)2, bl.get_num_buffers()); EXPECT_EQ(0, ::memcmp("AB", bl.c_str(), 2)); } TEST(BufferList, c_str_carriage) { // verify the c_str() optimization for carriage handling buffer::ptr bp("A", 1); bufferlist bl; bl.append(bp); bl.append('B'); EXPECT_EQ(2U, bl.get_num_buffers()); EXPECT_EQ(2U, bl.length()); // this should leave an empty bptr for carriage at the end of the bl bl.splice(1, 1); EXPECT_EQ(2U, bl.get_num_buffers()); EXPECT_EQ(1U, bl.length()); std::ignore = bl.c_str(); // if we have an empty bptr at the end, we don't need to rebuild EXPECT_EQ(2U, bl.get_num_buffers()); } TEST(BufferList, substr_of) { bufferlist bl; EXPECT_THROW(bl.substr_of(bl, 1, 1), buffer::end_of_buffer); const char *s[] = { "ABC", "DEF", "GHI", "JKL" }; for (unsigned i = 0; i < 4; i++) { bufferptr ptr(s[i], strlen(s[i])); bl.push_back(ptr); } EXPECT_EQ((unsigned)4, bl.get_num_buffers()); bufferlist other; other.append("TO BE CLEARED"); other.substr_of(bl, 4, 4); EXPECT_EQ((unsigned)2, other.get_num_buffers()); EXPECT_EQ((unsigned)4, other.length()); EXPECT_EQ(0, ::memcmp("EFGH", other.c_str(), 4)); } TEST(BufferList, splice) { bufferlist bl; EXPECT_THROW(bl.splice(1, 1), buffer::end_of_buffer); const char *s[] = { "ABC", "DEF", "GHI", "JKL" }; for (unsigned i = 0; i < 4; i++) { bufferptr ptr(s[i], strlen(s[i])); bl.push_back(ptr); } EXPECT_EQ((unsigned)4, bl.get_num_buffers()); bl.splice(0, 0); bufferlist other; other.append('X'); bl.splice(4, 4, &other); EXPECT_EQ((unsigned)3, other.get_num_buffers()); EXPECT_EQ((unsigned)5, other.length()); EXPECT_EQ(0, ::memcmp("XEFGH", other.c_str(), other.length())); EXPECT_EQ((unsigned)8, bl.length()); { bufferlist tmp(bl); EXPECT_EQ(0, ::memcmp("ABCDIJKL", tmp.c_str(), tmp.length())); } bl.splice(4, 4); EXPECT_EQ((unsigned)4, bl.length()); EXPECT_EQ(0, ::memcmp("ABCD", bl.c_str(), bl.length())); { bl.clear(); bufferptr ptr1("0123456789", 10); bl.push_back(ptr1); bufferptr ptr2("abcdefghij", 10); bl.append(ptr2, 5, 5); other.clear(); bl.splice(10, 4, &other); EXPECT_EQ((unsigned)11, bl.length()); EXPECT_EQ(0, ::memcmp("fghi", other.c_str(), other.length())); } } TEST(BufferList, write) { std::ostringstream stream; bufferlist bl; bl.append("ABC"); bl.write(1, 2, stream); EXPECT_EQ("BC", stream.str()); } TEST(BufferList, encode_base64) { bufferlist bl; bl.append("ABCD"); bufferlist other; bl.encode_base64(other); const char *expected = "QUJDRA=="; EXPECT_EQ(0, ::memcmp(expected, other.c_str(), strlen(expected))); } TEST(BufferList, decode_base64) { bufferlist bl; bl.append("QUJDRA=="); bufferlist other; other.decode_base64(bl); const char *expected = "ABCD"; EXPECT_EQ(0, ::memcmp(expected, other.c_str(), strlen(expected))); bufferlist malformed; malformed.append("QUJDRA"); EXPECT_THROW(other.decode_base64(malformed), buffer::malformed_input); } TEST(BufferList, hexdump) { bufferlist bl; std::ostringstream stream; bl.append("013245678901234\0006789012345678901234", 32); bl.hexdump(stream); EXPECT_EQ("00000000 30 31 33 32 34 35 36 37 38 39 30 31 32 33 34 00 |013245678901234.|\n" "00000010 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 |6789012345678901|\n" "00000020\n", stream.str()); } TEST(BufferList, read_file) { std::string error; bufferlist bl; ::unlink(FILENAME); EXPECT_EQ(-ENOENT, bl.read_file("UNLIKELY", &error)); snprintf(cmd, sizeof(cmd), "echo ABC> %s", FILENAME); EXPECT_EQ(0, ::system(cmd)); #ifndef _WIN32 snprintf(cmd, sizeof(cmd), "chmod 0 %s", FILENAME); EXPECT_EQ(0, ::system(cmd)); if (getuid() != 0) { EXPECT_EQ(-EACCES, bl.read_file(FILENAME, &error)); } snprintf(cmd, sizeof(cmd), "chmod +r %s", FILENAME); EXPECT_EQ(0, ::system(cmd)); #endif /* _WIN32 */ EXPECT_EQ(0, bl.read_file(FILENAME, &error)); ::unlink(FILENAME); EXPECT_EQ((unsigned)4, bl.length()); std::string actual(bl.c_str(), bl.length()); EXPECT_EQ("ABC\n", actual); } TEST(BufferList, read_fd) { unsigned len = 4; ::unlink(FILENAME); snprintf(cmd, sizeof(cmd), "echo ABC > %s", FILENAME); EXPECT_EQ(0, ::system(cmd)); int fd = -1; bufferlist bl; EXPECT_EQ(-EBADF, bl.read_fd(fd, len)); fd = ::open(FILENAME, O_RDONLY); ASSERT_NE(-1, fd); EXPECT_EQ(len, (unsigned)bl.read_fd(fd, len)); //EXPECT_EQ(CEPH_BUFFER_APPEND_SIZE - len, bl.front().unused_tail_length()); EXPECT_EQ(len, bl.length()); ::close(fd); ::unlink(FILENAME); } TEST(BufferList, write_file) { ::unlink(FILENAME); int mode = 0600; bufferlist bl; EXPECT_EQ(-ENOENT, bl.write_file("un/like/ly", mode)); bl.append("ABC"); EXPECT_EQ(0, bl.write_file(FILENAME, mode)); struct stat st; memset(&st, 0, sizeof(st)); ASSERT_EQ(0, ::stat(FILENAME, &st)); #ifndef _WIN32 EXPECT_EQ((unsigned)(mode | S_IFREG), st.st_mode); #endif ::unlink(FILENAME); } TEST(BufferList, write_fd) { ::unlink(FILENAME); int fd = ::open(FILENAME, O_WRONLY|O_CREAT|O_TRUNC, 0600); ASSERT_NE(-1, fd); bufferlist bl; for (unsigned i = 0; i < IOV_MAX * 2; i++) { bufferptr ptr("A", 1); bl.push_back(ptr); } EXPECT_EQ(0, bl.write_fd(fd)); ::close(fd); struct stat st; memset(&st, 0, sizeof(st)); ASSERT_EQ(0, ::stat(FILENAME, &st)); EXPECT_EQ(IOV_MAX * 2, st.st_size); ::unlink(FILENAME); } TEST(BufferList, write_fd_offset) { ::unlink(FILENAME); int fd = ::open(FILENAME, O_WRONLY|O_CREAT|O_TRUNC, 0600); ASSERT_NE(-1, fd); bufferlist bl; for (unsigned i = 0; i < IOV_MAX * 2; i++) { bufferptr ptr("A", 1); bl.push_back(ptr); } uint64_t offset = 200; EXPECT_EQ(0, bl.write_fd(fd, offset)); ::close(fd); struct stat st; memset(&st, 0, sizeof(st)); ASSERT_EQ(0, ::stat(FILENAME, &st)); EXPECT_EQ(IOV_MAX * 2 + offset, (unsigned)st.st_size); ::unlink(FILENAME); } TEST(BufferList, crc32c) { bufferlist bl; __u32 crc = 0; bl.append("A"); crc = bl.crc32c(crc); EXPECT_EQ((unsigned)0xB3109EBF, crc); crc = bl.crc32c(crc); EXPECT_EQ((unsigned)0x5FA5C0CC, crc); } TEST(BufferList, crc32c_append) { bufferlist bl1; bufferlist bl2; for (int j = 0; j < 200; ++j) { bufferlist bl; for (int i = 0; i < 200; ++i) { char x = rand(); bl.append(x); bl1.append(x); } bl.crc32c(rand()); // mess with the cached bufferptr crc values bl2.append(bl); } ASSERT_EQ(bl1.crc32c(0), bl2.crc32c(0)); } TEST(BufferList, crc32c_zeros) { char buffer[4*1024]; for (size_t i=0; i < sizeof(buffer); i++) { buffer[i] = i; } bufferlist bla; bufferlist blb; for (size_t j=0; j < 1000; j++) { bufferptr a(buffer, sizeof(buffer)); bla.push_back(a); uint32_t crca = bla.crc32c(111); blb.push_back(a); uint32_t crcb = ceph_crc32c(111, (unsigned char*)blb.c_str(), blb.length()); EXPECT_EQ(crca, crcb); } } TEST(BufferList, crc32c_append_perf) { int len = 256 * 1024 * 1024; bufferptr a(len); bufferptr b(len); bufferptr c(len); bufferptr d(len); std::cout << "populating large buffers (a, b=c=d)" << std::endl; char *pa = a.c_str(); char *pb = b.c_str(); char *pc = c.c_str(); char *pd = c.c_str(); for (int i=0; i<len; i++) { pa[i] = (i & 0xff) ^ 73; pb[i] = (i & 0xff) ^ 123; pc[i] = (i & 0xff) ^ 123; pd[i] = (i & 0xff) ^ 123; } // track usage of cached crcs buffer::track_cached_crc(true); [[maybe_unused]] int base_cached = buffer::get_cached_crc(); [[maybe_unused]] int base_cached_adjusted = buffer::get_cached_crc_adjusted(); bufferlist bla; bla.push_back(a); bufferlist blb; blb.push_back(b); { utime_t start = ceph_clock_now(); uint32_t r = bla.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "a.crc32c(0) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 1138817026u); } ceph_assert(buffer::get_cached_crc() == 0 + base_cached); { utime_t start = ceph_clock_now(); uint32_t r = bla.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "a.crc32c(0) (again) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 1138817026u); } ceph_assert(buffer::get_cached_crc() == 1 + base_cached); { utime_t start = ceph_clock_now(); uint32_t r = bla.crc32c(5); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "a.crc32c(5) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 3239494520u); } ceph_assert(buffer::get_cached_crc() == 1 + base_cached); ceph_assert(buffer::get_cached_crc_adjusted() == 1 + base_cached_adjusted); { utime_t start = ceph_clock_now(); uint32_t r = bla.crc32c(5); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "a.crc32c(5) (again) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 3239494520u); } ceph_assert(buffer::get_cached_crc() == 1 + base_cached); ceph_assert(buffer::get_cached_crc_adjusted() == 2 + base_cached_adjusted); { utime_t start = ceph_clock_now(); uint32_t r = blb.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "b.crc32c(0) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 2481791210u); } ceph_assert(buffer::get_cached_crc() == 1 + base_cached); { utime_t start = ceph_clock_now(); uint32_t r = blb.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)len / (float)(1024*1024) / (float)(end - start); std::cout << "b.crc32c(0) (again)= " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 2481791210u); } ceph_assert(buffer::get_cached_crc() == 2 + base_cached); bufferlist ab; ab.push_back(a); ab.push_back(b); { utime_t start = ceph_clock_now(); uint32_t r = ab.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)ab.length() / (float)(1024*1024) / (float)(end - start); std::cout << "ab.crc32c(0) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 2988268779u); } ceph_assert(buffer::get_cached_crc() == 3 + base_cached); ceph_assert(buffer::get_cached_crc_adjusted() == 3 + base_cached_adjusted); bufferlist ac; ac.push_back(a); ac.push_back(c); { utime_t start = ceph_clock_now(); uint32_t r = ac.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)ac.length() / (float)(1024*1024) / (float)(end - start); std::cout << "ac.crc32c(0) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 2988268779u); } ceph_assert(buffer::get_cached_crc() == 4 + base_cached); ceph_assert(buffer::get_cached_crc_adjusted() == 3 + base_cached_adjusted); bufferlist ba; ba.push_back(b); ba.push_back(a); { utime_t start = ceph_clock_now(); uint32_t r = ba.crc32c(0); utime_t end = ceph_clock_now(); float rate = (float)ba.length() / (float)(1024*1024) / (float)(end - start); std::cout << "ba.crc32c(0) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 169240695u); } ceph_assert(buffer::get_cached_crc() == 5 + base_cached); ceph_assert(buffer::get_cached_crc_adjusted() == 4 + base_cached_adjusted); { utime_t start = ceph_clock_now(); uint32_t r = ba.crc32c(5); utime_t end = ceph_clock_now(); float rate = (float)ba.length() / (float)(1024*1024) / (float)(end - start); std::cout << "ba.crc32c(5) = " << r << " at " << rate << " MB/sec" << std::endl; ASSERT_EQ(r, 1265464778u); } ceph_assert(buffer::get_cached_crc() == 5 + base_cached); ceph_assert(buffer::get_cached_crc_adjusted() == 6 + base_cached_adjusted); cout << "crc cache hits (same start) = " << buffer::get_cached_crc() << std::endl; cout << "crc cache hits (adjusted) = " << buffer::get_cached_crc_adjusted() << std::endl; } TEST(BufferList, compare) { bufferlist a; a.append("A"); bufferlist ab; // AB in segments ab.append(bufferptr("A", 1)); ab.append(bufferptr("B", 1)); bufferlist ac; ac.append("AC"); // // bool operator>(bufferlist& l, bufferlist& r) // ASSERT_FALSE(a > ab); ASSERT_TRUE(ab > a); ASSERT_TRUE(ac > ab); ASSERT_FALSE(ab > ac); ASSERT_FALSE(ab > ab); // // bool operator>=(bufferlist& l, bufferlist& r) // ASSERT_FALSE(a >= ab); ASSERT_TRUE(ab >= a); ASSERT_TRUE(ac >= ab); ASSERT_FALSE(ab >= ac); ASSERT_TRUE(ab >= ab); // // bool operator<(bufferlist& l, bufferlist& r) // ASSERT_TRUE(a < ab); ASSERT_FALSE(ab < a); ASSERT_FALSE(ac < ab); ASSERT_TRUE(ab < ac); ASSERT_FALSE(ab < ab); // // bool operator<=(bufferlist& l, bufferlist& r) // ASSERT_TRUE(a <= ab); ASSERT_FALSE(ab <= a); ASSERT_FALSE(ac <= ab); ASSERT_TRUE(ab <= ac); ASSERT_TRUE(ab <= ab); // // bool operator==(bufferlist &l, bufferlist &r) // ASSERT_FALSE(a == ab); ASSERT_FALSE(ac == ab); ASSERT_TRUE(ab == ab); } TEST(BufferList, ostream) { std::ostringstream stream; bufferlist bl; const char *s[] = { "ABC", "DEF" }; for (unsigned i = 0; i < 2; i++) { bufferptr ptr(s[i], strlen(s[i])); bl.push_back(ptr); } stream << bl; std::cerr << stream.str() << std::endl; EXPECT_GT(stream.str().size(), stream.str().find("list(len=6,")); EXPECT_GT(stream.str().size(), stream.str().find("len 3 nref 1),\n")); EXPECT_GT(stream.str().size(), stream.str().find("len 3 nref 1)\n")); } TEST(BufferList, zero) { // // void zero() // { bufferlist bl; bl.append('A'); EXPECT_EQ('A', bl[0]); bl.zero(); EXPECT_EQ('\0', bl[0]); } // // void zero(unsigned o, unsigned l) // const char *s[] = { "ABC", "DEF", "GHI", "KLM" }; { bufferlist bl; bufferptr ptr(s[0], strlen(s[0])); bl.push_back(ptr); bl.zero((unsigned)0, (unsigned)1); EXPECT_EQ(0, ::memcmp("\0BC", bl.c_str(), 3)); } { bufferlist bl; for (unsigned i = 0; i < 4; i++) { bufferptr ptr(s[i], strlen(s[i])); bl.push_back(ptr); } { PrCtl unset_dumpable; EXPECT_DEATH(bl.zero((unsigned)0, (unsigned)2000), ""); } bl.zero((unsigned)2, (unsigned)5); EXPECT_EQ(0, ::memcmp("AB\0\0\0\0\0HIKLM", bl.c_str(), 9)); } { bufferlist bl; for (unsigned i = 0; i < 4; i++) { bufferptr ptr(s[i], strlen(s[i])); bl.push_back(ptr); } bl.zero((unsigned)3, (unsigned)3); EXPECT_EQ(0, ::memcmp("ABC\0\0\0GHIKLM", bl.c_str(), 9)); } { bufferlist bl; bufferptr ptr1(4); bufferptr ptr2(4); memset(ptr1.c_str(), 'a', 4); memset(ptr2.c_str(), 'b', 4); bl.append(ptr1); bl.append(ptr2); bl.zero((unsigned)2, (unsigned)4); EXPECT_EQ(0, ::memcmp("aa\0\0\0\0bb", bl.c_str(), 8)); } } TEST(BufferList, EmptyAppend) { bufferlist bl; bufferptr ptr; bl.push_back(ptr); ASSERT_EQ(bl.begin().end(), 1); } TEST(BufferList, InternalCarriage) { ceph::bufferlist bl; EXPECT_EQ(bl.get_num_buffers(), 0u); encode(int64_t(42), bl); EXPECT_EQ(bl.get_num_buffers(), 1u); { ceph::bufferlist bl_with_foo; bl_with_foo.append("foo", 3); EXPECT_EQ(bl_with_foo.length(), 3u); EXPECT_EQ(bl_with_foo.get_num_buffers(), 1u); bl.append(bl_with_foo); EXPECT_EQ(bl.get_num_buffers(), 2u); } encode(int64_t(24), bl); EXPECT_EQ(bl.get_num_buffers(), 3u); } TEST(BufferList, ContiguousAppender) { ceph::bufferlist bl; EXPECT_EQ(bl.get_num_buffers(), 0u); // we expect a flush in ~contiguous_appender { auto ap = bl.get_contiguous_appender(100); denc(int64_t(42), ap); EXPECT_EQ(bl.get_num_buffers(), 1u); // append bufferlist with single ptr inside. This should // commit changes to bl::_len and the underlying bp::len. { ceph::bufferlist bl_with_foo; bl_with_foo.append("foo", 3); EXPECT_EQ(bl_with_foo.length(), 3u); EXPECT_EQ(bl_with_foo.get_num_buffers(), 1u); ap.append(bl_with_foo); // 3 as the ap::append(const bl&) splits the bp with free // space. EXPECT_EQ(bl.get_num_buffers(), 3u); } denc(int64_t(24), ap); EXPECT_EQ(bl.get_num_buffers(), 3u); EXPECT_EQ(bl.length(), sizeof(int64_t) + 3u); } EXPECT_EQ(bl.length(), 2u * sizeof(int64_t) + 3u); } TEST(BufferList, TestPtrAppend) { bufferlist bl; char correct[MAX_TEST]; int curpos = 0; int length = random() % 5 > 0 ? random() % 1000 : 0; while (curpos + length < MAX_TEST) { if (!length) { bufferptr ptr; bl.push_back(ptr); } else { char *current = correct + curpos; for (int i = 0; i < length; ++i) { char next = random() % 255; correct[curpos++] = next; } bufferptr ptr(current, length); bl.append(ptr); } length = random() % 5 > 0 ? random() % 1000 : 0; } ASSERT_EQ(memcmp(bl.c_str(), correct, curpos), 0); } TEST(BufferList, TestDirectAppend) { bufferlist bl; char correct[MAX_TEST]; int curpos = 0; int length = random() % 5 > 0 ? random() % 1000 : 0; while (curpos + length < MAX_TEST) { char *current = correct + curpos; for (int i = 0; i < length; ++i) { char next = random() % 255; correct[curpos++] = next; } bl.append(current, length); length = random() % 5 > 0 ? random() % 1000 : 0; } ASSERT_EQ(memcmp(bl.c_str(), correct, curpos), 0); } TEST(BufferList, TestCopyAll) { const static size_t BIG_SZ = 10737414; std::shared_ptr <unsigned char> big( (unsigned char*)malloc(BIG_SZ), free); unsigned char c = 0; for (size_t i = 0; i < BIG_SZ; ++i) { big.get()[i] = c++; } bufferlist bl; bl.append((const char*)big.get(), BIG_SZ); bufferlist::iterator i = bl.begin(); bufferlist bl2; i.copy_all(bl2); ASSERT_EQ(bl2.length(), BIG_SZ); std::shared_ptr <unsigned char> big2( (unsigned char*)malloc(BIG_SZ), free); bl2.begin().copy(BIG_SZ, (char*)big2.get()); ASSERT_EQ(memcmp(big.get(), big2.get(), BIG_SZ), 0); } TEST(BufferList, InvalidateCrc) { const static size_t buffer_size = 262144; std::shared_ptr <unsigned char> big( (unsigned char*)malloc(buffer_size), free); unsigned char c = 0; char* ptr = (char*) big.get(); char* inptr; for (size_t i = 0; i < buffer_size; ++i) { ptr[i] = c++; } bufferlist bl; // test for crashes (shouldn't crash) bl.invalidate_crc(); // put data into bufferlist bl.append((const char*)big.get(), buffer_size); // get its crc __u32 crc = bl.crc32c(0); // modify data in bl without its knowledge inptr = (char*) bl.c_str(); c = 0; for (size_t i = 0; i < buffer_size; ++i) { inptr[i] = c--; } // make sure data in bl are now different than in big EXPECT_NE(memcmp((void*) ptr, (void*) inptr, buffer_size), 0); // crc should remain the same __u32 new_crc = bl.crc32c(0); EXPECT_EQ(crc, new_crc); // force crc invalidate, check if it is updated bl.invalidate_crc(); EXPECT_NE(crc, bl.crc32c(0)); } TEST(BufferList, TestIsProvidedBuffer) { char buff[100]; bufferlist bl; bl.push_back(buffer::create_static(100, buff)); ASSERT_TRUE(bl.is_provided_buffer(buff)); bl.append_zero(100); ASSERT_FALSE(bl.is_provided_buffer(buff)); } TEST(BufferList, DISABLED_DanglingLastP) { bufferlist bl; { // previously we're using the unsharable buffer type to distinguish // the last_p-specific problem from the generic crosstalk issues we // had since the very beginning: // https://gist.github.com/rzarzynski/aed18372e88aed392101adac3bd87bbc // this is no longer possible as `buffer::create_unsharable()` has // been dropped. bufferptr bp(buffer::create(10)); bp.copy_in(0, 3, "XXX"); bl.push_back(std::move(bp)); EXPECT_EQ(0, ::memcmp("XXX", bl.c_str(), 3)); // let `copy_in` to set `last_p` member of bufferlist bl.begin().copy_in(2, "AB"); EXPECT_EQ(0, ::memcmp("ABX", bl.c_str(), 3)); } bufferlist empty; // before the fix this would have left `last_p` unchanged leading to // the dangerous dangling state – keep in mind that the initial, // unsharable bptr will be freed. bl = const_cast<const bufferlist&>(empty); bl.append("123"); // we must continue from where the previous copy_in had finished. // Otherwise `bl::copy_in` will call `seek()` and refresh `last_p`. bl.begin(2).copy_in(1, "C"); EXPECT_EQ(0, ::memcmp("12C", bl.c_str(), 3)); } TEST(BufferHash, all) { { bufferlist bl; bl.append("A"); bufferhash hash; EXPECT_EQ((unsigned)0, hash.digest()); hash.update(bl); EXPECT_EQ((unsigned)0xB3109EBF, hash.digest()); hash.update(bl); EXPECT_EQ((unsigned)0x5FA5C0CC, hash.digest()); } { bufferlist bl; bl.append("A"); bufferhash hash; EXPECT_EQ((unsigned)0, hash.digest()); bufferhash& returned_hash = hash << bl; EXPECT_EQ(&returned_hash, &hash); EXPECT_EQ((unsigned)0xB3109EBF, hash.digest()); } } /* * Local Variables: * compile-command: "cd .. ; make unittest_bufferlist && * ulimit -s unlimited ; valgrind \ * --max-stackframe=20000000 --tool=memcheck \ * ./unittest_bufferlist # --gtest_filter=BufferList.constructors" * End: */
80,980
25.258431
98
cc
null
ceph-main/src/test/buildtest_skeleton.cc
#include "common/common_init.h" /* This program exists to test that we can build libcommon without * referencing g_ceph_context * * This program will go away as soon as we actually don't use g_ceph_context in * more programs. Obviously, at that point, those programs will provide an * equivalent test. */ int main(int argc, char **argv) { return 0; }
360
24.785714
79
cc
null
ceph-main/src/test/ceph_argparse.cc
// -*- 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) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/ceph_argparse.h" #include "gtest/gtest.h" #include <vector> #include "include/stringify.h" using namespace std; /* Holds a std::vector with C-strings. * Will free() them properly in the destructor. * * Note: the ceph_argparse functions modify the vector, removing elements as * they find them. So we keep a parallel vector, orig, to make sure that we * never forget to delete a string. */ class VectorContainer { public: explicit VectorContainer(const char** arr_) { for (const char **a = arr_; *a; ++a) { const char *str = (const char*)strdup(*a); arr.push_back(str); orig.push_back(str); } } ~VectorContainer() { for (std::vector<const char*>::iterator i = orig.begin(); i != orig.end(); ++i) { free((void*)*i); } } void refresh() { arr.assign(orig.begin(), orig.end()); } std::vector < const char* > arr; private: std::vector < const char* > orig; }; TEST(CephArgParse, SimpleArgParse) { const char *BAR5[] = { "./myprog", "--bar", "5", NULL }; const char *FOO[] = { "./myprog", "--foo", "--baz", NULL }; const char *NONE[] = { "./myprog", NULL }; bool found_foo = false; std::string found_bar; VectorContainer bar5(BAR5); for (std::vector<const char*>::iterator i = bar5.arr.begin(); i != bar5.arr.end(); ) { if (ceph_argparse_flag(bar5.arr, i, "--foo", (char*)NULL)) { found_foo = true; } else if (ceph_argparse_witharg(bar5.arr, i, &found_bar, "--bar", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_foo, false); ASSERT_EQ(found_bar, "5"); found_foo = false; found_bar = ""; bool baz_found = false; std::string found_baz = ""; VectorContainer foo(FOO); ostringstream err; for (std::vector<const char*>::iterator i = foo.arr.begin(); i != foo.arr.end(); ) { if (ceph_argparse_flag(foo.arr, i, "--foo", (char*)NULL)) { found_foo = true; } else if (ceph_argparse_witharg(foo.arr, i, &found_bar, "--bar", (char*)NULL)) { } else if (ceph_argparse_witharg(foo.arr, i, &found_baz, err, "--baz", (char*)NULL)) { ASSERT_NE(string(""), err.str()); baz_found = true; } else ++i; } ASSERT_EQ(found_foo, true); ASSERT_EQ(found_bar, ""); ASSERT_EQ(baz_found, true); ASSERT_EQ(found_baz, ""); found_foo = false; found_bar = ""; VectorContainer none(NONE); for (std::vector<const char*>::iterator i = none.arr.begin(); i != none.arr.end(); ) { if (ceph_argparse_flag(none.arr, i, "--foo", (char*)NULL)) { found_foo = true; } else if (ceph_argparse_witharg(none.arr, i, &found_bar, "--bar", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_foo, false); ASSERT_EQ(found_bar, ""); } TEST(CephArgParse, DoubleDash) { const char *ARGS[] = { "./myprog", "--foo", "5", "--", "--bar", "6", NULL }; int foo = -1, bar = -1; VectorContainer args(ARGS); for (std::vector<const char*>::iterator i = args.arr.begin(); i != args.arr.end(); ) { std::string myarg; if (ceph_argparse_double_dash(args.arr, i)) { break; } else if (ceph_argparse_witharg(args.arr, i, &myarg, "--foo", (char*)NULL)) { foo = atoi(myarg.c_str()); } else if (ceph_argparse_witharg(args.arr, i, &myarg, "--bar", (char*)NULL)) { bar = atoi(myarg.c_str()); } else ++i; } ASSERT_EQ(foo, 5); ASSERT_EQ(bar, -1); } TEST(CephArgParse, WithDashesAndUnderscores) { const char *BAZSTUFF1[] = { "./myprog", "--goo", "--baz-stuff", "50", "--end", NULL }; const char *BAZSTUFF2[] = { "./myprog", "--goo2", "--baz_stuff", "50", NULL }; const char *BAZSTUFF3[] = { "./myprog", "--goo2", "--baz-stuff=50", "50", NULL }; const char *BAZSTUFF4[] = { "./myprog", "--goo2", "--baz_stuff=50", "50", NULL }; const char *NONE1[] = { "./myprog", NULL }; const char *NONE2[] = { "./myprog", "--goo2", "--baz_stuff2", "50", NULL }; const char *NONE3[] = { "./myprog", "--goo2", "__baz_stuff", "50", NULL }; // as flag std::string found_baz; VectorContainer bazstuff1(BAZSTUFF1); for (std::vector<const char*>::iterator i = bazstuff1.arr.begin(); i != bazstuff1.arr.end(); ) { if (ceph_argparse_flag(bazstuff1.arr, i, "--baz-stuff", (char*)NULL)) { found_baz = "true"; } else ++i; } ASSERT_EQ(found_baz, "true"); // as flag found_baz = ""; VectorContainer bazstuff2(BAZSTUFF2); for (std::vector<const char*>::iterator i = bazstuff2.arr.begin(); i != bazstuff2.arr.end(); ) { if (ceph_argparse_flag(bazstuff2.arr, i, "--baz-stuff", (char*)NULL)) { found_baz = "true"; } else ++i; } ASSERT_EQ(found_baz, "true"); // with argument found_baz = ""; bazstuff1.refresh(); for (std::vector<const char*>::iterator i = bazstuff1.arr.begin(); i != bazstuff1.arr.end(); ) { if (ceph_argparse_witharg(bazstuff1.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, "50"); // with argument found_baz = ""; bazstuff2.refresh(); for (std::vector<const char*>::iterator i = bazstuff2.arr.begin(); i != bazstuff2.arr.end(); ) { if (ceph_argparse_witharg(bazstuff2.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, "50"); // with argument found_baz = ""; VectorContainer bazstuff3(BAZSTUFF3); for (std::vector<const char*>::iterator i = bazstuff3.arr.begin(); i != bazstuff3.arr.end(); ) { if (ceph_argparse_witharg(bazstuff3.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, "50"); // with argument found_baz = ""; VectorContainer bazstuff4(BAZSTUFF4); for (std::vector<const char*>::iterator i = bazstuff4.arr.begin(); i != bazstuff4.arr.end(); ) { if (ceph_argparse_witharg(bazstuff4.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, "50"); // not found found_baz = ""; VectorContainer none1(NONE1); for (std::vector<const char*>::iterator i = none1.arr.begin(); i != none1.arr.end(); ) { if (ceph_argparse_flag(none1.arr, i, "--baz-stuff", (char*)NULL)) { found_baz = "true"; } else if (ceph_argparse_witharg(none1.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, ""); // not found found_baz = ""; VectorContainer none2(NONE2); for (std::vector<const char*>::iterator i = none2.arr.begin(); i != none2.arr.end(); ) { if (ceph_argparse_flag(none2.arr, i, "--baz-stuff", (char*)NULL)) { found_baz = "true"; } else if (ceph_argparse_witharg(none2.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, ""); // not found found_baz = ""; VectorContainer none3(NONE3); for (std::vector<const char*>::iterator i = none3.arr.begin(); i != none3.arr.end(); ) { if (ceph_argparse_flag(none3.arr, i, "--baz-stuff", (char*)NULL)) { found_baz = "true"; } else if (ceph_argparse_witharg(none3.arr, i, &found_baz, "--baz-stuff", (char*)NULL)) { } else ++i; } ASSERT_EQ(found_baz, ""); } TEST(CephArgParse, WithFloat) { const char *BAZSTUFF1[] = { "./myprog", "--foo", "50.5", "--bar", "52", NULL }; VectorContainer bazstuff1(BAZSTUFF1); ostringstream err; float foo; int bar = -1; for (std::vector<const char*>::iterator i = bazstuff1.arr.begin(); i != bazstuff1.arr.end(); ) { if (ceph_argparse_double_dash(bazstuff1.arr, i)) { break; } else if (ceph_argparse_witharg(bazstuff1.arr, i, &foo, err, "--foo", (char*)NULL)) { ASSERT_EQ(string(""), err.str()); } else if (ceph_argparse_witharg(bazstuff1.arr, i, &bar, err, "--bar", (char*)NULL)) { ASSERT_EQ(string(""), err.str()); } else { ++i; } } ASSERT_EQ(foo, 50.5); ASSERT_EQ(bar, 52); } TEST(CephArgParse, WithInt) { const char *BAZSTUFF1[] = { "./myprog", "--foo", "50", "--bar", "52", NULL }; const char *BAZSTUFF2[] = { "./myprog", "--foo", "--bar", "52", NULL }; const char *BAZSTUFF3[] = { "./myprog", "--foo", "40", "--", "--bar", "42", NULL }; // normal test VectorContainer bazstuff1(BAZSTUFF1); ostringstream err; int foo = -1, bar = -1; for (std::vector<const char*>::iterator i = bazstuff1.arr.begin(); i != bazstuff1.arr.end(); ) { if (ceph_argparse_double_dash(bazstuff1.arr, i)) { break; } else if (ceph_argparse_witharg(bazstuff1.arr, i, &foo, err, "--foo", (char*)NULL)) { ASSERT_EQ(string(""), err.str()); } else if (ceph_argparse_witharg(bazstuff1.arr, i, &bar, err, "--bar", (char*)NULL)) { ASSERT_EQ(string(""), err.str()); } else { ++i; } } ASSERT_EQ(foo, 50); ASSERT_EQ(bar, 52); // parse error test VectorContainer bazstuff2(BAZSTUFF2); ostringstream err2; for (std::vector<const char*>::iterator i = bazstuff2.arr.begin(); i != bazstuff2.arr.end(); ) { if (ceph_argparse_double_dash(bazstuff2.arr, i)) { break; } else if (ceph_argparse_witharg(bazstuff2.arr, i, &foo, err2, "--foo", (char*)NULL)) { ASSERT_NE(string(""), err2.str()); } else { ++i; } } // double dash test VectorContainer bazstuff3(BAZSTUFF3); foo = -1, bar = -1; for (std::vector<const char*>::iterator i = bazstuff3.arr.begin(); i != bazstuff3.arr.end(); ) { if (ceph_argparse_double_dash(bazstuff3.arr, i)) { break; } else if (ceph_argparse_witharg(bazstuff3.arr, i, &foo, err, "--foo", (char*)NULL)) { ASSERT_EQ(string(""), err.str()); } else if (ceph_argparse_witharg(bazstuff3.arr, i, &bar, err, "--bar", (char*)NULL)) { ASSERT_EQ(string(""), err.str()); } else { ++i; } } ASSERT_EQ(foo, 40); ASSERT_EQ(bar, -1); } TEST(CephArgParse, env_to_vec) { { std::vector<const char*> args; unsetenv("CEPH_ARGS"); unsetenv("WHATEVER"); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(0u, args.size()); clear_g_str_vec(); env_to_vec(args, "WHATEVER"); EXPECT_EQ(0u, args.size()); args.push_back("a"); setenv("CEPH_ARGS", "b c", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(3u, args.size()); EXPECT_EQ(string("b"), args[0]); EXPECT_EQ(string("c"), args[1]); EXPECT_EQ(string("a"), args[2]); setenv("WHATEVER", "d e", 0); clear_g_str_vec(); env_to_vec(args, "WHATEVER"); EXPECT_EQ(5u, args.size()); EXPECT_EQ(string("d"), args[0]); EXPECT_EQ(string("e"), args[1]); } { std::vector<const char*> args; unsetenv("CEPH_ARGS"); args.push_back("a"); args.push_back("--"); args.push_back("c"); setenv("CEPH_ARGS", "b -- d", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(5u, args.size()); EXPECT_EQ(string("b"), args[0]); EXPECT_EQ(string("a"), args[1]); EXPECT_EQ(string("--"), args[2]); EXPECT_EQ(string("d"), args[3]); EXPECT_EQ(string("c"), args[4]); } { std::vector<const char*> args; unsetenv("CEPH_ARGS"); args.push_back("a"); args.push_back("--"); setenv("CEPH_ARGS", "b -- c", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(4u, args.size()); EXPECT_EQ(string("b"), args[0]); EXPECT_EQ(string("a"), args[1]); EXPECT_EQ(string("--"), args[2]); EXPECT_EQ(string("c"), args[3]); } { std::vector<const char*> args; unsetenv("CEPH_ARGS"); args.push_back("--"); args.push_back("c"); setenv("CEPH_ARGS", "b -- d", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(4u, args.size()); EXPECT_EQ(string("b"), args[0]); EXPECT_EQ(string("--"), args[1]); EXPECT_EQ(string("d"), args[2]); EXPECT_EQ(string("c"), args[3]); } { std::vector<const char*> args; unsetenv("CEPH_ARGS"); args.push_back("b"); setenv("CEPH_ARGS", "c -- d", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(4u, args.size()); EXPECT_EQ(string("c"), args[0]); EXPECT_EQ(string("b"), args[1]); EXPECT_EQ(string("--"), args[2]); EXPECT_EQ(string("d"), args[3]); } { std::vector<const char*> args; unsetenv("CEPH_ARGS"); args.push_back("a"); args.push_back("--"); args.push_back("c"); setenv("CEPH_ARGS", "-- d", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(4u, args.size()); EXPECT_EQ(string("a"), args[0]); EXPECT_EQ(string("--"), args[1]); EXPECT_EQ(string("d"), args[2]); EXPECT_EQ(string("c"), args[3]); } { std::vector<const char*> args; unsetenv("CEPH_ARGS"); args.push_back("a"); args.push_back("--"); args.push_back("c"); setenv("CEPH_ARGS", "d", 0); clear_g_str_vec(); env_to_vec(args); EXPECT_EQ(4u, args.size()); EXPECT_EQ(string("d"), args[0]); EXPECT_EQ(string("a"), args[1]); EXPECT_EQ(string("--"), args[2]); EXPECT_EQ(string("c"), args[3]); } } TEST(CephArgParse, parse_ip_port_vec) { struct { const char *from; int type; const char *to; } tests[] = { { "1.2.3.4", entity_addr_t::TYPE_MSGR2, "v2:1.2.3.4:0/0\n" }, { "v1:1.2.3.4", entity_addr_t::TYPE_MSGR2, "v1:1.2.3.4:0/0\n" }, { "1.2.3.4", entity_addr_t::TYPE_LEGACY, "v1:1.2.3.4:0/0\n" }, { "[::],1.2.3.4", entity_addr_t::TYPE_LEGACY, "v1:[::]:0/0\nv1:1.2.3.4:0/0\n" }, { "v2:1.2.3.4:111,v1:5.6.7.8:222", entity_addr_t::TYPE_LEGACY, "v2:1.2.3.4:111/0\nv1:5.6.7.8:222/0\n" }, { "v2:1.2.3.4:111 v1:5.6.7.8:222", entity_addr_t::TYPE_LEGACY, "v2:1.2.3.4:111/0\nv1:5.6.7.8:222/0\n" }, { "[v2:1.2.3.4:111,v1:5.6.7.8:222] [v2:[::]:3300,v1:[::]:6789]", entity_addr_t::TYPE_LEGACY, "[v2:1.2.3.4:111/0,v1:5.6.7.8:222/0]\n[v2:[::]:3300/0,v1:[::]:6789/0]\n" }, { "[v2:1.2.3.4:111,v1:5.6.7.8:222],[v2:[::]:3300,v1:[::]:6789]", entity_addr_t::TYPE_LEGACY, "[v2:1.2.3.4:111/0,v1:5.6.7.8:222/0]\n[v2:[::]:3300/0,v1:[::]:6789/0]\n" }, { 0, 0, 0 }, }; for (unsigned i = 0; tests[i].from; ++i) { vector<entity_addrvec_t> v; cout << "-- " << tests[i].from << " type " << tests[i].type << " ->\n" << tests[i].to; ASSERT_TRUE(parse_ip_port_vec(tests[i].from, v, tests[i].type)); string actual; for (auto s : v) { actual += stringify(s) + "\n"; } ASSERT_EQ(actual, tests[i].to); } const char *bad[] = { "1.2.3.4 foo", 0 }; for (unsigned i = 0; bad[i]; ++i) { vector<entity_addrvec_t> v; cout << "bad " << bad[i] << std::endl; ASSERT_FALSE(parse_ip_port_vec(bad[i], v)); } } /* * Local Variables: * compile-command: "cd .. ; make unittest_ceph_argparse && ./unittest_ceph_argparse" * End: */
15,254
26.990826
93
cc
null
ceph-main/src/test/ceph_compatset.cc
// -*- 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) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <fstream> #include <iostream> #include <errno.h> #include <sys/stat.h> #include <signal.h> #include <ctype.h> #include <boost/scoped_ptr.hpp> #include <string> #include "include/types.h" #include "include/compat.h" #include "include/coredumpctl.h" #include "include/CompatSet.h" #include "gtest/gtest.h" #include <vector> using namespace std; TEST(CephCompatSet, AllSet) { CompatSet::FeatureSet compat; CompatSet::FeatureSet ro; CompatSet::FeatureSet incompat; { PrCtl unset_dumpable; EXPECT_DEATH(compat.insert(CompatSet::Feature(0, "test")), ""); EXPECT_DEATH(compat.insert(CompatSet::Feature(64, "test")), ""); } for (int i = 1; i < 64; i++) { stringstream cname; cname << string("c") << i; compat.insert(CompatSet::Feature(i,cname.str().c_str())); stringstream roname; roname << string("r") << i; ro.insert(CompatSet::Feature(i,roname.str().c_str())); stringstream iname; iname << string("i") << i; incompat.insert(CompatSet::Feature(i,iname.str().c_str())); } CompatSet tcs(compat, ro, incompat); //cout << tcs << std::endl; //Due to a workaround for a bug bit 0 is always set even though it is //not a legal feature. EXPECT_EQ(tcs.compat.mask, (uint64_t)0xffffffffffffffff); EXPECT_EQ(tcs.ro_compat.mask, (uint64_t)0xffffffffffffffff); EXPECT_EQ(tcs.incompat.mask, (uint64_t)0xffffffffffffffff); for (int i = 1; i < 64; i++) { EXPECT_TRUE(tcs.compat.contains(i)); stringstream cname; cname << string("c") << i; EXPECT_TRUE(tcs.compat.contains(CompatSet::Feature(i,cname.str().c_str()))); tcs.compat.remove(i); EXPECT_TRUE(tcs.ro_compat.contains(i)); stringstream roname; roname << string("r") << i; EXPECT_TRUE(tcs.ro_compat.contains(CompatSet::Feature(i,roname.str().c_str()))); tcs.ro_compat.remove(i); EXPECT_TRUE(tcs.incompat.contains(i)); stringstream iname; iname << string("i") << i; EXPECT_TRUE(tcs.incompat.contains(CompatSet::Feature(i,iname.str().c_str()))); tcs.incompat.remove(i); } //Due to a workaround for a bug bit 0 is always set even though it is //not a legal feature. EXPECT_EQ(tcs.compat.mask, (uint64_t)1); EXPECT_TRUE(tcs.compat.names.empty()); EXPECT_EQ(tcs.ro_compat.mask, (uint64_t)1); EXPECT_TRUE(tcs.ro_compat.names.empty()); EXPECT_EQ(tcs.incompat.mask, (uint64_t)1); EXPECT_TRUE(tcs.incompat.names.empty()); } TEST(CephCompatSet, other) { CompatSet s1, s2, s1dup; s1.compat.insert(CompatSet::Feature(1, "c1")); s1.compat.insert(CompatSet::Feature(2, "c2")); s1.compat.insert(CompatSet::Feature(32, "c32")); s1.ro_compat.insert(CompatSet::Feature(63, "r63")); s1.incompat.insert(CompatSet::Feature(1, "i1")); s2.compat.insert(CompatSet::Feature(1, "c1")); s2.compat.insert(CompatSet::Feature(32, "c32")); s2.ro_compat.insert(CompatSet::Feature(63, "r63")); s2.incompat.insert(CompatSet::Feature(1, "i1")); s1dup = s1; //Check exact match EXPECT_EQ(s1.compare(s1dup), 0); //Check superset EXPECT_EQ(s1.compare(s2), 1); //Check missing features EXPECT_EQ(s2.compare(s1), -1); CompatSet diff = s2.unsupported(s1); EXPECT_EQ(diff.compat.mask, (uint64_t)1<<2 | 1); EXPECT_EQ(diff.ro_compat.mask, (uint64_t)1); EXPECT_EQ(diff.incompat.mask, (uint64_t)1); CompatSet s3 = s1; s3.incompat.insert(CompatSet::Feature(4, "i4")); diff = s1.unsupported(s3); EXPECT_EQ(diff.compat.mask, (uint64_t)1); EXPECT_EQ(diff.ro_compat.mask, (uint64_t)1); EXPECT_EQ(diff.incompat.mask, (uint64_t)1<<4 | 1); } TEST(CephCompatSet, merge) { CompatSet s1, s2, s1dup, s2dup; s1.compat.insert(CompatSet::Feature(1, "c1")); s1.compat.insert(CompatSet::Feature(2, "c2")); s1.compat.insert(CompatSet::Feature(32, "c32")); s1.ro_compat.insert(CompatSet::Feature(63, "r63")); s1.incompat.insert(CompatSet::Feature(1, "i1")); s1dup = s1; s2.compat.insert(CompatSet::Feature(1, "c1")); s2.compat.insert(CompatSet::Feature(32, "c32")); s2.ro_compat.insert(CompatSet::Feature(1, "r1")); s2.ro_compat.insert(CompatSet::Feature(63, "r63")); s2.incompat.insert(CompatSet::Feature(1, "i1")); s2dup = s2; //Nothing to merge if they are the same EXPECT_FALSE(s1.merge(s1dup)); EXPECT_FALSE(s2.merge(s2dup)); EXPECT_TRUE(s1.merge(s2)); EXPECT_EQ(s1.compat.mask, (uint64_t)1<<1 | (uint64_t)1<<2 | (uint64_t)1<<32 | 1); EXPECT_EQ(s1.ro_compat.mask, (uint64_t)1<<1 | (uint64_t)1<<63 | 1); EXPECT_EQ(s1.incompat.mask, (uint64_t)1<<1 | 1); EXPECT_TRUE(s2.merge(s1dup)); EXPECT_EQ(s2.compat.mask, (uint64_t)1<<1 | (uint64_t)1<<2 | (uint64_t)1<<32 | 1); EXPECT_EQ(s2.ro_compat.mask, (uint64_t)1<<1 | (uint64_t)1<<63 | 1); EXPECT_EQ(s2.incompat.mask, (uint64_t)1<<1 | 1); }
5,161
29.72619
84
cc
null
ceph-main/src/test/ceph_crypto.cc
#include "gtest/gtest.h" #include "common/ceph_argparse.h" #include "common/ceph_crypto.h" #include "common/common_init.h" #include "global/global_init.h" #include "global/global_context.h" class CryptoEnvironment: public ::testing::Environment { public: void SetUp() override { ceph::crypto::init(); } }; TEST(MD5, Simple) { ceph::crypto::MD5 h; h.Update((const unsigned char*)"foo", 3); unsigned char digest[CEPH_CRYPTO_MD5_DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[CEPH_CRYPTO_MD5_DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, CEPH_CRYPTO_MD5_DIGESTSIZE); ASSERT_EQ(0, err); } TEST(MD5, MultiUpdate) { ceph::crypto::MD5 h; h.Update((const unsigned char*)"", 0); h.Update((const unsigned char*)"fo", 2); h.Update((const unsigned char*)"", 0); h.Update((const unsigned char*)"o", 1); h.Update((const unsigned char*)"", 0); unsigned char digest[CEPH_CRYPTO_MD5_DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[CEPH_CRYPTO_MD5_DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, CEPH_CRYPTO_MD5_DIGESTSIZE); ASSERT_EQ(0, err); } TEST(MD5, Restart) { ceph::crypto::MD5 h; h.Update((const unsigned char*)"bar", 3); h.Restart(); h.Update((const unsigned char*)"foo", 3); unsigned char digest[CEPH_CRYPTO_MD5_DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[CEPH_CRYPTO_MD5_DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, CEPH_CRYPTO_MD5_DIGESTSIZE); ASSERT_EQ(0, err); } TEST(HMACSHA1, Simple) { ceph::crypto::HMACSHA1 h((const unsigned char*)"sekrit", 6); h.Update((const unsigned char*)"foo", 3); unsigned char digest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE] = { 0x04, 0xbc, 0x52, 0x66, 0xb6, 0xff, 0xad, 0xad, 0x9d, 0x57, 0xce, 0x13, 0xea, 0x8c, 0xf5, 0x6b, 0xf9, 0x95, 0x2f, 0xd6, }; err = memcmp(digest, want_digest, CEPH_CRYPTO_HMACSHA1_DIGESTSIZE); ASSERT_EQ(0, err); } TEST(HMACSHA1, MultiUpdate) { ceph::crypto::HMACSHA1 h((const unsigned char*)"sekrit", 6); h.Update((const unsigned char*)"", 0); h.Update((const unsigned char*)"fo", 2); h.Update((const unsigned char*)"", 0); h.Update((const unsigned char*)"o", 1); h.Update((const unsigned char*)"", 0); unsigned char digest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE] = { 0x04, 0xbc, 0x52, 0x66, 0xb6, 0xff, 0xad, 0xad, 0x9d, 0x57, 0xce, 0x13, 0xea, 0x8c, 0xf5, 0x6b, 0xf9, 0x95, 0x2f, 0xd6, }; err = memcmp(digest, want_digest, CEPH_CRYPTO_HMACSHA1_DIGESTSIZE); ASSERT_EQ(0, err); } TEST(HMACSHA1, Restart) { ceph::crypto::HMACSHA1 h((const unsigned char*)"sekrit", 6); h.Update((const unsigned char*)"bar", 3); h.Restart(); h.Update((const unsigned char*)"foo", 3); unsigned char digest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE] = { 0x04, 0xbc, 0x52, 0x66, 0xb6, 0xff, 0xad, 0xad, 0x9d, 0x57, 0xce, 0x13, 0xea, 0x8c, 0xf5, 0x6b, 0xf9, 0x95, 0x2f, 0xd6, }; err = memcmp(digest, want_digest, CEPH_CRYPTO_HMACSHA1_DIGESTSIZE); ASSERT_EQ(0, err); } TEST(Digest, SHA1) { auto digest = [](const bufferlist& bl) { return ceph::crypto::digest<ceph::crypto::SHA1>(bl); }; { bufferlist bl; sha1_digest_t sha1 = digest(bl); EXPECT_EQ("da39a3ee5e6b4b0d3255bfef95601890afd80709", sha1.to_str()); } { bufferlist bl; bl.append(""); sha1_digest_t sha1 = digest(bl); EXPECT_EQ("da39a3ee5e6b4b0d3255bfef95601890afd80709", sha1.to_str()); } { bufferlist bl; bl.append("Hello"); sha1_digest_t sha1 = digest(bl); EXPECT_EQ("f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0", sha1.to_str()); } { bufferlist bl, bl2; bl.append("Hello"); bl2.append(", world!"); bl.claim_append(bl2); sha1_digest_t sha1 = digest(bl); EXPECT_EQ("943a702d06f34599aee1f8da8ef9f7296031d699", sha1.to_str()); bl2.append(" How are you today?"); bl.claim_append(bl2); sha1 = digest(bl); EXPECT_EQ("778b5d10e5133aa28fb8de71d35b6999b9a25eb4", sha1.to_str()); } { bufferptr p(65536); memset(p.c_str(), 0, 65536); bufferlist bl; bl.append(p); sha1_digest_t sha1 = digest(bl); EXPECT_EQ("1adc95bebe9eea8c112d40cd04ab7a8d75c4f961", sha1.to_str()); } } TEST(Digest, SHA256) { auto digest = [](const bufferlist& bl) { return ceph::crypto::digest<ceph::crypto::SHA256>(bl); }; { bufferlist bl; sha256_digest_t sha256 = digest(bl); EXPECT_EQ("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", sha256.to_str()); } { bufferlist bl; bl.append(""); sha256_digest_t sha256 = digest(bl); EXPECT_EQ("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", sha256.to_str()); } { bufferlist bl; bl.append("Hello"); sha256_digest_t sha256 = digest(bl); EXPECT_EQ("185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969", sha256.to_str()); } { bufferlist bl, bl2; bl.append("Hello"); bl2.append(", world!"); bl.claim_append(bl2); sha256_digest_t sha256 = digest(bl); EXPECT_EQ("315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3", sha256.to_str()); bl2.append(" How are you today?"); bl.claim_append(bl2); sha256 = digest(bl); EXPECT_EQ("e85f57f8bb018bd4f7beed6f27488cef22b13d5e06e8b8a27cac8b087c2a549e", sha256.to_str()); } { bufferptr p(65536); memset(p.c_str(), 0, 65536); bufferlist bl; bl.append(p); sha256_digest_t sha256 = digest(bl); EXPECT_EQ("de2f256064a0af797747c2b97505dc0b9f3df0de4f489eac731c23ae9ca9cc31", sha256.to_str()); } } TEST(Digest, SHA512) { auto digest = [](const bufferlist& bl) { return ceph::crypto::digest<ceph::crypto::SHA512>(bl); }; { bufferlist bl; sha512_digest_t sha512 = digest(bl); EXPECT_EQ("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", sha512.to_str()); } { bufferlist bl; bl.append(""); sha512_digest_t sha512 = digest(bl); EXPECT_EQ("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", sha512.to_str()); } { bufferlist bl; bl.append("Hello"); sha512_digest_t sha512 = digest(bl); EXPECT_EQ("3615f80c9d293ed7402687f94b22d58e529b8cc7916f8fac7fddf7fbd5af4cf777d3d795a7a00a16bf7e7f3fb9561ee9baae480da9fe7a18769e71886b03f315", sha512.to_str()); } { bufferlist bl, bl2; bl.append("Hello"); bl2.append(", world!"); bl.claim_append(bl2); sha512_digest_t sha512 = digest(bl); EXPECT_EQ("c1527cd893c124773d811911970c8fe6e857d6df5dc9226bd8a160614c0cd963a4ddea2b94bb7d36021ef9d865d5cea294a82dd49a0bb269f51f6e7a57f79421", sha512.to_str()); bl2.append(" How are you today?"); bl.claim_append(bl2); sha512 = digest(bl); EXPECT_EQ("7d50e299496754f9a0d158e018d4b733f2ef51c487b43b50719ffdabe3c3da5a347029741056887b4ffa2ddd0aa9e0dd358b8ed9da9a4f3455f44896fc8e5395", sha512.to_str()); } { bufferptr p(65536); memset(p.c_str(), 0, 65536); bufferlist bl; bl.append(p); sha512_digest_t sha512 = digest(bl); EXPECT_EQ("73e4153936dab198397b74ee9efc26093dda721eaab2f8d92786891153b45b04265a161b169c988edb0db2c53124607b6eaaa816559c5ce54f3dbc9fa6a7a4b2", sha512.to_str()); } } class ForkDeathTest : public ::testing::Test { protected: void SetUp() override { // shutdown NSS so it can be reinitialized after the fork // some data structures used by NSPR are only initialized once, and they // will be cleaned up with ceph::crypto::shutdown(false), so we need to // keep them around after fork. ceph::crypto::shutdown(true); } void TearDown() override { // undo the NSS shutdown we did in the parent process, after the // test is done ceph::crypto::init(); } }; void do_simple_crypto() { // ensure that the shutdown/fork/init sequence results in a working // NSS crypto library; this function is run in the child, after the // fork, and if you comment out the ceph::crypto::init, or if the // trick were to fail, you would see this ending in an assert and // not exit status 0 ceph::crypto::init(); ceph::crypto::MD5 h; h.Update((const unsigned char*)"foo", 3); unsigned char digest[CEPH_CRYPTO_MD5_DIGESTSIZE]; h.Final(digest); exit(0); } #if GTEST_HAS_DEATH_TEST && !defined(_WIN32) TEST_F(ForkDeathTest, MD5) { ASSERT_EXIT(do_simple_crypto(), ::testing::ExitedWithCode(0), "^$"); } #endif // GTEST_HAS_DEATH_TEST && !defined(_WIN32) int main(int argc, char **argv) { std::vector<const char*> args(argv, argv + argc); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
9,505
32.121951
163
cc
null
ceph-main/src/test/confutils.cc
// -*- 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) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/ConfUtils.h" #include "common/config_proxy.h" #include "common/errno.h" #include "gtest/gtest.h" #include "include/buffer.h" #include <errno.h> #include <filesystem> #include <iostream> #include <sstream> #include <stdlib.h> #include <stdint.h> #include <sys/stat.h> #include <sys/types.h> namespace fs = std::filesystem; using namespace std; using ceph::bufferlist; using std::cerr; using std::ostringstream; #define MAX_FILES_TO_DELETE 1000UL static size_t config_idx = 0; static size_t unlink_idx = 0; static char *to_unlink[MAX_FILES_TO_DELETE]; static std::string get_temp_dir() { static std::string temp_dir; if (temp_dir.empty()) { const char *tmpdir = getenv("TMPDIR"); if (!tmpdir) tmpdir = "/tmp"; srand(time(NULL)); ostringstream oss; oss << tmpdir << "/confutils_test_dir." << rand() << "." << getpid(); umask(022); if (!fs::exists(oss.str())) { std::error_code ec; if (!fs::create_directory(oss.str(), ec)) { cerr << "failed to create temp directory '" << temp_dir << "' " << ec.message() << std::endl; return ""; } fs::permissions(oss.str(), fs::perms::sticky_bit | fs::perms::all); } temp_dir = oss.str(); } return temp_dir; } static void unlink_all(void) { for (size_t i = 0; i < unlink_idx; ++i) { unlink(to_unlink[i]); } for (size_t i = 0; i < unlink_idx; ++i) { free(to_unlink[i]); } rmdir(get_temp_dir().c_str()); } static int create_tempfile(const std::string &fname, const char *text) { FILE *fp = fopen(fname.c_str(), "w"); if (!fp) { int err = errno; cerr << "Failed to write file '" << fname << "' to temp directory '" << get_temp_dir() << "'. " << cpp_strerror(err) << std::endl; return err; } std::shared_ptr<FILE> fpp(fp, fclose); if (unlink_idx >= MAX_FILES_TO_DELETE) return -ENOBUFS; if (unlink_idx == 0) { memset(to_unlink, 0, sizeof(to_unlink)); atexit(unlink_all); } to_unlink[unlink_idx++] = strdup(fname.c_str()); size_t strlen_text = strlen(text); size_t res = fwrite(text, 1, strlen_text, fp); if (res != strlen_text) { int err = errno; cerr << "fwrite error while writing to " << fname << ": " << cpp_strerror(err) << std::endl; return err; } return 0; } static std::string next_tempfile(const char *text) { ostringstream oss; std::string temp_dir(get_temp_dir()); if (temp_dir.empty()) return ""; oss << temp_dir << "/test_config." << config_idx++ << ".config"; int ret = create_tempfile(oss.str(), text); if (ret) return ""; return oss.str(); } const char * const trivial_conf_1 = ""; const char * const trivial_conf_2 = "log dir = foobar"; const char * const trivial_conf_3 = "log dir = barfoo\n"; const char * const trivial_conf_4 = "log dir = \"barbaz\"\n"; const char * const simple_conf_1 = "\ ; here's a comment\n\ [global]\n\ keyring = .my_ceph_keyring\n\ \n\ [mds]\n\ log dir = out\n\ log per instance = true\n\ log sym history = 100\n\ profiling logger = true\n\ profiling logger dir = wowsers\n\ chdir = ""\n\ pid file = out/$name.pid\n\ \n\ mds debug frag = true\n\ [osd]\n\ pid file = out/$name.pid\n\ osd scrub load threshold = 5.0\n\ \n\ lockdep = 1\n\ [osd0]\n\ osd data = dev/osd0\n\ osd journal size = 100\n\ [mds.a]\n\ [mds.b]\n\ [mds.c]\n\ "; // we can add whitespace at odd locations and it will get stripped out. const char * const simple_conf_2 = "\ [mds.a]\n\ log dir = special_mds_a\n\ [mds]\n\ log sym history = 100\n\ log dir = out # after a comment, anything # can ### happen ;;; right?\n\ log per instance = true\n\ profiling logger = true\n\ profiling logger dir = log\n\ chdir = ""\n\ pid file\t=\tfoo2\n\ [osd0]\n\ keyring = osd_keyring ; osd's keyring\n\ \n\ \n\ [global]\n\ # I like pound signs as comment markers.\n\ ; Do you like pound signs as comment markers?\n\ keyring = shenanigans ; The keyring of a leprechaun\n\ \n\ # Let's just have a line with a lot of whitespace and nothing else.\n\ \n\ lockdep = 1\n\ "; // test line-combining const char * const conf3 = "\ [global]\n\ log file = /quite/a/long/path\\\n\ /for/a/log/file\n\ pid file = \\\n\ spork\\\n\ \n\ [mon] #nothing here \n\ "; const char * const escaping_conf_1 = "\ [global]\n\ log file = the \"scare quotes\"\n\ pid file = a \\\n\ pid file\n\ [mon]\n\ keyring = \"nested \\\"quotes\\\"\"\n\ "; const char * const escaping_conf_2 = "\ [apple \\]\\[]\n\ log file = floppy disk\n\ [mon]\n\ keyring = \"backslash\\\\\"\n\ "; // illegal because it contains an invalid utf8 sequence. const char illegal_conf1[] = "\ [global]\n\ log file = foo\n\ pid file = invalid-utf-\xe2\x28\xa1\n\ [osd0]\n\ keyring = osd_keyring ; osd's keyring\n\ "; // illegal because it contains a malformed section header. const char illegal_conf2[] = "\ [global\n\ log file = foo\n\ [osd0]\n\ keyring = osd_keyring ; osd's keyring\n\ "; // illegal because it contains a line that doesn't parse const char illegal_conf3[] = "\ [global]\n\ who_what_where\n\ [osd0]\n\ keyring = osd_keyring ; osd's keyring\n\ "; // illegal because it has unterminated quotes const char illegal_conf4[] = "\ [global]\n\ keyring = \"unterminated quoted string\n\ [osd0]\n\ keyring = osd_keyring ; osd's keyring\n\ "; const char override_config_1[] = "\ [global]\n\ log file = global_log\n\ [mds]\n\ log file = mds_log\n\ [osd]\n\ log file = osd_log\n\ [osd.0]\n\ log file = osd0_log\n\ "; const char dup_key_config_1[] = "\ [mds.a]\n\ log_file = 1\n\ log_file = 3\n\ "; TEST(ConfUtils, ParseFiles0) { std::string val; { std::ostringstream err; std::string trivial_conf_1_f(next_tempfile(trivial_conf_1)); ConfFile cf1; ASSERT_EQ(cf1.parse_file(trivial_conf_1_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); } { std::ostringstream err; std::string trivial_conf_2_f(next_tempfile(trivial_conf_2)); ConfFile cf2; ASSERT_EQ(cf2.parse_file(trivial_conf_2_f.c_str(), &err), -EINVAL); ASSERT_GT(err.tellp(), 0U); } { std::ostringstream err; bufferlist bl3; bl3.append(trivial_conf_3, strlen(trivial_conf_3)); ConfFile cf3; ASSERT_EQ(cf3.parse_bufferlist(&bl3, &err), 0); ASSERT_EQ(err.tellp(), 0U); ASSERT_EQ(cf3.read("global", "log dir", val), 0); ASSERT_EQ(val, "barfoo"); } { std::ostringstream err; std::string trivial_conf_4_f(next_tempfile(trivial_conf_4)); ConfFile cf4; ASSERT_EQ(cf4.parse_file(trivial_conf_4_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); ASSERT_EQ(cf4.read("global", "log dir", val), 0); ASSERT_EQ(val, "barbaz"); } } TEST(ConfUtils, ParseFiles1) { std::ostringstream err; std::string simple_conf_1_f(next_tempfile(simple_conf_1)); ConfFile cf1; ASSERT_EQ(cf1.parse_file(simple_conf_1_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); std::string simple_conf_2_f(next_tempfile(simple_conf_1)); ConfFile cf2; ASSERT_EQ(cf2.parse_file(simple_conf_2_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); bufferlist bl3; bl3.append(simple_conf_1, strlen(simple_conf_1)); ConfFile cf3; ASSERT_EQ(cf3.parse_bufferlist(&bl3, &err), 0); ASSERT_EQ(err.tellp(), 0U); bufferlist bl4; bl4.append(simple_conf_2, strlen(simple_conf_2)); ConfFile cf4; ASSERT_EQ(cf4.parse_bufferlist(&bl4, &err), 0); ASSERT_EQ(err.tellp(), 0U); } TEST(ConfUtils, ReadFiles1) { std::ostringstream err; std::string simple_conf_1_f(next_tempfile(simple_conf_1)); ConfFile cf1; ASSERT_EQ(cf1.parse_file(simple_conf_1_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); std::string val; ASSERT_EQ(cf1.read("global", "keyring", val), 0); ASSERT_EQ(val, ".my_ceph_keyring"); ASSERT_EQ(cf1.read("mds", "profiling logger dir", val), 0); ASSERT_EQ(val, "wowsers"); ASSERT_EQ(cf1.read("mds", "something that does not exist", val), -ENOENT); // exists in mds section, but not in global ASSERT_EQ(cf1.read("global", "profiling logger dir", val), -ENOENT); bufferlist bl2; bl2.append(simple_conf_2, strlen(simple_conf_2)); ConfFile cf2; ASSERT_EQ(cf2.parse_bufferlist(&bl2, &err), 0); ASSERT_EQ(err.tellp(), 0U); ASSERT_EQ(cf2.read("osd0", "keyring", val), 0); ASSERT_EQ(val, "osd_keyring"); ASSERT_EQ(cf2.read("mds", "pid file", val), 0); ASSERT_EQ(val, "foo2"); ASSERT_EQ(cf2.read("nonesuch", "keyring", val), -ENOENT); } TEST(ConfUtils, ReadFiles2) { std::ostringstream err; std::string conf3_f(next_tempfile(conf3)); ConfFile cf1; std::string val; ASSERT_EQ(cf1.parse_file(conf3_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); ASSERT_EQ(cf1.read("global", "log file", val), 0); ASSERT_EQ(val, "/quite/a/long/path/for/a/log/file"); ASSERT_EQ(cf1.read("global", "pid file", val), 0); ASSERT_EQ(val, "spork"); } TEST(ConfUtils, IllegalFiles) { { std::ostringstream err; ConfFile cf1; std::string illegal_conf1_f(next_tempfile(illegal_conf1)); ASSERT_EQ(cf1.parse_file(illegal_conf1_f.c_str(), &err), -EINVAL); ASSERT_GT(err.tellp(), 0U); } { std::ostringstream err; bufferlist bl2; bl2.append(illegal_conf2, strlen(illegal_conf2)); ConfFile cf2; ASSERT_EQ(cf2.parse_bufferlist(&bl2, &err), -EINVAL); ASSERT_GT(err.tellp(), 0U); } { std::ostringstream err; std::string illegal_conf3_f(next_tempfile(illegal_conf3)); ConfFile cf3; ASSERT_EQ(cf3.parse_file(illegal_conf3_f.c_str(), &err), -EINVAL); ASSERT_GT(err.tellp(), 0U); } { std::ostringstream err; std::string illegal_conf4_f(next_tempfile(illegal_conf4)); ConfFile cf4; ASSERT_EQ(cf4.parse_file(illegal_conf4_f.c_str(), &err), -EINVAL); ASSERT_GT(err.tellp(), 0U); } } TEST(ConfUtils, EscapingFiles) { std::ostringstream err; std::string escaping_conf_1_f(next_tempfile(escaping_conf_1)); ConfFile cf1; std::string val; ASSERT_EQ(cf1.parse_file(escaping_conf_1_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); ASSERT_EQ(cf1.read("global", "log file", val), 0); ASSERT_EQ(val, "the \"scare quotes\""); ASSERT_EQ(cf1.read("global", "pid file", val), 0); ASSERT_EQ(val, "a pid file"); ASSERT_EQ(cf1.read("mon", "keyring", val), 0); ASSERT_EQ(val, "nested \"quotes\""); std::string escaping_conf_2_f(next_tempfile(escaping_conf_2)); ConfFile cf2; ASSERT_EQ(cf2.parse_file(escaping_conf_2_f.c_str(), &err), 0); ASSERT_EQ(err.tellp(), 0U); ASSERT_EQ(cf2.read("apple ][", "log file", val), 0); ASSERT_EQ(val, "floppy disk"); ASSERT_EQ(cf2.read("mon", "keyring", val), 0); ASSERT_EQ(val, "backslash\\"); } TEST(ConfUtils, Overrides) { ConfigProxy conf{false}; std::ostringstream warn; std::string override_conf_1_f(next_tempfile(override_config_1)); conf->name.set(CEPH_ENTITY_TYPE_MON, "0"); conf.parse_config_files(override_conf_1_f.c_str(), &warn, 0); ASSERT_FALSE(conf.has_parse_error()); ASSERT_EQ(conf->log_file, "global_log"); conf->name.set(CEPH_ENTITY_TYPE_MDS, "a"); conf.parse_config_files(override_conf_1_f.c_str(), &warn, 0); ASSERT_FALSE(conf.has_parse_error()); ASSERT_EQ(conf->log_file, "mds_log"); conf->name.set(CEPH_ENTITY_TYPE_OSD, "0"); conf.parse_config_files(override_conf_1_f.c_str(), &warn, 0); ASSERT_FALSE(conf.has_parse_error()); ASSERT_EQ(conf->log_file, "osd0_log"); } TEST(ConfUtils, DupKey) { ConfigProxy conf{false}; std::ostringstream warn; std::string dup_key_config_f(next_tempfile(dup_key_config_1)); conf->name.set(CEPH_ENTITY_TYPE_MDS, "a"); conf.parse_config_files(dup_key_config_f.c_str(), &warn, 0); ASSERT_FALSE(conf.has_parse_error()); ASSERT_EQ(conf->log_file, string("3")); }
12,434
26.091503
76
cc
null
ceph-main/src/test/coverage.sh
#!/bin/sh set -e usage () { printf '%s: usage: %s [-d srcdir] [-o output_basename] COMMAND [ARGS..]\n' "$(basename "$0")" "$(basename "$0")" 1>&2 exit 1 } OUTPUT_BASENAME=coverage SRCDIR=. while getopts "d:o:h" flag do case $flag in d) SRCDIR=$OPTARG;; o) OUTPUT_BASENAME=$OPTARG;; *) usage;; esac done shift $(($OPTIND - 1)) lcov -d $SRCDIR -z > /dev/null 2>&1 lcov -d $SRCDIR -c -i -o "${OUTPUT_BASENAME}_base_full.lcov" > /dev/null 2>&1 "$@" lcov -d $SRCDIR -c -o "${OUTPUT_BASENAME}_tested_full.lcov" > /dev/null 2>&1 lcov -r "${OUTPUT_BASENAME}_base_full.lcov" /usr/include\* -o "${OUTPUT_BASENAME}_base.lcov" > /dev/null 2>&1 lcov -r "${OUTPUT_BASENAME}_tested_full.lcov" /usr/include\* -o "${OUTPUT_BASENAME}_tested.lcov" > /dev/null 2>&1 lcov -a "${OUTPUT_BASENAME}_base.lcov" -a "${OUTPUT_BASENAME}_tested.lcov" -o "${OUTPUT_BASENAME}.lcov" | tail -n 3
900
29.033333
123
sh
null
ceph-main/src/test/crypto.cc
#include <errno.h> #include <time.h> #include <boost/container/small_vector.hpp> #include "gtest/gtest.h" #include "include/types.h" #include "auth/Crypto.h" #include "common/Clock.h" #include "common/ceph_crypto.h" #include "common/ceph_context.h" #include "global/global_context.h" using namespace std; class CryptoEnvironment: public ::testing::Environment { public: void SetUp() override { ceph::crypto::init(); } }; TEST(AES, ValidateSecret) { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); int l; for (l=0; l<16; l++) { bufferptr bp(l); int err; err = h->validate_secret(bp); EXPECT_EQ(-EINVAL, err); } for (l=16; l<50; l++) { bufferptr bp(l); int err; err = h->validate_secret(bp); EXPECT_EQ(0, err); } } TEST(AES, Encrypt) { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); char secret_s[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; bufferptr secret(secret_s, sizeof(secret_s)); unsigned char plaintext_s[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, }; bufferlist plaintext; plaintext.append((char *)plaintext_s, sizeof(plaintext_s)); bufferlist cipher; std::string error; CryptoKeyHandler *kh = h->get_key_handler(secret, error); int r = kh->encrypt(plaintext, cipher, &error); ASSERT_EQ(r, 0); ASSERT_EQ(error, ""); unsigned char want_cipher[] = { 0xb3, 0x8f, 0x5b, 0xc9, 0x35, 0x4c, 0xf8, 0xc6, 0x13, 0x15, 0x66, 0x6f, 0x37, 0xd7, 0x79, 0x3a, 0x11, 0x90, 0x7b, 0xe9, 0xd8, 0x3c, 0x35, 0x70, 0x58, 0x7b, 0x97, 0x9b, 0x03, 0xd2, 0xa5, 0x01, }; char cipher_s[sizeof(want_cipher)]; ASSERT_EQ(sizeof(cipher_s), cipher.length()); cipher.cbegin().copy(sizeof(cipher_s), &cipher_s[0]); int err; err = memcmp(cipher_s, want_cipher, sizeof(want_cipher)); ASSERT_EQ(0, err); delete kh; } TEST(AES, EncryptNoBl) { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); char secret_s[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; bufferptr secret(secret_s, sizeof(secret_s)); const unsigned char plaintext[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, }; std::string error; std::unique_ptr<CryptoKeyHandler> kh(h->get_key_handler(secret, error)); const CryptoKey::in_slice_t plain_slice { sizeof(plaintext), plaintext }; // we need to deduce size first const CryptoKey::out_slice_t probe_slice { 0, nullptr }; const auto needed = kh->encrypt(plain_slice, probe_slice); ASSERT_GE(needed, plain_slice.length); boost::container::small_vector< // FIXME? //unsigned char, sizeof(plaintext) + kh->get_block_size()> buf; unsigned char, sizeof(plaintext) + 16> buf(needed); const CryptoKey::out_slice_t cipher_slice { needed, buf.data() }; const auto cipher_size = kh->encrypt(plain_slice, cipher_slice); ASSERT_EQ(cipher_size, needed); const unsigned char want_cipher[] = { 0xb3, 0x8f, 0x5b, 0xc9, 0x35, 0x4c, 0xf8, 0xc6, 0x13, 0x15, 0x66, 0x6f, 0x37, 0xd7, 0x79, 0x3a, 0x11, 0x90, 0x7b, 0xe9, 0xd8, 0x3c, 0x35, 0x70, 0x58, 0x7b, 0x97, 0x9b, 0x03, 0xd2, 0xa5, 0x01, }; ASSERT_EQ(sizeof(want_cipher), cipher_size); const int err = memcmp(buf.data(), want_cipher, sizeof(want_cipher)); ASSERT_EQ(0, err); } TEST(AES, Decrypt) { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); char secret_s[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; bufferptr secret(secret_s, sizeof(secret_s)); unsigned char cipher_s[] = { 0xb3, 0x8f, 0x5b, 0xc9, 0x35, 0x4c, 0xf8, 0xc6, 0x13, 0x15, 0x66, 0x6f, 0x37, 0xd7, 0x79, 0x3a, 0x11, 0x90, 0x7b, 0xe9, 0xd8, 0x3c, 0x35, 0x70, 0x58, 0x7b, 0x97, 0x9b, 0x03, 0xd2, 0xa5, 0x01, }; bufferlist cipher; cipher.append((char *)cipher_s, sizeof(cipher_s)); unsigned char want_plaintext[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, }; char plaintext_s[sizeof(want_plaintext)]; std::string error; bufferlist plaintext; CryptoKeyHandler *kh = h->get_key_handler(secret, error); int r = kh->decrypt(cipher, plaintext, &error); ASSERT_EQ(r, 0); ASSERT_EQ(error, ""); ASSERT_EQ(sizeof(plaintext_s), plaintext.length()); plaintext.cbegin().copy(sizeof(plaintext_s), &plaintext_s[0]); int err; err = memcmp(plaintext_s, want_plaintext, sizeof(want_plaintext)); ASSERT_EQ(0, err); delete kh; } TEST(AES, DecryptNoBl) { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); const char secret_s[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; bufferptr secret(secret_s, sizeof(secret_s)); const unsigned char ciphertext[] = { 0xb3, 0x8f, 0x5b, 0xc9, 0x35, 0x4c, 0xf8, 0xc6, 0x13, 0x15, 0x66, 0x6f, 0x37, 0xd7, 0x79, 0x3a, 0x11, 0x90, 0x7b, 0xe9, 0xd8, 0x3c, 0x35, 0x70, 0x58, 0x7b, 0x97, 0x9b, 0x03, 0xd2, 0xa5, 0x01, }; const unsigned char want_plaintext[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, }; constexpr static std::size_t plain_buf_size = \ CryptoKey::get_max_outbuf_size(sizeof(want_plaintext)); unsigned char plaintext[plain_buf_size]; std::string error; std::unique_ptr<CryptoKeyHandler> kh(h->get_key_handler(secret, error)); CryptoKey::in_slice_t cipher_slice { sizeof(ciphertext), ciphertext }; CryptoKey::out_slice_t plain_slice { sizeof(plaintext), plaintext }; const auto plain_size = kh->decrypt(cipher_slice, plain_slice); ASSERT_EQ(plain_size, sizeof(want_plaintext)); const int err = memcmp(plaintext, want_plaintext, sizeof(plain_size)); ASSERT_EQ(0, err); } template <std::size_t TextSizeV> static void aes_loop_cephx() { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); CryptoRandom random; bufferptr secret(16); random.get_bytes(secret.c_str(), secret.length()); std::string error; std::unique_ptr<CryptoKeyHandler> kh(h->get_key_handler(secret, error)); unsigned char plaintext[TextSizeV]; random.get_bytes(reinterpret_cast<char*>(plaintext), sizeof(plaintext)); const CryptoKey::in_slice_t plain_slice { sizeof(plaintext), plaintext }; // we need to deduce size first const CryptoKey::out_slice_t probe_slice { 0, nullptr }; const auto needed = kh->encrypt(plain_slice, probe_slice); ASSERT_GE(needed, plain_slice.length); boost::container::small_vector< // FIXME? //unsigned char, sizeof(plaintext) + kh->get_block_size()> buf; unsigned char, sizeof(plaintext) + 16> buf(needed); std::size_t cipher_size; for (std::size_t i = 0; i < 1000000; i++) { const CryptoKey::out_slice_t cipher_slice { needed, buf.data() }; cipher_size = kh->encrypt(plain_slice, cipher_slice); ASSERT_EQ(cipher_size, needed); } } // These magics reflects Cephx's signature size. Please consult // CephxSessionHandler::_calc_signature() for more details. TEST(AES, LoopCephx) { aes_loop_cephx<29>(); } TEST(AES, LoopCephxV2) { aes_loop_cephx<32>(); } static void aes_loop(const std::size_t text_size) { CryptoRandom random; bufferptr secret(16); random.get_bytes(secret.c_str(), secret.length()); bufferptr orig_plaintext(text_size); random.get_bytes(orig_plaintext.c_str(), orig_plaintext.length()); bufferlist plaintext; plaintext.append(orig_plaintext.c_str(), orig_plaintext.length()); for (int i=0; i<10000; i++) { bufferlist cipher; { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); std::string error; CryptoKeyHandler *kh = h->get_key_handler(secret, error); int r = kh->encrypt(plaintext, cipher, &error); ASSERT_EQ(r, 0); ASSERT_EQ(error, ""); delete kh; } plaintext.clear(); { CryptoHandler *h = g_ceph_context->get_crypto_handler(CEPH_CRYPTO_AES); std::string error; CryptoKeyHandler *ckh = h->get_key_handler(secret, error); int r = ckh->decrypt(cipher, plaintext, &error); ASSERT_EQ(r, 0); ASSERT_EQ(error, ""); delete ckh; } } bufferlist orig; orig.append(orig_plaintext); ASSERT_EQ(orig, plaintext); } TEST(AES, Loop) { aes_loop(256); } // These magics reflects Cephx's signature size. Please consult // CephxSessionHandler::_calc_signature() for more details. TEST(AES, Loop_29) { aes_loop(29); } TEST(AES, Loop_32) { aes_loop(32); } void aes_loopkey(const std::size_t text_size) { CryptoRandom random; bufferptr k(16); random.get_bytes(k.c_str(), k.length()); CryptoKey key(CEPH_CRYPTO_AES, ceph_clock_now(), k); bufferlist data; bufferptr r(text_size); random.get_bytes(r.c_str(), r.length()); data.append(r); utime_t start = ceph_clock_now(); int n = 100000; for (int i=0; i<n; ++i) { bufferlist encoded; string error; int r = key.encrypt(g_ceph_context, data, encoded, &error); ASSERT_EQ(r, 0); } utime_t end = ceph_clock_now(); utime_t dur = end - start; cout << n << " encoded in " << dur << std::endl; } TEST(AES, LoopKey) { aes_loopkey(128); } // These magics reflects Cephx's signature size. Please consult // CephxSessionHandler::_calc_signature() for more details. TEST(AES, LoopKey_29) { aes_loopkey(29); } TEST(AES, LoopKey_32) { aes_loopkey(32); }
9,684
27.236152
77
cc
null
ceph-main/src/test/crypto_init.cc
#include <errno.h> #include <time.h> #include <pthread.h> #include <unistd.h> #include <vector> #include "include/types.h" #include "common/code_environment.h" #include "global/global_context.h" #include "global/global_init.h" #include "include/msgr.h" #include "gtest/gtest.h" #include "auth/Crypto.h" #include "common/ceph_crypto.h" // TODO: ensure OpenSSL init int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
471
20.454545
41
cc
null
ceph-main/src/test/cxx11_client.cc
#include "include/buffer.h" // We might want to include here all our public headers. // Not any file residing in src/include has this status. int main() {}
158
21.714286
56
cc
null
ceph-main/src/test/daemon_config.cc
// -*- 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) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "gtest/gtest.h" #include "common/ceph_argparse.h" #include "common/ceph_context.h" #include "common/config.h" #include "global/global_context.h" #include "include/cephfs/libcephfs.h" #include "include/rados/librados.h" #include <errno.h> #include <sstream> #include <string> #include <string.h> #include <boost/lexical_cast.hpp> using namespace std; TEST(DaemonConfig, SimpleSet) { int ret; ret = g_ceph_context->_conf.set_val("log_graylog_port", "21"); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); char buf[128]; memset(buf, 0, sizeof(buf)); char *tmp = buf; ret = g_ceph_context->_conf.get_val("log_graylog_port", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("21"), string(buf)); g_ceph_context->_conf.rm_val("log_graylog_port"); } TEST(DaemonConfig, Substitution) { int ret; g_conf()._clear_safe_to_start_threads(); ret = g_ceph_context->_conf.set_val("host", "foo"); ASSERT_EQ(0, ret); ret = g_ceph_context->_conf.set_val("public_network", "bar$host.baz"); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); char buf[128]; memset(buf, 0, sizeof(buf)); char *tmp = buf; ret = g_ceph_context->_conf.get_val("public_network", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("barfoo.baz"), string(buf)); } TEST(DaemonConfig, SubstitutionTrailing) { int ret; g_conf()._clear_safe_to_start_threads(); ret = g_ceph_context->_conf.set_val("host", "foo"); ASSERT_EQ(0, ret); ret = g_ceph_context->_conf.set_val("public_network", "bar$host"); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); char buf[128]; memset(buf, 0, sizeof(buf)); char *tmp = buf; ret = g_ceph_context->_conf.get_val("public_network", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("barfoo"), string(buf)); } TEST(DaemonConfig, SubstitutionBraces) { int ret; g_conf()._clear_safe_to_start_threads(); ret = g_ceph_context->_conf.set_val("host", "foo"); ASSERT_EQ(0, ret); ret = g_ceph_context->_conf.set_val("public_network", "bar${host}baz"); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); char buf[128]; memset(buf, 0, sizeof(buf)); char *tmp = buf; ret = g_ceph_context->_conf.get_val("public_network", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("barfoobaz"), string(buf)); } TEST(DaemonConfig, SubstitutionBracesTrailing) { int ret; g_conf()._clear_safe_to_start_threads(); ret = g_ceph_context->_conf.set_val("host", "foo"); ASSERT_EQ(0, ret); ret = g_ceph_context->_conf.set_val("public_network", "bar${host}"); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); char buf[128]; memset(buf, 0, sizeof(buf)); char *tmp = buf; ret = g_ceph_context->_conf.get_val("public_network", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("barfoo"), string(buf)); } // config: variable substitution happen only once http://tracker.ceph.com/issues/7103 TEST(DaemonConfig, SubstitutionMultiple) { int ret; ret = g_ceph_context->_conf.set_val("mon_host", "localhost"); ASSERT_EQ(0, ret); ret = g_ceph_context->_conf.set_val("keyring", "$mon_host/$cluster.keyring,$mon_host/$cluster.mon.keyring"); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); char buf[512]; memset(buf, 0, sizeof(buf)); char *tmp = buf; ret = g_ceph_context->_conf.get_val("keyring", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("localhost/ceph.keyring,localhost/ceph.mon.keyring"), tmp); ASSERT_TRUE(strchr(buf, '$') == NULL); } TEST(DaemonConfig, ArgV) { g_conf()._clear_safe_to_start_threads(); int ret; const char *argv[] = { "foo", "--log-graylog-port", "22", "--key", "my-key", NULL }; size_t argc = (sizeof(argv) / sizeof(argv[0])) - 1; auto args = argv_to_vec(argc, argv); g_ceph_context->_conf.parse_argv(args); g_ceph_context->_conf.apply_changes(nullptr); char buf[128]; char *tmp = buf; memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("key", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("my-key"), string(buf)); memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_graylog_port", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("22"), string(buf)); g_conf().set_safe_to_start_threads(); } TEST(DaemonConfig, InjectArgs) { int ret; std::string injection("--log-graylog-port 56 --log_max_new 42"); ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(0, ret); char buf[128]; char *tmp = buf; memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_max_new", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("42"), string(buf)); memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_graylog_port", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("56"), string(buf)); injection = "--log-graylog-port 57"; ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(0, ret); ret = g_ceph_context->_conf.get_val("log_graylog_port", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("57"), string(buf)); } TEST(DaemonConfig, InjectArgsReject) { int ret; char buf[128]; char *tmp = buf; char buf2[128]; char *tmp2 = buf2; // We should complain about the garbage in the input std::string injection("--random-garbage-in-injectargs 26 --log-graylog-port 28"); ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(-EINVAL, ret); // But, debug should still be set... memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_graylog_port", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("28"), string(buf)); // What's the current value of osd_data? memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("osd_data", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); // Injectargs shouldn't let us change this, since it is a string-valued // variable and there isn't an observer for it. std::string injection2("--osd_data /tmp/some-other-directory --log-graylog-port 4"); ret = g_ceph_context->_conf.injectargs(injection2, &cout); ASSERT_EQ(-EPERM, ret); // It should be unchanged. memset(buf2, 0, sizeof(buf2)); ret = g_ceph_context->_conf.get_val("osd_data", &tmp2, sizeof(buf2)); ASSERT_EQ(0, ret); ASSERT_EQ(string(buf), string(buf2)); // We should complain about the missing arguments. std::string injection3("--log-graylog-port 28 --debug_ms"); ret = g_ceph_context->_conf.injectargs(injection3, &cout); ASSERT_EQ(-EINVAL, ret); } TEST(DaemonConfig, InjectArgsBooleans) { int ret; char buf[128]; char *tmp = buf; // Change log_to_syslog std::string injection("--log_to_syslog --log-graylog-port 28"); ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(0, ret); // log_to_syslog should be set... memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_to_syslog", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("true"), string(buf)); // Turn off log_to_syslog injection = "--log_to_syslog=false --log-graylog-port 28"; ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(0, ret); // log_to_syslog should be cleared... memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_to_syslog", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("false"), string(buf)); // Turn on log_to_syslog injection = "--log-graylog-port=1 --log_to_syslog=true --log_max_new 40"; ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(0, ret); // log_to_syslog should be set... memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_to_syslog", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("true"), string(buf)); // parse error injection = "--log-graylog-port 1 --log_to_syslog=falsey --log_max_new 42"; ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(-EINVAL, ret); // log_to_syslog should still be set... memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_to_syslog", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("true"), string(buf)); // debug-ms should still become 42... memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_max_new", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("42"), string(buf)); } TEST(DaemonConfig, InjectArgsLogfile) { int ret; char tmpfile[PATH_MAX]; const char *tmpdir = getenv("TMPDIR"); if (!tmpdir) tmpdir = "/tmp"; snprintf(tmpfile, sizeof(tmpfile), "%s/daemon_config_test.%d", tmpdir, getpid()); std::string injection("--log_file "); injection += tmpfile; // We're allowed to change log_file because there is an observer. ret = g_ceph_context->_conf.injectargs(injection, &cout); ASSERT_EQ(0, ret); // It should have taken effect. char buf[128]; char *tmp = buf; memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("log_file", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string(buf), string(tmpfile)); // The logfile should exist. ASSERT_EQ(0, access(tmpfile, R_OK)); // Let's turn off the logfile. ret = g_ceph_context->_conf.set_val("log_file", ""); ASSERT_EQ(0, ret); g_ceph_context->_conf.apply_changes(nullptr); ret = g_ceph_context->_conf.get_val("log_file", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string(""), string(buf)); // Clean up the garbage unlink(tmpfile); } TEST(DaemonConfig, ThreadSafety1) { int ret; // Verify that we can't change this, since safe_to_start_threads has // been set. ret = g_ceph_context->_conf.set_val("osd_data", ""); ASSERT_EQ(-EPERM, ret); g_conf()._clear_safe_to_start_threads(); // Ok, now we can change this. Since this is just a test, and there are no // OSD threads running, we know changing osd_data won't actually blow up the // world. ret = g_ceph_context->_conf.set_val("osd_data", "/tmp/crazydata"); ASSERT_EQ(0, ret); char buf[128]; char *tmp = buf; memset(buf, 0, sizeof(buf)); ret = g_ceph_context->_conf.get_val("osd_data", &tmp, sizeof(buf)); ASSERT_EQ(0, ret); ASSERT_EQ(string("/tmp/crazydata"), string(buf)); g_conf()._clear_safe_to_start_threads(); ASSERT_EQ(0, ret); } TEST(DaemonConfig, InvalidIntegers) { { int ret = g_ceph_context->_conf.set_val("log_graylog_port", "rhubarb"); ASSERT_EQ(-EINVAL, ret); } { int64_t max = std::numeric_limits<int64_t>::max(); string str = boost::lexical_cast<string>(max); str = str + "999"; // some extra digits to take us out of bounds int ret = g_ceph_context->_conf.set_val("log_graylog_port", str); ASSERT_EQ(-EINVAL, ret); } g_ceph_context->_conf.rm_val("log_graylog_port"); } TEST(DaemonConfig, InvalidFloats) { { double bad_value = 2 * (double)std::numeric_limits<float>::max(); string str = boost::lexical_cast<string>(-bad_value); int ret = g_ceph_context->_conf.set_val("log_stop_at_utilization", str); ASSERT_EQ(-EINVAL, ret); } { double bad_value = 2 * (double)std::numeric_limits<float>::max(); string str = boost::lexical_cast<string>(bad_value); int ret = g_ceph_context->_conf.set_val("log_stop_at_utilization", str); ASSERT_EQ(-EINVAL, ret); } { int ret = g_ceph_context->_conf.set_val("log_stop_at_utilization", "not a float"); ASSERT_EQ(-EINVAL, ret); } } /* * Local Variables: * compile-command: "cd ../../build ; \ * make unittest_daemon_config && ./bin/unittest_daemon_config" * End: */
12,034
30.587927
110
cc
null
ceph-main/src/test/detect-build-env-vars.sh
#!/usr/bin/env bash if [ -n "$CEPH_BUILD_DIR" ] && [ -n "$CEPH_ROOT" ] && [ -n "$CEPH_BIN" ] && [ -n "$CEPH_LIB" ]; then echo "Enivronment Variables Already Set" elif [ -e CMakeCache.txt ]; then echo "Environment Variables Not All Set, Detected Build System CMake" echo "Setting Environment Variables" export CEPH_ROOT=`grep ceph_SOURCE_DIR CMakeCache.txt | cut -d "=" -f 2` export CEPH_BUILD_DIR=`pwd` export CEPH_BIN=$CEPH_BUILD_DIR/bin export CEPH_LIB=$CEPH_BUILD_DIR/lib export PATH=$CEPH_BIN:$PATH export LD_LIBRARY_PATH=$CEPH_LIB else echo "Please execute this command out of the proper directory" exit 1 fi
639
31
100
sh
null
ceph-main/src/test/docker-test-helper.sh
#!/usr/bin/env bash # # Copyright (C) 2014, 2015 Red Hat <[email protected]> # # Author: Loic Dachary <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Library Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Public License for more details. # function get_image_name() { local os_type=$1 local os_version=$2 echo ceph-$os_type-$os_version-$USER } function setup_container() { local os_type=$1 local os_version=$2 local dockercmd=$3 local opts="$4" # rm not valid here opts=${opts//' --rm'}; local image=$(get_image_name $os_type $os_version) local build=true if $dockercmd images $image | grep --quiet "^$image " ; then eval touch --date=$($dockercmd inspect $image | jq '.[0].Created') $image found=$(find -L test/$os_type-$os_version/* -newer $image) rm $image if test -n "$found" ; then $dockercmd rmi $image else build=false fi fi if $build ; then # # In the dockerfile, # replace environment variables %%FOO%% with their content # rm -fr dockerfile cp --dereference --recursive test/$os_type-$os_version dockerfile os_version=$os_version user_id=$(id -u) \ perl -p -e 's/%%(\w+)%%/$ENV{$1}/g' \ dockerfile/Dockerfile.in > dockerfile/Dockerfile $dockercmd $opts build --tag=$image dockerfile rm -fr dockerfile fi } function get_upstream() { git rev-parse --show-toplevel } function get_downstream() { local os_type=$1 local os_version=$2 local image=$(get_image_name $os_type $os_version) local upstream=$(get_upstream) local dir=$(dirname $upstream) echo "$dir/$image" } function setup_downstream() { local os_type=$1 local os_version=$2 local ref=$3 local image=$(get_image_name $os_type $os_version) local upstream=$(get_upstream) local dir=$(dirname $upstream) local downstream=$(get_downstream $os_type $os_version) ( cd $dir if ! test -d $downstream ; then # Inspired by https://github.com/git/git/blob/master/contrib/workdir/git-new-workdir mkdir -p $downstream/.git || return 1 for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache do case $x in */*) mkdir -p "$downstream/.git/$x" ;; esac ln -s "$upstream/.git/$x" "$downstream/.git/$x" done cp "$upstream/.git/HEAD" "$downstream/.git/HEAD" fi cd $downstream git reset --hard $ref || return 1 git submodule sync --recursive || return 1 git submodule update --force --init --recursive || return 1 ) } function run_in_docker() { local os_type=$1 shift local os_version=$1 shift local ref=$1 shift local dockercmd=$1 shift local opts="$1" shift local script=$1 setup_downstream $os_type $os_version $ref || return 1 setup_container $os_type $os_version $dockercmd "$opts" || return 1 local downstream=$(get_downstream $os_type $os_version) local image=$(get_image_name $os_type $os_version) local upstream=$(get_upstream) local ccache mkdir -p $HOME/.ccache ccache="--volume $HOME/.ccache:$HOME/.ccache" user="--user $USER" local cmd="$dockercmd run $opts --name $image --privileged $ccache" cmd+=" --volume $downstream:$downstream" cmd+=" --volume $upstream:$upstream" if test "$dockercmd" = "podman" ; then cmd+=" --userns=keep-id" fi local status=0 if test "$script" = "SHELL" ; then echo Running: $cmd --tty --interactive --workdir $downstream $user $image bash $cmd --tty --interactive --workdir $downstream $user $image bash else echo Running: $cmd --workdir $downstream $user $image "$@" if ! $cmd --workdir $downstream $user $image "$@" ; then status=1 fi fi return $status } function remove_all() { local os_type=$1 local os_version=$2 local dockercmd=$3 local image=$(get_image_name $os_type $os_version) $dockercmd rm $image $dockercmd rmi $image } function usage() { cat <<EOF Run commands within Ceph sources, in a container. Use podman if available, docker if not. $0 [options] command args ... [-h|--help] display usage [--verbose] trace all shell lines [--os-type type] docker image repository (centos, ubuntu, etc.) (defaults to ubuntu) [--os-version version] docker image tag (7 for centos, 16.04 for ubuntu, etc.) (defaults to 16.04) [--ref gitref] git reset --hard gitref before running the command (defaults to git rev-parse HEAD) [--all types+versions] list of docker image repositories and tags [--shell] run an interactive shell in the container [--remove-all] remove the container and the image for the specified types+versions [--no-rm] don't remove the container when finished [--opts options] run the container with 'options' docker-test.sh must be run from a Ceph clone and it will run the command in a container, using a copy of the clone so that long running commands such as make check are not disturbed while development continues. Here is a sample use case including an interactive session and running a unit test: $ grep PRETTY_NAME /etc/os-release PRETTY_NAME="Ubuntu 16.04.7 LTS" $ test/docker-test.sh --os-type centos --os-version 7 --shell HEAD is now at 1caee81 autotools: add --enable-docker bash-4.2$ pwd /srv/ceph/ceph-centos-7 bash-4.2$ cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) bash-4.2$ $ time test/docker-test.sh --os-type centos --os-version 7 unittest_str_map HEAD is now at 1caee81 autotools: add --enable-docker Running main() from gtest_main.cc [==========] Running 2 tests from 1 test case. [----------] Global test environment set-up. [----------] 2 tests from str_map [ RUN ] str_map.json [ OK ] str_map.json (1 ms) [ RUN ] str_map.plaintext [ OK ] str_map.plaintext (0 ms) [----------] 2 tests from str_map (1 ms total) [----------] Global test environment tear-down [==========] 2 tests from 1 test case ran. (1 ms total) [ PASSED ] 2 tests. real 0m3.759s user 0m0.074s sys 0m0.051s The --all argument is a bash associative array literal listing the operating system version for each operating system type. For instance docker-test.sh --all '([ubuntu]="16.04 17.04" [centos]="7")' is strictly equivalent to docker-test.sh --os-type ubuntu --os-version 16.04 docker-test.sh --os-type ubuntu --os-version 17.04 docker-test.sh --os-type centos --os-version 7 The --os-type and --os-version must be exactly as displayed by docker images: $ docker images REPOSITORY TAG IMAGE ID ... centos 7 87e5b6b3ccc1 ... ubuntu 16.04 6b4e8a7373fe ... The --os-type value can be any string in the REPOSITORY column, the --os-version can be any string in the TAG column. The --shell and --remove actions are mutually exclusive. Run make check in centos 7 docker-test.sh --os-type centos --os-version 7 -- make check Run make check on a giant docker-test.sh --ref giant -- make check Run an interactive shell and set resolv.conf to use 172.17.42.1 docker-test.sh --opts --dns=172.17.42.1 --shell Run make check on centos 7, ubuntu 16.04 and ubuntu 17.04 docker-test.sh --all '([ubuntu]="16.04 17.04" [centos]="7")' -- make check EOF } function main_docker() { local dockercmd="docker" if type podman > /dev/null; then dockercmd="podman" fi if ! $dockercmd ps > /dev/null 2>&1 ; then echo "docker not available: $0" return 0 fi local temp temp=$(getopt -o scht:v:o:a:r: --long remove-all,verbose,shell,no-rm,help,os-type:,os-version:,opts:,all:,ref: -n $0 -- "$@") || return 1 eval set -- "$temp" local os_type=ubuntu local os_version=16.04 local all local remove=false local shell=false local opts local ref=$(git rev-parse HEAD) local no-rm=false while true ; do case "$1" in --remove-all) remove=true shift ;; --verbose) set -xe PS4='${BASH_SOURCE[0]}:$LINENO: ${FUNCNAME[0]}: ' shift ;; -s|--shell) shell=true shift ;; -h|--help) usage return 0 ;; -t|--os-type) os_type=$2 shift 2 ;; -v|--os-version) os_version=$2 shift 2 ;; -o|--opts) opts="$2" shift 2 ;; -a|--all) all="$2" shift 2 ;; -r|--ref) ref="$2" shift 2 ;; --no-rm) no-rm=true shift ;; --) shift break ;; *) echo "unexpected argument $1" return 1 ;; esac done if test -z "$all" ; then all="([$os_type]=\"$os_version\")" fi declare -A os_type2versions eval os_type2versions="$all" if ! $no-rm ; then opts+=" --rm" fi for os_type in ${!os_type2versions[@]} ; do for os_version in ${os_type2versions[$os_type]} ; do if $remove ; then remove_all $os_type $os_version $dockercmd || return 1 elif $shell ; then run_in_docker $os_type $os_version $ref $dockercmd "$opts" SHELL || return 1 else run_in_docker $os_type $os_version $ref $dockercmd "$opts" "$@" || return 1 fi done done }
10,592
28.839437
141
sh
null
ceph-main/src/test/docker-test.sh
#!/usr/bin/env bash # # Copyright (C) 2014 Red Hat <[email protected]> # # Author: Loic Dachary <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Library Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Public License for more details. # source test/docker-test-helper.sh main_docker "$@"
649
31.5
70
sh
null
ceph-main/src/test/encoding.cc
#include "include/buffer.h" #include "include/encoding.h" #include <fmt/format.h> #include "gtest/gtest.h" using namespace std; template < typename T > static void test_encode_and_decode(const T& src) { bufferlist bl(1000000); encode(src, bl); T dst; auto i = bl.cbegin(); decode(dst, i); ASSERT_EQ(src, dst) << "Encoding roundtrip changed the string: orig=" << src << ", but new=" << dst; } TEST(EncodingRoundTrip, StringSimple) { string my_str("I am the very model of a modern major general"); test_encode_and_decode < std::string >(my_str); } TEST(EncodingRoundTrip, StringEmpty) { string my_str(""); test_encode_and_decode < std::string >(my_str); } TEST(EncodingRoundTrip, StringNewline) { string my_str("foo bar baz\n"); test_encode_and_decode < std::string >(my_str); } template <typename Size, typename T> static void test_encode_and_nohead_nohead(Size len, const T& src) { bufferlist bl(1000000); encode(len, bl); encode_nohead(src, bl); T dst; auto i = bl.cbegin(); decode(len, i); decode_nohead(len, dst, i); ASSERT_EQ(src, dst) << "Encoding roundtrip changed the string: orig=" << src << ", but new=" << dst; } TEST(EncodingRoundTrip, StringNoHead) { const string str("The quick brown fox jumps over the lazy dog"); auto size = str.size(); test_encode_and_nohead_nohead(static_cast<int>(size), str); test_encode_and_nohead_nohead(static_cast<unsigned>(size), str); test_encode_and_nohead_nohead(static_cast<uint32_t>(size), str); test_encode_and_nohead_nohead(static_cast<__u32>(size), str); test_encode_and_nohead_nohead(static_cast<size_t>(size), str); } TEST(EncodingRoundTrip, BufferListNoHead) { bufferlist bl; bl.append("is this a dagger which i see before me?"); auto size = bl.length(); test_encode_and_nohead_nohead(static_cast<int>(size), bl); test_encode_and_nohead_nohead(static_cast<unsigned>(size), bl); test_encode_and_nohead_nohead(static_cast<uint32_t>(size), bl); test_encode_and_nohead_nohead(static_cast<__u32>(size), bl); test_encode_and_nohead_nohead(static_cast<size_t>(size), bl); } typedef std::multimap < int, std::string > multimap_t; typedef multimap_t::value_type my_val_ty; namespace std { static std::ostream& operator<<(std::ostream& oss, const multimap_t &multimap) { for (multimap_t::const_iterator m = multimap.begin(); m != multimap.end(); ++m) { oss << m->first << "->" << m->second << " "; } return oss; } } TEST(EncodingRoundTrip, Multimap) { multimap_t multimap; multimap.insert( my_val_ty(1, "foo") ); multimap.insert( my_val_ty(2, "bar") ); multimap.insert( my_val_ty(2, "baz") ); multimap.insert( my_val_ty(3, "lucky number 3") ); multimap.insert( my_val_ty(10000, "large number") ); test_encode_and_decode < multimap_t >(multimap); } /////////////////////////////////////////////////////// // ConstructorCounter /////////////////////////////////////////////////////// template <typename T> class ConstructorCounter { public: ConstructorCounter() : data(0) { default_ctor++; } explicit ConstructorCounter(const T& data_) : data(data_) { one_arg_ctor++; } ConstructorCounter(const ConstructorCounter &rhs) : data(rhs.data) { copy_ctor++; } ConstructorCounter &operator=(const ConstructorCounter &rhs) { data = rhs.data; assigns++; return *this; } static void init(void) { default_ctor = 0; one_arg_ctor = 0; copy_ctor = 0; assigns = 0; } static int get_default_ctor(void) { return default_ctor; } static int get_one_arg_ctor(void) { return one_arg_ctor; } static int get_copy_ctor(void) { return copy_ctor; } static int get_assigns(void) { return assigns; } bool operator<(const ConstructorCounter &rhs) const { return data < rhs.data; } bool operator==(const ConstructorCounter &rhs) const { return data == rhs.data; } friend void decode(ConstructorCounter &s, bufferlist::const_iterator& p) { decode(s.data, p); } friend void encode(const ConstructorCounter &s, bufferlist& p) { encode(s.data, p); } friend ostream& operator<<(ostream &oss, const ConstructorCounter &cc) { oss << cc.data; return oss; } T data; private: static int default_ctor; static int one_arg_ctor; static int copy_ctor; static int assigns; }; template class ConstructorCounter <int32_t>; template class ConstructorCounter <int16_t>; typedef ConstructorCounter <int32_t> my_key_t; typedef ConstructorCounter <int16_t> my_val_t; typedef std::multimap < my_key_t, my_val_t > multimap2_t; typedef multimap2_t::value_type val2_ty; template <class T> int ConstructorCounter<T>::default_ctor = 0; template <class T> int ConstructorCounter<T>::one_arg_ctor = 0; template <class T> int ConstructorCounter<T>::copy_ctor = 0; template <class T> int ConstructorCounter<T>::assigns = 0; static std::ostream& operator<<(std::ostream& oss, const multimap2_t &multimap) { for (multimap2_t::const_iterator m = multimap.begin(); m != multimap.end(); ++m) { oss << m->first << "->" << m->second << " "; } return oss; } TEST(EncodingRoundTrip, MultimapConstructorCounter) { multimap2_t multimap2; multimap2.insert( val2_ty(my_key_t(1), my_val_t(10)) ); multimap2.insert( val2_ty(my_key_t(2), my_val_t(20)) ); multimap2.insert( val2_ty(my_key_t(2), my_val_t(30)) ); multimap2.insert( val2_ty(my_key_t(3), my_val_t(40)) ); multimap2.insert( val2_ty(my_key_t(10000), my_val_t(1)) ); my_key_t::init(); my_val_t::init(); test_encode_and_decode < multimap2_t >(multimap2); EXPECT_EQ(my_key_t::get_default_ctor(), 5); EXPECT_EQ(my_key_t::get_one_arg_ctor(), 0); EXPECT_EQ(my_key_t::get_copy_ctor(), 5); EXPECT_EQ(my_key_t::get_assigns(), 0); EXPECT_EQ(my_val_t::get_default_ctor(), 5); EXPECT_EQ(my_val_t::get_one_arg_ctor(), 0); EXPECT_EQ(my_val_t::get_copy_ctor(), 5); EXPECT_EQ(my_val_t::get_assigns(), 0); } namespace ceph { // make sure that the legacy encode/decode methods are selected // over the ones defined using templates. the later is likely to // be slower, see also the definition of "WRITE_INT_DENC" in // include/denc.h template<> void encode<uint64_t, denc_traits<uint64_t>>(const uint64_t&, bufferlist&, uint64_t f) { static_assert(denc_traits<uint64_t>::supported, "should support new encoder"); static_assert(!denc_traits<uint64_t>::featured, "should not be featured"); ASSERT_EQ(0UL, f); // make sure the test fails if i get called ASSERT_TRUE(false); } template<> void encode<ceph_le64, denc_traits<ceph_le64>>(const ceph_le64&, bufferlist&, uint64_t f) { static_assert(denc_traits<ceph_le64>::supported, "should support new encoder"); static_assert(!denc_traits<ceph_le64>::featured, "should not be featured"); ASSERT_EQ(0UL, f); // make sure the test fails if i get called ASSERT_TRUE(false); } } namespace { // search `underlying_type` in denc.h for supported underlying types enum class Colour : int8_t { R,G,B }; ostream& operator<<(ostream& os, Colour c) { switch (c) { case Colour::R: return os << "Colour::R"; case Colour::G: return os << "Colour::G"; case Colour::B: return os << "Colour::B"; default: return os << "Colour::???"; } } } TEST(EncodingRoundTrip, Integers) { // int types { uint64_t i = 42; test_encode_and_decode(i); } { int16_t i = 42; test_encode_and_decode(i); } { bool b = true; test_encode_and_decode(b); } { bool b = false; test_encode_and_decode(b); } // raw encoder { ceph_le64 i; i = 42; test_encode_and_decode(i); } // enum { test_encode_and_decode(Colour::R); // this should not build, as the size of unsigned is not the same on // different archs, that's why denc_traits<> intentionally leaves // `int` and `unsigned int` out of supported types. // // enum E { R, G, B }; // test_encode_and_decode(R); } } TEST(EncodingException, Macros) { const struct { buffer::malformed_input exc; std::string expected_what; } tests[] = { { DECODE_ERR_OLDVERSION(__PRETTY_FUNCTION__, 100, 200), fmt::format("{} no longer understand old encoding version 100 < 200: Malformed input", __PRETTY_FUNCTION__) }, { DECODE_ERR_PAST(__PRETTY_FUNCTION__), fmt::format("{} decode past end of struct encoding: Malformed input", __PRETTY_FUNCTION__) } }; for (auto& [exec, expected_what] : tests) { try { throw exec; } catch (const exception& e) { ASSERT_NE(string(e.what()).find(expected_what), string::npos); } } } TEST(small_encoding, varint) { uint32_t v[][4] = { /* value, varint bytes, signed varint bytes, signed varint bytes (neg) */ {0, 1, 1, 1}, {1, 1, 1, 1}, {2, 1, 1, 1}, {31, 1, 1, 1}, {32, 1, 1, 1}, {0xff, 2, 2, 2}, {0x100, 2, 2, 2}, {0xfff, 2, 2, 2}, {0x1000, 2, 2, 2}, {0x2000, 2, 3, 3}, {0x3fff, 2, 3, 3}, {0x4000, 3, 3, 3}, {0x4001, 3, 3, 3}, {0x10001, 3, 3, 3}, {0x20001, 3, 3, 3}, {0x40001, 3, 3, 3}, {0x80001, 3, 3, 3}, {0x7f0001, 4, 4, 4}, {0xff00001, 4, 5, 5}, {0x1ff00001, 5, 5, 5}, {0xffff0001, 5, 5, 5}, {0xffffffff, 5, 5, 5}, {1074790401, 5, 5, 5}, {0, 0, 0, 0} }; for (unsigned i=0; v[i][1]; ++i) { { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_varint(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][1]); uint32_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_varint(u, p); ASSERT_EQ(v[i][0], u); } { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][2] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][2]); int32_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint(u, p); ASSERT_EQ((int32_t)v[i][0], u); } { bufferlist bl; int64_t x = -(int64_t)v[i][0]; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint(x, app); } cout << std::dec << x << std::hex << "\t" << v[i][3] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][3]); int64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint(u, p); ASSERT_EQ(x, u); } } } TEST(small_encoding, varint_lowz) { uint32_t v[][4] = { /* value, bytes encoded */ {0, 1, 1, 1}, {1, 1, 1, 1}, {2, 1, 1, 1}, {15, 1, 1, 1}, {16, 1, 1, 1}, {31, 1, 2, 2}, {63, 2, 2, 2}, {64, 1, 1, 1}, {0xff, 2, 2, 2}, {0x100, 1, 1, 1}, {0x7ff, 2, 2, 2}, {0xfff, 2, 3, 3}, {0x1000, 1, 1, 1}, {0x4000, 1, 1, 1}, {0x8000, 1, 1, 1}, {0x10000, 1, 2, 2}, {0x20000, 2, 2, 2}, {0x40000, 2, 2, 2}, {0x80000, 2, 2, 2}, {0x7f0000, 2, 2, 2}, {0xffff0000, 4, 4, 4}, {0xffffffff, 5, 5, 5}, {0x41000000, 3, 4, 4}, {0, 0, 0, 0} }; for (unsigned i=0; v[i][1]; ++i) { { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_varint_lowz(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][1]); uint32_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_varint_lowz(u, p); ASSERT_EQ(v[i][0], u); } { bufferlist bl; int64_t x = v[i][0]; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint_lowz(x, app); } cout << std::hex << x << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][2]); int64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint_lowz(u, p); ASSERT_EQ(x, u); } { bufferlist bl; int64_t x = -(int64_t)v[i][0]; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint_lowz(x, app); } cout << std::dec << x << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][3]); int64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint_lowz(u, p); ASSERT_EQ(x, u); } } } TEST(small_encoding, lba) { uint64_t v[][2] = { /* value, bytes encoded */ {0, 4}, {1, 4}, {0xff, 4}, {0x10000, 4}, {0x7f0000, 4}, {0xffff0000, 4}, {0x0fffffff, 4}, {0x1fffffff, 5}, {0xffffffff, 5}, {0x3fffffff000, 4}, {0x7fffffff000, 5}, {0x1fffffff0000, 4}, {0x3fffffff0000, 5}, {0xfffffff00000, 4}, {0x1fffffff00000, 5}, {0x41000000, 4}, {0, 0} }; for (unsigned i=0; v[i][1]; ++i) { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_lba(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][1]); uint64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_lba(u, p); ASSERT_EQ(v[i][0], u); } }
13,939
24.625
102
cc
null
ceph-main/src/test/escape.cc
// -*- 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) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/escape.h" #include "gtest/gtest.h" #include <stdint.h> static std::string escape_xml_attrs(const char *str) { int len = escape_xml_attr_len(str); char out[len]; escape_xml_attr(str, out); return out; } static std::string escape_xml_stream(const char *str) { std::stringstream ss; ss << xml_stream_escaper(str); return ss.str(); } TEST(EscapeXml, PassThrough) { ASSERT_EQ(escape_xml_attrs("simplicity itself"), "simplicity itself"); ASSERT_EQ(escape_xml_stream("simplicity itself"), "simplicity itself"); ASSERT_EQ(escape_xml_attrs(""), ""); ASSERT_EQ(escape_xml_stream(""), ""); ASSERT_EQ(escape_xml_attrs("simple examples please!"), "simple examples please!"); ASSERT_EQ(escape_xml_stream("simple examples please!"), "simple examples please!"); } TEST(EscapeXml, EntityRefs1) { ASSERT_EQ(escape_xml_attrs("The \"scare quotes\""), "The &quot;scare quotes&quot;"); ASSERT_EQ(escape_xml_stream("The \"scare quotes\""), "The &quot;scare quotes&quot;"); ASSERT_EQ(escape_xml_attrs("I <3 XML"), "I &lt;3 XML"); ASSERT_EQ(escape_xml_stream("I <3 XML"), "I &lt;3 XML"); ASSERT_EQ(escape_xml_attrs("Some 'single' \"quotes\" here"), "Some &apos;single&apos; &quot;quotes&quot; here"); ASSERT_EQ(escape_xml_stream("Some 'single' \"quotes\" here"), "Some &apos;single&apos; &quot;quotes&quot; here"); } TEST(EscapeXml, ControlChars) { ASSERT_EQ(escape_xml_attrs("\x01\x02\x03"), "&#x01;&#x02;&#x03;"); ASSERT_EQ(escape_xml_stream("\x01\x02\x03"), "&#x01;&#x02;&#x03;"); ASSERT_EQ(escape_xml_attrs("abc\x7f"), "abc&#x7f;"); ASSERT_EQ(escape_xml_stream("abc\x7f"), "abc&#x7f;"); } TEST(EscapeXml, Utf8) { const char *cc1 = "\xe6\xb1\x89\xe5\xad\x97\n"; ASSERT_EQ(escape_xml_attrs(cc1), cc1); ASSERT_EQ(escape_xml_stream(cc1), cc1); ASSERT_EQ(escape_xml_attrs("<\xe6\xb1\x89\xe5\xad\x97>\n"), "&lt;\xe6\xb1\x89\xe5\xad\x97&gt;\n"); ASSERT_EQ(escape_xml_stream("<\xe6\xb1\x89\xe5\xad\x97>\n"), "&lt;\xe6\xb1\x89\xe5\xad\x97&gt;\n"); } static std::string escape_json_attrs(const char *str, size_t src_len = 0) { if (!src_len) src_len = strlen(str); int len = escape_json_attr_len(str, src_len); char out[len]; escape_json_attr(str, src_len, out); return out; } static std::string escape_json_stream(const char *str, size_t src_len = 0) { if (!src_len) src_len = strlen(str); std::stringstream ss; ss << json_stream_escaper(std::string_view(str, src_len)); return ss.str(); } TEST(EscapeJson, PassThrough) { ASSERT_EQ(escape_json_attrs("simplicity itself"), "simplicity itself"); ASSERT_EQ(escape_json_stream("simplicity itself"), "simplicity itself"); ASSERT_EQ(escape_json_attrs(""), ""); ASSERT_EQ(escape_json_stream(""), ""); ASSERT_EQ(escape_json_attrs("simple examples please!"), "simple examples please!"); ASSERT_EQ(escape_json_stream("simple examples please!"), "simple examples please!"); } TEST(EscapeJson, Escapes1) { ASSERT_EQ(escape_json_attrs("The \"scare quotes\""), "The \\\"scare quotes\\\""); ASSERT_EQ(escape_json_stream("The \"scare quotes\""), "The \\\"scare quotes\\\""); ASSERT_EQ(escape_json_attrs("I <3 JSON"), "I <3 JSON"); ASSERT_EQ(escape_json_stream("I <3 JSON"), "I <3 JSON"); ASSERT_EQ(escape_json_attrs("Some 'single' \"quotes\" here"), "Some 'single' \\\"quotes\\\" here"); ASSERT_EQ(escape_json_stream("Some 'single' \"quotes\" here"), "Some 'single' \\\"quotes\\\" here"); ASSERT_EQ(escape_json_attrs("tabs\tand\tnewlines\n, oh my"), "tabs\\tand\\tnewlines\\n, oh my"); ASSERT_EQ(escape_json_stream("tabs\tand\tnewlines\n, oh my"), "tabs\\tand\\tnewlines\\n, oh my"); } TEST(EscapeJson, ControlChars) { ASSERT_EQ(escape_json_attrs("\x01\x02\x03"), "\\u0001\\u0002\\u0003"); ASSERT_EQ(escape_json_stream("\x01\x02\x03"), "\\u0001\\u0002\\u0003"); ASSERT_EQ(escape_json_stream("\x00\x02\x03", 3), "\\u0000\\u0002\\u0003"); // json can't print binary data! ASSERT_EQ(escape_json_stream("\x00\x7f\xff", 3), "\\u0000\\u007f\xff"); ASSERT_EQ(escape_json_attrs("abc\x7f"), "abc\\u007f"); ASSERT_EQ(escape_json_stream("abc\x7f"), "abc\\u007f"); } TEST(EscapeJson, Utf8) { EXPECT_EQ(escape_json_attrs("\xe6\xb1\x89\xe5\xad\x97\n"), "\xe6\xb1\x89\xe5\xad\x97\\n"); EXPECT_EQ(escape_json_stream("\xe6\xb1\x89\xe5\xad\x97\n"), "\xe6\xb1\x89\xe5\xad\x97\\n"); }
4,786
36.108527
101
cc
null
ceph-main/src/test/fooclass.cc
#include <iostream> #include <string.h> #include <stdlib.h> #include "objclass/objclass.h" CLS_VER(1,0) CLS_NAME(foo) cls_handle_t h_class; cls_method_handle_t h_foo; int foo_method(cls_method_context_t ctx, char *indata, int datalen, char **outdata, int *outdatalen) { int i; cls_log("hello world, this is foo"); cls_log("indata=%s", indata); *outdata = (char *)malloc(128); for (i=0; i<strlen(indata) + 1; i++) { if (indata[i] == '1') { (*outdata)[i] = 'I'; } else { (*outdata)[i] = indata[i]; } } *outdatalen = strlen(*outdata) + 1; cls_log("outdata=%s", *outdata); return 0; } void class_init() { cls_log("Loaded foo class!"); cls_register("foo", &h_class); cls_register_method(h_class, "foo", foo_method, &h_foo); return; }
817
15.693878
67
cc