repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
AICP-main/veins/src/veins/modules/world/annotations/AnnotationManager.h
// // Copyright (C) 2010 Christoph Sommer <christoph.sommer@informatik.uni-erlangen.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // AnnotationManager - manages annotations on the OMNeT++ canvas #pragma once #include <list> #include "veins/veins.h" #include "veins/base/utils/FindModule.h" #include "veins/base/utils/Coord.h" namespace veins { /** * manages annotations on the OMNeT++ canvas. */ class VEINS_API AnnotationManager : public cSimpleModule { public: class VEINS_API Group; class VEINS_API Annotation { public: Annotation() : group(nullptr) , figure(nullptr) { } virtual ~Annotation() { } protected: friend class AnnotationManager; Group* group; mutable cFigure* figure; mutable std::list<std::string> traciPoiIds; mutable std::list<std::string> traciLineIds; mutable std::list<std::string> traciPolygonsIds; }; class VEINS_API Point : public Annotation { public: Point(Coord pos, std::string color, std::string text) : pos(pos) , color(color) , text(text) { } ~Point() override { } protected: friend class AnnotationManager; Coord pos; std::string color; std::string text; }; class VEINS_API Line : public Annotation { public: Line(Coord p1, Coord p2, std::string color) : p1(p1) , p2(p2) , color(color) { } ~Line() override { } protected: friend class AnnotationManager; Coord p1; Coord p2; std::string color; }; class VEINS_API Polygon : public Annotation { public: Polygon(std::list<Coord> coords, std::string color) : coords(coords) , color(color) { } ~Polygon() override { } protected: friend class AnnotationManager; std::list<Coord> coords; std::string color; }; class VEINS_API Group { public: Group(std::string title) : title(title) { } virtual ~Group() { } protected: friend class AnnotationManager; std::string title; }; ~AnnotationManager() override; void initialize() override; void finish() override; void handleMessage(cMessage* msg) override; void handleSelfMsg(cMessage* msg); void handleParameterChange(const char* parname) override; void addFromXml(cXMLElement* xml); Group* createGroup(std::string title = "untitled"); Point* drawPoint(Coord p, std::string color, std::string text, Group* group = nullptr); Line* drawLine(Coord p1, Coord p2, std::string color, Group* group = nullptr); Polygon* drawPolygon(std::list<Coord> coords, std::string color, Group* group = nullptr); Polygon* drawPolygon(std::vector<Coord> coords, std::string color, Group* group = nullptr); void drawBubble(Coord p1, std::string text); void erase(const Annotation* annotation); void eraseAll(Group* group = nullptr); void scheduleErase(simtime_t deltaT, Annotation* annotation); void show(const Annotation* annotation); void hide(const Annotation* annotation); void showAll(Group* group = nullptr); void hideAll(Group* group = nullptr); protected: using Annotations = std::list<Annotation*>; using Groups = std::list<Group*>; cXMLElement* annotationsXml; /**< annotations to add at startup */ std::list<cMessage*> scheduledEraseEvts; Annotations annotations; Groups groups; cGroupFigure* annotationLayer; }; class VEINS_API AnnotationManagerAccess { public: AnnotationManager* getIfExists() { return FindModule<AnnotationManager*>::findGlobalModule(); }; }; } // namespace veins
4,754
24.564516
95
h
null
AICP-main/veins/src/veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.h
// // Copyright (C) 2015-2018 Dominik Buse <dbuse@mail.uni-paderborn.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/modules/mobility/traci/TraCIScenarioManager.h" #include "veins/modules/mobility/traci/TraCICommandInterface.h" #include "veins/modules/world/traci/trafficLight/TraCITrafficLightProgram.h" namespace veins { class VEINS_API TraCITrafficLightInterface : public cSimpleModule { public: TraCITrafficLightInterface(); ~TraCITrafficLightInterface() override; /** Set parameters for connection to TraCI */ virtual void preInitialize(const std::string& external_id, const Coord& position, const simtime_t& updateInterval); virtual void setExternalId(const std::string& external_id) { this->external_id = external_id; } virtual std::string getExternalId() const { if (external_id == "") throw cRuntimeError("TraCITrafficLightInterface::getExternalId called with no external_id set yet"); return external_id; } virtual TraCIScenarioManager* getManager() const { if (!manager) { manager = TraCIScenarioManagerAccess().get(); } return manager; } virtual TraCICommandInterface* getCommandInterface() const { if (!commandInterface) { commandInterface = getManager()->getCommandInterface(); } return commandInterface; } virtual TraCICommandInterface::Trafficlight* getTlCommandInterface() const { if (!tlCommandInterface) { tlCommandInterface = new TraCICommandInterface::Trafficlight(getCommandInterface(), external_id); } return tlCommandInterface; } virtual std::list<std::list<TraCITrafficLightLink>> getControlledLinks(); virtual Coord getPosition() const; virtual TraCITrafficLightProgram::Logic getCurrentLogic() const; virtual std::string getCurrentLogicId() const; virtual int getCurrentPhaseId() const; virtual TraCITrafficLightProgram::Phase getCurrentPhase() const; virtual simtime_t getAssumedNextSwitch() const; virtual simtime_t getRemainingDuration() const; virtual std::string getCurrentState() const; virtual bool isInOnlineSignalState() const; virtual void setProgramDefinition(const TraCITrafficLightProgram& programDefinition); virtual void setControlledLinks(const std::list<std::list<TraCITrafficLightLink>>& controlledLinks); virtual void setCurrentLogicById(const std::string& logicId, bool setSumo = true); virtual void setCurrentPhaseByNr(const unsigned int phaseNr, bool setSumo = true); virtual void setCurrentState(const std::string& state, bool setSumo = true); virtual void setNextSwitch(const simtime_t& newNextSwitch, bool setSumo = true); virtual void setRemainingDuration(const simtime_t& timeTillSwitch, bool setSumo = true); protected: void initialize() override; void handleMessage(cMessage* msg) override; virtual void handleChangeCommandMessage(cMessage* msg); virtual void sendChangeMsg(int changedAttribute, const std::string newValue, const std::string oldValue); bool isPreInitialized; /**< true if preInitialize() has been called immediately before initialize() */ simtime_t updateInterval; /**< ScenarioManager's update interval */ /** reference to the simulations ScenarioManager */ mutable TraCIScenarioManager* manager; /** reference to the simulations traffic light-specific TraCI command interface */ mutable TraCICommandInterface* commandInterface; /** reference to the simulations traffic light-specific TraCI command interface */ mutable TraCICommandInterface::Trafficlight* tlCommandInterface; std::string external_id; /**< id used on the other end of TraCI */ Coord position; /**< position of the traffic light */ TraCITrafficLightProgram programDefinition; /**< full definition of program (all logics) */ std::list<std::list<TraCITrafficLightLink>> controlledLinks; /**< controlledLinks[signal][link] */ // std::list< std::list<TraCITrafficLightLink> > controlledLanes; /**< controlledLanes[signal][link] */ std::string currentLogicId; /**< id of the currently active logic */ int currentPhaseNr; /**< current phase of the current program */ simtime_t nextSwitchTime; /**< predicted next phase switch time (absolute timestamp) */ std::string currentSignalState; /**< current state of the signals (rRgGyY-String) */ bool inOnlineSignalState; /**< whether the TLS is currently set to a manual (i.e. online) phase state */ }; } // namespace veins namespace veins { class VEINS_API TraCITrafficLightInterfaceAccess { public: TraCITrafficLightInterface* get(cModule* host) { TraCITrafficLightInterface* traci = FindModule<TraCITrafficLightInterface*>::findSubModule(host); ASSERT(traci); return traci; }; }; } // namespace veins
5,743
42.515152
131
h
null
AICP-main/veins/src/veins/modules/world/traci/trafficLight/TraCITrafficLightProgram.h
// // Copyright (C) 2015-2018 Dominik Buse <dbuse@mail.uni-paderborn.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include <string> #include <vector> #include <map> #include "veins/veins.h" using omnetpp::simtime_t; namespace veins { class VEINS_API TraCITrafficLightProgram { public: struct Phase { simtime_t duration; std::string state; simtime_t minDuration; simtime_t maxDuration; std::vector<int32_t> next; std::string name; bool isGreenPhase() const; }; struct Logic { std::string id; int32_t currentPhase; std::vector<Phase> phases; int32_t type; // currently unused, just 0 int32_t parameter; // currently unused, just 0 }; TraCITrafficLightProgram(std::string id = ""); void addLogic(const Logic& logic); TraCITrafficLightProgram::Logic getLogic(const std::string& lid) const; bool hasLogic(const std::string& lid) const; private: std::string id; std::map<std::string, TraCITrafficLightProgram::Logic> logics; }; struct VEINS_API TraCITrafficLightLink { std::string incoming; std::string outgoing; std::string internal; }; } // namespace veins
2,019
27.055556
76
h
null
AICP-main/veins/src/veins/modules/world/traci/trafficLight/logics/TraCITrafficLightAbstractLogic.h
// // Copyright (C) 2015-2018 Dominik Buse <dbuse@mail.uni-paderborn.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/modules/messages/TraCITrafficLightMessage_m.h" namespace veins { using omnetpp::cMessage; using omnetpp::cSimpleModule; /** * Base class to simplify implementation of traffic light logics * * already provides multiplexing of different message types to message handlers and a * special handler to be executed right before the TraCI server performs a phase switch */ class VEINS_API TraCITrafficLightAbstractLogic : public cSimpleModule { public: TraCITrafficLightAbstractLogic(); ~TraCITrafficLightAbstractLogic() override; protected: cMessage* switchTimer; void initialize() override; void handleMessage(cMessage* msg) override; virtual void handleSelfMsg(cMessage* msg); virtual void handleApplMsg(cMessage* msg) = 0; virtual void handleTlIfMsg(TraCITrafficLightMessage* tlMsg) = 0; virtual void handlePossibleSwitch() = 0; }; } // namespace veins
1,860
32.232143
87
h
null
AICP-main/veins/src/veins/modules/world/traci/trafficLight/logics/TraCITrafficLightSimpleLogic.h
// // Copyright (C) 2015-2018 Dominik Buse <dbuse@mail.uni-paderborn.de> // // Documentation for these modules is at http://veins.car2x.org/ // // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #pragma once #include "veins/veins.h" #include "veins/base/utils/FindModule.h" #include "veins/modules/world/traci/trafficLight/logics/TraCITrafficLightAbstractLogic.h" #include "veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.h" namespace veins { class VEINS_API TraCITrafficLightSimpleLogic : public TraCITrafficLightAbstractLogic { public: using signalScheme = std::string; protected: void handleApplMsg(cMessage* msg) override; void handleTlIfMsg(TraCITrafficLightMessage* tlMsg) override; void handlePossibleSwitch() override; }; class VEINS_API TraCITrafficLightSimpleLogicAccess { public: TraCITrafficLightSimpleLogic* get(cModule* host) { TraCITrafficLightSimpleLogic* traci = FindModule<TraCITrafficLightSimpleLogic*>::findSubModule(host); ASSERT(traci); return traci; }; }; } // namespace veins
1,791
32.185185
109
h
LiDAR2LiDAR
LiDAR2LiDAR-master/geotransformer/geotransformer/extensions/common/torch_helper.h
#pragma once #include <ATen/cuda/CUDAContext.h> #include <torch/extension.h> #define CHECK_CUDA(x) \ TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CPU(x) \ TORCH_CHECK(!x.device().is_cuda(), #x " must be a CPU tensor") #define CHECK_CONTIGUOUS(x) \ TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) \ CHECK_CUDA(x); \ CHECK_CONTIGUOUS(x) #define CHECK_IS_INT(x) \ do { \ TORCH_CHECK(x.scalar_type() == at::ScalarType::Int, \ #x " must be an int tensor"); \ } while (0) #define CHECK_IS_LONG(x) \ do { \ TORCH_CHECK(x.scalar_type() == at::ScalarType::Long, \ #x " must be an long tensor"); \ } while (0) #define CHECK_IS_FLOAT(x) \ do { \ TORCH_CHECK(x.scalar_type() == at::ScalarType::Float, \ #x " must be a float tensor"); \ } while (0)
1,698
46.194444
79
h
LiDAR2LiDAR
LiDAR2LiDAR-master/geotransformer/geotransformer/extensions/extra/cloud/cloud.h
// Modified from https://github.com/HuguesTHOMAS/KPConv-PyTorch #pragma once #include <vector> #include <unordered_map> #include <map> #include <algorithm> #include <numeric> #include <iostream> #include <iomanip> #include <cmath> #include <time.h> class PointXYZ { public: float x, y, z; PointXYZ() { x = 0; y = 0; z = 0; } PointXYZ(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } float operator [] (int i) const { if (i == 0) { return x; } else if (i == 1) { return y; } else { return z; } } float dot(const PointXYZ P) const { return x * P.x + y * P.y + z * P.z; } float sq_norm() { return x * x + y * y + z * z; } PointXYZ cross(const PointXYZ P) const { return PointXYZ(y * P.z - z * P.y, z * P.x - x * P.z, x * P.y - y * P.x); } PointXYZ& operator+=(const PointXYZ& P) { x += P.x; y += P.y; z += P.z; return *this; } PointXYZ& operator-=(const PointXYZ& P) { x -= P.x; y -= P.y; z -= P.z; return *this; } PointXYZ& operator*=(const float& a) { x *= a; y *= a; z *= a; return *this; } }; inline PointXYZ operator + (const PointXYZ A, const PointXYZ B) { return PointXYZ(A.x + B.x, A.y + B.y, A.z + B.z); } inline PointXYZ operator - (const PointXYZ A, const PointXYZ B) { return PointXYZ(A.x - B.x, A.y - B.y, A.z - B.z); } inline PointXYZ operator * (const PointXYZ P, const float a) { return PointXYZ(P.x * a, P.y * a, P.z * a); } inline PointXYZ operator * (const float a, const PointXYZ P) { return PointXYZ(P.x * a, P.y * a, P.z * a); } inline std::ostream& operator << (std::ostream& os, const PointXYZ P) { return os << "[" << P.x << ", " << P.y << ", " << P.z << "]"; } inline bool operator == (const PointXYZ A, const PointXYZ B) { return A.x == B.x && A.y == B.y && A.z == B.z; } inline PointXYZ floor(const PointXYZ P) { return PointXYZ(std::floor(P.x), std::floor(P.y), std::floor(P.z)); } PointXYZ max_point(std::vector<PointXYZ> points); PointXYZ min_point(std::vector<PointXYZ> points); struct PointCloud { std::vector<PointXYZ> pts; inline size_t kdtree_get_point_count() const { return pts.size(); } // Returns the dim'th component of the idx'th point in the class: // Since this is inlined and the "dim" argument is typically an immediate value, the // "if/else's" are actually solved at compile time. inline float kdtree_get_pt(const size_t idx, const size_t dim) const { if (dim == 0) { return pts[idx].x; } else if (dim == 1) { return pts[idx].y; } else { return pts[idx].z; } } // Optional bounding-box computation: return false to default to a standard bbox computation loop. // Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again. // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX& /* bb */) const { return false; } };
3,099
21.463768
124
h
null
ceph-main/examples/librados/hello_world_c.c
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * Copyright 2013 Inktank */ // install the librados-dev package to get this #include <rados/librados.h> #include <stdio.h> #include <stdlib.h> int main(int argc, const char **argv) { int ret = 0; // we will use all of these below const char *pool_name = "hello_world_pool"; const char* hello = "hello world!"; const char* object_name = "hello_object"; rados_ioctx_t io_ctx = NULL; int pool_created = 0; // first, we create a Rados object and initialize it rados_t rados = NULL; { ret = rados_create(&rados, "admin"); // just use the client.admin keyring if (ret < 0) { // let's handle any error that might have come back printf("couldn't initialize rados! error %d\n", ret); ret = EXIT_FAILURE; goto out; } printf("we just set up a rados cluster object\n"); } /* * Now we need to get the rados object its config info. It can * parse argv for us to find the id, monitors, etc, so let's just * use that. */ { ret = rados_conf_parse_argv(rados, argc, argv); if (ret < 0) { // This really can't happen, but we need to check to be a good citizen. printf("failed to parse config options! error %d\n", ret); ret = EXIT_FAILURE; goto out; } printf("we just parsed our config options\n"); // We also want to apply the config file if the user specified // one, and conf_parse_argv won't do that for us. int i; for (i = 0; i < argc; ++i) { if ((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "--conf") == 0)) { ret = rados_conf_read_file(rados, argv[i+1]); if (ret < 0) { // This could fail if the config file is malformed, but it'd be hard. printf("failed to parse config file %s! error %d\n", argv[i+1], ret); ret = EXIT_FAILURE; goto out; } break; } } } /* * next, we actually connect to the cluster */ { ret = rados_connect(rados); if (ret < 0) { printf("couldn't connect to cluster! error %d\n", ret); ret = EXIT_FAILURE; goto out; } printf("we just connected to the rados cluster\n"); } /* * let's create our own pool instead of scribbling over real data. * Note that this command creates pools with default PG counts specified * by the monitors, which may not be appropriate for real use -- it's fine * for testing, though. */ { ret = rados_pool_create(rados, pool_name); if (ret < 0) { printf("couldn't create pool! error %d\n", ret); return EXIT_FAILURE; } printf("we just created a new pool named %s\n", pool_name); pool_created = 1; } /* * create an "IoCtx" which is used to do IO to a pool */ { ret = rados_ioctx_create(rados, pool_name, &io_ctx); if (ret < 0) { printf("couldn't set up ioctx! error %d\n", ret); ret = EXIT_FAILURE; goto out; } printf("we just created an ioctx for our pool\n"); } /* * now let's do some IO to the pool! We'll write "hello world!" to a * new object. */ { /* * now that we have the data to write, let's send it to an object. * We'll use the synchronous interface for simplicity. */ ret = rados_write_full(io_ctx, object_name, hello, strlen(hello)); if (ret < 0) { printf("couldn't write object! error %d\n", ret); ret = EXIT_FAILURE; goto out; } printf("we just wrote new object %s, with contents '%s'\n", object_name, hello); } /* * now let's read that object back! Just for fun, we'll do it using * async IO instead of synchronous. (This would be more useful if we * wanted to send off multiple reads at once; see * http://docs.ceph.com/docs/master/rados/api/librados/#asychronous-io ) */ { int read_len = 4194304; // this is way more than we need char* read_buf = malloc(read_len + 1); // add one for the terminating 0 we'll add later if (!read_buf) { printf("couldn't allocate read buffer\n"); ret = EXIT_FAILURE; goto out; } // allocate the completion from librados rados_completion_t read_completion; ret = rados_aio_create_completion2(NULL, NULL, &read_completion); if (ret < 0) { printf("couldn't create completion! error %d\n", ret); ret = EXIT_FAILURE; free(read_buf); goto out; } printf("we just created a new completion\n"); // send off the request. ret = rados_aio_read(io_ctx, object_name, read_completion, read_buf, read_len, 0); if (ret < 0) { printf("couldn't start read object! error %d\n", ret); ret = EXIT_FAILURE; free(read_buf); rados_aio_release(read_completion); goto out; } // wait for the request to complete, and check that it succeeded. rados_aio_wait_for_complete(read_completion); ret = rados_aio_get_return_value(read_completion); if (ret < 0) { printf("couldn't read object! error %d\n", ret); ret = EXIT_FAILURE; free(read_buf); rados_aio_release(read_completion); goto out; } read_buf[ret] = 0; // null-terminate the string printf("we read our object %s, and got back %d bytes with contents\n%s\n", object_name, ret, read_buf); free(read_buf); rados_aio_release(read_completion); } /* * We can also use xattrs that go alongside the object. */ { const char* version = "1"; ret = rados_setxattr(io_ctx, object_name, "version", version, strlen(version)); if (ret < 0) { printf("failed to set xattr version entry! error %d\n", ret); ret = EXIT_FAILURE; goto out; } printf("we set the xattr 'version' on our object!\n"); } /* * And if we want to be really cool, we can do multiple things in a single * atomic operation. For instance, we can update the contents of our object * and set the version at the same time. */ { const char* content = "v2"; rados_write_op_t write_op = rados_create_write_op(); if (!write_op) { printf("failed to allocate write op\n"); ret = EXIT_FAILURE; goto out; } rados_write_op_write_full(write_op, content, strlen(content)); const char* version = "2"; rados_write_op_setxattr(write_op, "version", version, strlen(version)); ret = rados_write_op_operate(write_op, io_ctx, object_name, NULL, 0); if (ret < 0) { printf("failed to do compound write! error %d\n", ret); ret = EXIT_FAILURE; rados_release_write_op(write_op); goto out; } printf("we overwrote our object %s with contents\n%s\n", object_name, content); rados_release_write_op(write_op); } /* * And to be even cooler, we can make sure that the object looks the * way we expect before doing the write! Notice how this attempt fails * because the xattr differs. */ { rados_write_op_t failed_write_op = rados_create_write_op(); if (!failed_write_op) { printf("failed to allocate write op\n"); ret = EXIT_FAILURE; goto out; } const char* content = "v2"; const char* version = "2"; const char* old_version = "1"; rados_write_op_cmpxattr(failed_write_op, "version", LIBRADOS_CMPXATTR_OP_EQ, old_version, strlen(old_version)); rados_write_op_write_full(failed_write_op, content, strlen(content)); rados_write_op_setxattr(failed_write_op, "version", version, strlen(version)); ret = rados_write_op_operate(failed_write_op, io_ctx, object_name, NULL, 0); if (ret < 0) { printf("we just failed a write because the xattr wasn't as specified\n"); } else { printf("we succeeded on writing despite an xattr comparison mismatch!\n"); ret = EXIT_FAILURE; rados_release_write_op(failed_write_op); goto out; } rados_release_write_op(failed_write_op); /* * Now let's do the update with the correct xattr values so it * actually goes through */ content = "v3"; old_version = "2"; version = "3"; rados_write_op_t update_op = rados_create_write_op(); if (!failed_write_op) { printf("failed to allocate write op\n"); ret = EXIT_FAILURE; goto out; } rados_write_op_cmpxattr(update_op, "version", LIBRADOS_CMPXATTR_OP_EQ, old_version, strlen(old_version)); rados_write_op_write_full(update_op, content, strlen(content)); rados_write_op_setxattr(update_op, "version", version, strlen(version)); ret = rados_write_op_operate(update_op, io_ctx, object_name, NULL, 0); if (ret < 0) { printf("failed to do a compound write update! error %d\n", ret); ret = EXIT_FAILURE; rados_release_write_op(update_op); goto out; } printf("we overwrote our object %s following an xattr test with contents\n%s\n", object_name, content); rados_release_write_op(update_op); } ret = EXIT_SUCCESS; out: if (io_ctx) { rados_ioctx_destroy(io_ctx); } if (pool_created) { /* * And now we're done, so let's remove our pool and then * shut down the connection gracefully. */ int delete_ret = rados_pool_delete(rados, pool_name); if (delete_ret < 0) { // be careful not to printf("We failed to delete our test pool!\n"); ret = EXIT_FAILURE; } } rados_shutdown(rados); return ret; }
9,667
30.698361
115
c
null
ceph-main/qa/btrfs/clone_range.c
#include <fcntl.h> #include <stdlib.h> #include <sys/ioctl.h> #include <string.h> #include <linux/types.h> #include "../../src/os/btrfs_ioctl.h" #include <stdio.h> #include <errno.h> int main(int argc, char **argv) { struct btrfs_ioctl_clone_range_args ca; int dfd; int r; if (argc < 6) { printf("usage: %s <srcfn> <srcoffset> <srclen> <destfn> <destoffset>\n", argv[0]); exit(1); } ca.src_fd = open(argv[1], O_RDONLY); ca.src_offset = atoi(argv[2]); ca.src_length = atoi(argv[3]); dfd = open(argv[4], O_WRONLY|O_CREAT); ca.dest_offset = atoi(argv[5]); r = ioctl(dfd, BTRFS_IOC_CLONE_RANGE, &ca); printf("clone_range %s %lld %lld~%lld to %s %d %lld = %d %s\n", argv[1], ca.src_fd, ca.src_offset, ca.src_length, argv[4], dfd, ca.dest_offset, r, strerror(errno)); return r; }
919
24.555556
84
c
null
ceph-main/qa/btrfs/create_async_snap.c
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <sys/ioctl.h> #include <string.h> #include <linux/ioctl.h> #include <linux/types.h> #include "../../src/os/btrfs_ioctl.h" struct btrfs_ioctl_vol_args_v2 va; int main(int argc, char **argv) { int fd; int r; if (argc != 3) { printf("usage: %s <source subvol> <name>\n", argv[0]); return 1; } printf("creating snap ./%s from %s\n", argv[2], argv[1]); fd = open(".", O_RDONLY); va.fd = open(argv[1], O_RDONLY); va.flags = BTRFS_SUBVOL_CREATE_ASYNC; strcpy(va.name, argv[2]); r = ioctl(fd, BTRFS_IOC_SNAP_CREATE_V2, (unsigned long long)&va); printf("result %d\n", r ? -errno:0); return r; }
757
20.657143
66
c
null
ceph-main/qa/btrfs/test_async_snap.c
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <sys/ioctl.h> #include <string.h> #include <linux/ioctl.h> #include <linux/types.h> #include "../../src/os/btrfs_ioctl.h" struct btrfs_ioctl_vol_args_v2 va; struct btrfs_ioctl_vol_args vold; int max = 4; void check_return(int r) { if (r < 0) { printf("********* failed with %d %s ********\n", errno, strerror(errno)); exit(1); } } int main(int argc, char **argv) { int num = 1000; if (argc > 1) num = atoi(argv[1]); printf("will do %d iterations\n", num); int cwd = open(".", O_RDONLY); printf("cwd = %d\n", cwd); while (num-- > 0) { if (rand() % 10 == 0) { __u64 transid; int r; printf("sync starting\n"); r = ioctl(cwd, BTRFS_IOC_START_SYNC, &transid); check_return(r); printf("sync started, transid %lld, waiting\n", transid); r = ioctl(cwd, BTRFS_IOC_WAIT_SYNC, &transid); check_return(r); printf("sync finished\n"); } int i = rand() % max; struct stat st; va.fd = cwd; sprintf(va.name, "test.%d", i); va.transid = 0; int r = stat(va.name, &st); if (r < 0) { if (rand() % 3 == 0) { printf("snap create (sync) %s\n", va.name); va.flags = 0; r = ioctl(cwd, BTRFS_IOC_SNAP_CREATE_V2, &va); check_return(r); } else { printf("snap create (async) %s\n", va.name); va.flags = BTRFS_SUBVOL_CREATE_ASYNC; r = ioctl(cwd, BTRFS_IOC_SNAP_CREATE_V2, &va); check_return(r); printf("snap created, transid %lld\n", va.transid); if (rand() % 2 == 0) { printf("waiting for async snap create\n"); r = ioctl(cwd, BTRFS_IOC_WAIT_SYNC, &va.transid); check_return(r); } } } else { printf("snap remove %s\n", va.name); vold.fd = va.fd; strcpy(vold.name, va.name); r = ioctl(cwd, BTRFS_IOC_SNAP_DESTROY, &vold); check_return(r); } } return 0; }
2,148
24.583333
75
c
null
ceph-main/qa/btrfs/test_rmdir_async_snap.c
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <sys/ioctl.h> #include <string.h> #include <linux/ioctl.h> #include <linux/types.h> #include "../../src/os/btrfs_ioctl.h" struct btrfs_ioctl_vol_args_v2 va; struct btrfs_ioctl_vol_args vold; int main(int argc, char **argv) { int num = 1000; int i, r, fd; char buf[30]; if (argc > 1) num = atoi(argv[1]); printf("will do %d iterations\n", num); fd = open(".", O_RDONLY); vold.fd = 0; strcpy(vold.name, "current"); r = ioctl(fd, BTRFS_IOC_SUBVOL_CREATE, (unsigned long int)&vold); printf("create current ioctl got %d\n", r ? errno:0); if (r) return 1; for (i=0; i<num; i++) { sprintf(buf, "current/dir.%d", i); r = mkdir(buf, 0755); printf("mkdir got %d\n", r ? errno:0); if (r) return 1; } va.fd = open("current", O_RDONLY); va.flags = BTRFS_SUBVOL_CREATE_ASYNC; for (i=0; i<num; i++) { system("/bin/cp /boot/vmlinuz-3.2.0-ceph-00142-g9e98323 current/foo"); sprintf(buf, "current/dir.%d", i); r = rmdir(buf); printf("rmdir got %d\n", r ? errno:0); if (r) return 1; if (i % 10) continue; sprintf(va.name, "snap.%d", i); r = ioctl(fd, BTRFS_IOC_SNAP_CREATE_V2, (unsigned long long)&va); printf("ioctl got %d\n", r ? errno:0); if (r) return 1; } return 0; }
1,373
20.809524
72
c
null
ceph-main/qa/libceph/trivial_libceph.c
#define _FILE_OFFSET_BITS 64 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/statvfs.h> #include "../../src/include/cephfs/libcephfs.h" #define MB64 (1<<26) int main(int argc, const char **argv) { struct ceph_mount_info *cmount; int ret, fd, len; char buf[1024]; if (argc < 3) { fprintf(stderr, "usage: ./%s <conf> <file>\n", argv[0]); exit(1); } ret = ceph_create(&cmount, NULL); if (ret) { fprintf(stderr, "ceph_create=%d\n", ret); exit(1); } ret = ceph_conf_read_file(cmount, argv[1]); if (ret) { fprintf(stderr, "ceph_conf_read_file=%d\n", ret); exit(1); } ret = ceph_conf_parse_argv(cmount, argc, argv); if (ret) { fprintf(stderr, "ceph_conf_parse_argv=%d\n", ret); exit(1); } ret = ceph_mount(cmount, NULL); if (ret) { fprintf(stderr, "ceph_mount=%d\n", ret); exit(1); } ret = ceph_chdir(cmount, "/"); if (ret) { fprintf(stderr, "ceph_chdir=%d\n", ret); exit(1); } fd = ceph_open(cmount, argv[2], O_CREAT|O_TRUNC|O_RDWR, 0777); if (fd < 0) { fprintf(stderr, "ceph_open=%d\n", fd); exit(1); } memset(buf, 'a', sizeof(buf)); len = ceph_write(cmount, fd, buf, sizeof(buf), 0); fprintf(stdout, "wrote %d bytes\n", len); ceph_shutdown(cmount); return 0; }
1,709
23.428571
72
c
null
ceph-main/qa/workunits/direct_io/direct_io_test.c
/* * 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 <errno.h> #include <inttypes.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> /* * direct_io_test * * This test does some I/O using O_DIRECT. * * Semantics of O_DIRECT can be found at http://lwn.net/Articles/348739/ * */ static int g_num_pages = 100; static int g_duration = 10; struct chunk { uint64_t offset; uint64_t pad0; uint64_t pad1; uint64_t pad2; uint64_t pad3; uint64_t pad4; uint64_t pad5; uint64_t not_offset; } __attribute__((packed)); static int page_size; static char temp_file[] = "direct_io_temp_file_XXXXXX"; static int safe_write(int fd, const void *buf, signed int len) { const char *b = (const char*)buf; /* Handle EINTR and short writes */ while (1) { int res = write(fd, b, len); if (res < 0) { int err = errno; if (err != EINTR) { return err; } } len -= res; b += res; if (len <= 0) return 0; } } static int do_read(int fd, char *buf, int buf_sz) { /* We assume no short reads or EINTR. It's not really clear how * those things interact with O_DIRECT. */ int ret = read(fd, buf, buf_sz); if (ret < 0) { int err = errno; printf("do_read: error: %d (%s)\n", err, strerror(err)); return err; } if (ret != buf_sz) { printf("do_read: short read\n"); return -EIO; } return 0; } static int setup_temp_file(void) { int fd; int64_t num_chunks, i; if (page_size % sizeof(struct chunk)) { printf("setup_big_file: page_size doesn't divide evenly " "into data blocks.\n"); return -EINVAL; } fd = mkstemp(temp_file); if (fd < 0) { int err = errno; printf("setup_big_file: mkostemps failed with error %d\n", err); return err; } num_chunks = g_num_pages * (page_size / sizeof(struct chunk)); for (i = 0; i < num_chunks; ++i) { int ret; struct chunk c; memset(&c, 0, sizeof(c)); c.offset = i * sizeof(struct chunk); c.pad0 = 0; c.pad1 = 1; c.pad2 = 2; c.pad3 = 3; c.pad4 = 4; c.pad5 = 5; c.not_offset = ~c.offset; ret = safe_write(fd, &c, sizeof(struct chunk)); if (ret) { printf("setup_big_file: safe_write failed with " "error: %d\n", ret); TEMP_FAILURE_RETRY(close(fd)); unlink(temp_file); return ret; } } TEMP_FAILURE_RETRY(close(fd)); return 0; } static int verify_chunk(const struct chunk *c, uint64_t offset) { if (c->offset != offset) { printf("verify_chunk(%" PRId64 "): bad offset value (got: %" PRId64 ", expected: %" PRId64 "\n", offset, c->offset, offset); return EIO; } if (c->pad0 != 0) { printf("verify_chunk(%" PRId64 "): bad pad0 value\n", offset); return EIO; } if (c->pad1 != 1) { printf("verify_chunk(%" PRId64 "): bad pad1 value\n", offset); return EIO; } if (c->pad2 != 2) { printf("verify_chunk(%" PRId64 "): bad pad2 value\n", offset); return EIO; } if (c->pad3 != 3) { printf("verify_chunk(%" PRId64 "): bad pad3 value\n", offset); return EIO; } if (c->pad4 != 4) { printf("verify_chunk(%" PRId64 "): bad pad4 value\n", offset); return EIO; } if (c->pad5 != 5) { printf("verify_chunk(%" PRId64 "): bad pad5 value\n", offset); return EIO; } if (c->not_offset != ~offset) { printf("verify_chunk(%" PRId64 "): bad not_offset value\n", offset); return EIO; } return 0; } static int do_o_direct_reads(void) { int fd, ret; unsigned int i; void *buf = 0; time_t cur_time, end_time; ret = posix_memalign(&buf, page_size, page_size); if (ret) { printf("do_o_direct_reads: posix_memalign returned %d\n", ret); goto done; } fd = open(temp_file, O_RDONLY | O_DIRECT); if (fd < 0) { ret = errno; printf("do_o_direct_reads: error opening fd: %d\n", ret); goto free_buf; } // read the first chunk and see if it looks OK ret = do_read(fd, buf, page_size); if (ret) goto close_fd; ret = verify_chunk((struct chunk*)buf, 0); if (ret) goto close_fd; // read some random chunks and see how they look cur_time = time(NULL); end_time = cur_time + g_duration; i = 0; do { time_t next_time; uint64_t offset; int page; unsigned int seed; seed = i++; page = rand_r(&seed) % g_num_pages; offset = page; offset *= page_size; if (lseek64(fd, offset, SEEK_SET) == -1) { int err = errno; printf("lseek64(%" PRId64 ") failed: error %d (%s)\n", offset, err, strerror(err)); goto close_fd; } ret = do_read(fd, buf, page_size); if (ret) goto close_fd; ret = verify_chunk((struct chunk*)buf, offset); if (ret) goto close_fd; next_time = time(NULL); if (next_time > cur_time) { printf("."); } cur_time = next_time; } while (time(NULL) < end_time); printf("\ndo_o_direct_reads: SUCCESS\n"); close_fd: TEMP_FAILURE_RETRY(close(fd)); free_buf: free(buf); done: return ret; } static void usage(char *argv0) { printf("%s: tests direct I/O\n", argv0); printf("-d <seconds>: sets duration to <seconds>\n"); printf("-h: this help\n"); printf("-p <pages>: sets number of pages to allocate\n"); } static void parse_args(int argc, char *argv[]) { int c; while ((c = getopt (argc, argv, "d:hp:")) != -1) { switch (c) { case 'd': g_duration = atoi(optarg); if (g_duration <= 0) { printf("tried to set invalid value of " "g_duration: %d\n", g_num_pages); exit(1); } break; case 'h': usage(argv[0]); exit(0); break; case 'p': g_num_pages = atoi(optarg); if (g_num_pages <= 0) { printf("tried to set invalid value of " "g_num_pages: %d\n", g_num_pages); exit(1); } break; case '?': usage(argv[0]); exit(1); break; default: usage(argv[0]); exit(1); break; } } } int main(int argc, char *argv[]) { int ret; parse_args(argc, argv); setvbuf(stdout, NULL, _IONBF, 0); page_size = getpagesize(); ret = setup_temp_file(); if (ret) { printf("setup_temp_file failed with error %d\n", ret); goto done; } ret = do_o_direct_reads(); if (ret) { printf("do_o_direct_reads failed with error %d\n", ret); goto unlink_temp_file; } unlink_temp_file: unlink(temp_file); done: return ret; }
9,251
28.559105
86
c
null
ceph-main/qa/workunits/direct_io/test_sync_io.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <inttypes.h> #include <linux/types.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <errno.h> //#include "../client/ioctl.h" #include <linux/ioctl.h> #define CEPH_IOCTL_MAGIC 0x97 #define CEPH_IOC_SYNCIO _IO(CEPH_IOCTL_MAGIC, 5) void write_pattern() { printf("writing pattern\n"); uint64_t i; int r; int fd = open("foo", O_CREAT|O_WRONLY, 0644); if (fd < 0) { r = errno; printf("write_pattern: error: open() failed with: %d (%s)\n", r, strerror(r)); exit(r); } for (i=0; i<1048576 * sizeof(i); i += sizeof(i)) { r = write(fd, &i, sizeof(i)); if (r == -1) { r = errno; printf("write_pattern: error: write() failed with: %d (%s)\n", r, strerror(r)); break; } } close(fd); } int verify_pattern(char *buf, size_t len, uint64_t off) { size_t i; for (i = 0; i < len; i += sizeof(uint64_t)) { uint64_t expected = i + off; uint64_t actual = *(uint64_t*)(buf + i); if (expected != actual) { printf("error: offset %llu had %llu\n", (unsigned long long)expected, (unsigned long long)actual); exit(1); } } return 0; } void generate_pattern(void *buf, size_t len, uint64_t offset) { uint64_t *v = buf; size_t i; for (i=0; i<len / sizeof(v); i++) v[i] = i * sizeof(v) + offset; verify_pattern(buf, len, offset); } int read_file(int buf_align, uint64_t offset, int len, int direct) { printf("read_file buf_align %d offset %llu len %d\n", buf_align, (unsigned long long)offset, len); void *rawbuf; int r; int flags; int err = 0; if(direct) flags = O_RDONLY|O_DIRECT; else flags = O_RDONLY; int fd = open("foo", flags); if (fd < 0) { err = errno; printf("read_file: error: open() failed with: %d (%s)\n", err, strerror(err)); exit(err); } if (!direct) ioctl(fd, CEPH_IOC_SYNCIO); if ((r = posix_memalign(&rawbuf, 4096, len + buf_align)) != 0) { printf("read_file: error: posix_memalign failed with %d", r); close(fd); exit (r); } void *buf = (char *)rawbuf + buf_align; memset(buf, 0, len); r = pread(fd, buf, len, offset); if (r == -1) { err = errno; printf("read_file: error: pread() failed with: %d (%s)\n", err, strerror(err)); goto out; } r = verify_pattern(buf, len, offset); out: close(fd); free(rawbuf); return r; } int read_direct(int buf_align, uint64_t offset, int len) { printf("read_direct buf_align %d offset %llu len %d\n", buf_align, (unsigned long long)offset, len); return read_file(buf_align, offset, len, 1); } int read_sync(int buf_align, uint64_t offset, int len) { printf("read_sync buf_align %d offset %llu len %d\n", buf_align, (unsigned long long)offset, len); return read_file(buf_align, offset, len, 0); } int write_file(int buf_align, uint64_t offset, int len, int direct) { printf("write_file buf_align %d offset %llu len %d\n", buf_align, (unsigned long long)offset, len); void *rawbuf; int r; int err = 0; int flags; if (direct) flags = O_WRONLY|O_DIRECT|O_CREAT; else flags = O_WRONLY|O_CREAT; int fd = open("foo", flags, 0644); if (fd < 0) { int err = errno; printf("write_file: error: open() failed with: %d (%s)\n", err, strerror(err)); exit(err); } if ((r = posix_memalign(&rawbuf, 4096, len + buf_align)) != 0) { printf("write_file: error: posix_memalign failed with %d", r); err = r; goto out_close; } if (!direct) ioctl(fd, CEPH_IOC_SYNCIO); void *buf = (char *)rawbuf + buf_align; generate_pattern(buf, len, offset); r = pwrite(fd, buf, len, offset); close(fd); fd = open("foo", O_RDONLY); if (fd < 0) { err = errno; printf("write_file: error: open() failed with: %d (%s)\n", err, strerror(err)); free(rawbuf); goto out_unlink; } void *buf2 = malloc(len); if (!buf2) { err = -ENOMEM; printf("write_file: error: malloc failed\n"); goto out_free; } memset(buf2, 0, len); r = pread(fd, buf2, len, offset); if (r == -1) { err = errno; printf("write_file: error: pread() failed with: %d (%s)\n", err, strerror(err)); goto out_free_buf; } r = verify_pattern(buf2, len, offset); out_free_buf: free(buf2); out_free: free(rawbuf); out_close: close(fd); out_unlink: unlink("foo"); if (err) exit(err); return r; } int write_direct(int buf_align, uint64_t offset, int len) { printf("write_direct buf_align %d offset %llu len %d\n", buf_align, (unsigned long long)offset, len); return write_file (buf_align, offset, len, 1); } int write_sync(int buf_align, uint64_t offset, int len) { printf("write_sync buf_align %d offset %llu len %d\n", buf_align, (unsigned long long)offset, len); return write_file (buf_align, offset, len, 0); } int main(int argc, char **argv) { uint64_t i, j, k; int read = 1; int write = 1; if (argc >= 2 && strcmp(argv[1], "read") == 0) write = 0; if (argc >= 2 && strcmp(argv[1], "write") == 0) read = 0; if (read) { write_pattern(); for (i = 0; i < 4096; i += 512) for (j = 4*1024*1024 - 4096; j < 4*1024*1024 + 4096; j += 512) for (k = 1024; k <= 16384; k *= 2) { read_direct(i, j, k); read_sync(i, j, k); } } unlink("foo"); if (write) { for (i = 0; i < 4096; i += 512) for (j = 4*1024*1024 - 4096 + 512; j < 4*1024*1024 + 4096; j += 512) for (k = 1024; k <= 16384; k *= 2) { write_direct(i, j, k); write_sync(i, j, k); } } return 0; }
5,551
21.119522
84
c
null
ceph-main/src/SimpleRADOSStriper.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) 2021 Red Hat, Inc. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 2.1, as published by * the Free Software Foundation. See file COPYING. * */ #ifndef _SIMPLERADOSSTRIPER_H #define _SIMPLERADOSSTRIPER_H #include <queue> #include <string_view> #include <thread> #include "include/buffer.h" #include "include/rados/librados.hpp" #include "include/uuid.h" #include "include/types.h" #include "common/ceph_time.h" #include "common/perf_counters.h" class [[gnu::visibility("default")]] SimpleRADOSStriper { public: using aiocompletionptr = std::unique_ptr<librados::AioCompletion>; using clock = ceph::coarse_mono_clock; using time = ceph::coarse_mono_time; static inline const uint64_t object_size = 22; /* power of 2 */ static inline const uint64_t min_growth = (1<<27); /* 128 MB */ static int config_logger(CephContext* cct, std::string_view name, std::shared_ptr<PerfCounters>* l); SimpleRADOSStriper() = default; SimpleRADOSStriper(librados::IoCtx _ioctx, std::string _oid) : ioctx(std::move(_ioctx)) , oid(std::move(_oid)) { cookie.generate_random(); auto r = librados::Rados(ioctx); myaddrs = r.get_addrs(); } SimpleRADOSStriper(const SimpleRADOSStriper&) = delete; SimpleRADOSStriper& operator=(const SimpleRADOSStriper&) = delete; SimpleRADOSStriper& operator=(SimpleRADOSStriper&&) = delete; SimpleRADOSStriper(SimpleRADOSStriper&&) = delete; ~SimpleRADOSStriper(); int create(); int open(); int remove(); int stat(uint64_t* size); ssize_t write(const void* data, size_t len, uint64_t off); ssize_t read(void* data, size_t len, uint64_t off); int truncate(size_t size); int flush(); int lock(uint64_t timeoutms); int unlock(); int is_locked() const { return locked; } int print_lockers(std::ostream& out); void set_logger(std::shared_ptr<PerfCounters> l) { logger = std::move(l); } void set_lock_interval(std::chrono::milliseconds t) { lock_keeper_interval = t; } void set_lock_timeout(std::chrono::milliseconds t) { lock_keeper_timeout = t; } void set_blocklist_the_dead(bool b) { blocklist_the_dead = b; } protected: struct extent { std::string soid; size_t len; size_t off; }; ceph::bufferlist str2bl(std::string_view sv); ceph::bufferlist uint2bl(uint64_t v); int set_metadata(uint64_t new_size, bool update_size); int shrink_alloc(uint64_t a); int maybe_shrink_alloc(); int wait_for_aios(bool block); int recover_lock(); extent get_next_extent(uint64_t off, size_t len) const; extent get_first_extent() const { return get_next_extent(0, 0); } private: static inline const char XATTR_EXCL[] = "striper.excl"; static inline const char XATTR_SIZE[] = "striper.size"; static inline const char XATTR_ALLOCATED[] = "striper.allocated"; static inline const char XATTR_VERSION[] = "striper.version"; static inline const char XATTR_LAYOUT_STRIPE_UNIT[] = "striper.layout.stripe_unit"; static inline const char XATTR_LAYOUT_STRIPE_COUNT[] = "striper.layout.stripe_count"; static inline const char XATTR_LAYOUT_OBJECT_SIZE[] = "striper.layout.object_size"; static inline const std::string biglock = "striper.lock"; static inline const std::string lockdesc = "SimpleRADOSStriper"; void lock_keeper_main(); librados::IoCtx ioctx; std::shared_ptr<PerfCounters> logger; std::string oid; std::thread lock_keeper; std::condition_variable lock_keeper_cvar; std::mutex lock_keeper_mutex; time last_renewal = time::min(); std::chrono::milliseconds lock_keeper_interval{2000}; std::chrono::milliseconds lock_keeper_timeout{30000}; std::atomic<bool> blocklisted = false; bool shutdown = false; version_t version = 0; std::string exclusive_holder; uint64_t size = 0; uint64_t allocated = 0; uuid_d cookie{}; bool locked = false; bool size_dirty = false; bool blocklist_the_dead = true; std::queue<aiocompletionptr> aios; int aios_failure = 0; std::string myaddrs; }; #endif /* _SIMPLERADOSSTRIPER_H */
4,279
29.571429
102
h
null
ceph-main/src/perf_histogram.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 OVH * * 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_COMMON_PERF_HISTOGRAM_H #define CEPH_COMMON_PERF_HISTOGRAM_H #include "common/Formatter.h" #include "include/int_types.h" #include <array> #include <atomic> #include <memory> #include "include/ceph_assert.h" class PerfHistogramCommon { public: enum scale_type_d : uint8_t { SCALE_LINEAR = 1, SCALE_LOG2 = 2, }; struct axis_config_d { const char *m_name = nullptr; scale_type_d m_scale_type = SCALE_LINEAR; int64_t m_min = 0; int64_t m_quant_size = 0; int32_t m_buckets = 0; axis_config_d() = default; axis_config_d(const char* name, scale_type_d scale_type, int64_t min, int64_t quant_size, int32_t buckets) : m_name(name), m_scale_type(scale_type), m_min(min), m_quant_size(quant_size), m_buckets(buckets) {} }; protected: /// Dump configuration of one axis to a formatter static void dump_formatted_axis(ceph::Formatter *f, const axis_config_d &ac); /// Quantize given value and convert to bucket number on given axis static int64_t get_bucket_for_axis(int64_t value, const axis_config_d &ac); /// Calculate inclusive ranges of axis values for each bucket on that axis static std::vector<std::pair<int64_t, int64_t>> get_axis_bucket_ranges( const axis_config_d &ac); }; /// PerfHistogram does trace a histogram of input values. It's an extended /// version of a standard histogram which does trace characteristics of a single /// one value only. In this implementation, values can be traced in multiple /// dimensions - i.e. we can create a histogram of input request size (first /// dimension) and processing latency (second dimension). Creating standard /// histogram out of such multidimensional one is trivial and requires summing /// values across dimensions we're not interested in. template <int DIM = 2> class PerfHistogram : public PerfHistogramCommon { public: /// Initialize new histogram object PerfHistogram(std::initializer_list<axis_config_d> axes_config) { ceph_assert(axes_config.size() == DIM && "Invalid number of axis configuration objects"); int i = 0; for (const auto &ac : axes_config) { ceph_assertf(ac.m_buckets > 0, "Must have at least one bucket on axis"); ceph_assertf(ac.m_quant_size > 0, "Quantization unit must be non-zero positive integer value"); m_axes_config[i++] = ac; } m_rawData.reset(new std::atomic<uint64_t>[get_raw_size()]); } /// Copy from other histogram object PerfHistogram(const PerfHistogram &other) : m_axes_config(other.m_axes_config) { int64_t size = get_raw_size(); m_rawData.reset(new std::atomic<uint64_t>[size]); for (int64_t i = 0; i < size; i++) { m_rawData[i] = other.m_rawData[i]; } } /// Set all histogram values to 0 void reset() { auto size = get_raw_size(); for (auto i = size; --i >= 0;) { m_rawData[i] = 0; } } /// Increase counter for given axis values by one template <typename... T> void inc(T... axis) { auto index = get_raw_index_for_value(axis...); m_rawData[index] += 1; } /// Increase counter for given axis buckets by one template <typename... T> void inc_bucket(T... bucket) { auto index = get_raw_index_for_bucket(bucket...); m_rawData[index] += 1; } /// Read value from given bucket template <typename... T> uint64_t read_bucket(T... bucket) const { auto index = get_raw_index_for_bucket(bucket...); return m_rawData[index]; } /// Dump data to a Formatter object void dump_formatted(ceph::Formatter *f) const { // Dump axes configuration f->open_array_section("axes"); for (auto &ac : m_axes_config) { dump_formatted_axis(f, ac); } f->close_section(); // Dump histogram values dump_formatted_values(f); } protected: /// Raw data stored as linear space, internal indexes are calculated on /// demand. std::unique_ptr<std::atomic<uint64_t>[]> m_rawData; /// Configuration of axes std::array<axis_config_d, DIM> m_axes_config; /// Dump histogram counters to a formatter void dump_formatted_values(ceph::Formatter *f) const { visit_values([f](int) { f->open_array_section("values"); }, [f](int64_t value) { f->dump_unsigned("value", value); }, [f](int) { f->close_section(); }); } /// Get number of all histogram counters int64_t get_raw_size() { int64_t ret = 1; for (const auto &ac : m_axes_config) { ret *= ac.m_buckets; } return ret; } /// Calculate m_rawData index from axis values template <typename... T> int64_t get_raw_index_for_value(T... axes) const { static_assert(sizeof...(T) == DIM, "Incorrect number of arguments"); return get_raw_index_internal<0>(get_bucket_for_axis, 0, axes...); } /// Calculate m_rawData index from axis bucket numbers template <typename... T> int64_t get_raw_index_for_bucket(T... buckets) const { static_assert(sizeof...(T) == DIM, "Incorrect number of arguments"); return get_raw_index_internal<0>( [](int64_t bucket, const axis_config_d &ac) { ceph_assertf(bucket >= 0, "Bucket index can not be negative"); ceph_assertf(bucket < ac.m_buckets, "Bucket index too large"); return bucket; }, 0, buckets...); } template <int level = 0, typename F, typename... T> int64_t get_raw_index_internal(F bucket_evaluator, int64_t startIndex, int64_t value, T... tail) const { static_assert(level + 1 + sizeof...(T) == DIM, "Internal consistency check"); auto &ac = m_axes_config[level]; auto bucket = bucket_evaluator(value, ac); return get_raw_index_internal<level + 1>( bucket_evaluator, ac.m_buckets * startIndex + bucket, tail...); } template <int level, typename F> int64_t get_raw_index_internal(F, int64_t startIndex) const { static_assert(level == DIM, "Internal consistency check"); return startIndex; } /// Visit all histogram counters, call onDimensionEnter / onDimensionLeave /// when starting / finishing traversal /// on given axis, call onValue when dumping raw histogram counter value. template <typename FDE, typename FV, typename FDL> void visit_values(FDE onDimensionEnter, FV onValue, FDL onDimensionLeave, int level = 0, int startIndex = 0) const { if (level == DIM) { onValue(m_rawData[startIndex]); return; } onDimensionEnter(level); auto &ac = m_axes_config[level]; startIndex *= ac.m_buckets; for (int32_t i = 0; i < ac.m_buckets; ++i, ++startIndex) { visit_values(onDimensionEnter, onValue, onDimensionLeave, level + 1, startIndex); } onDimensionLeave(level); } }; #endif
7,206
30.334783
80
h
null
ceph-main/src/arch/intel.c
/* * Ceph - scalable distributed file system * * Copyright (C) 2013,2014 Inktank Storage, Inc. * Copyright (C) 2014 Cloudwatt <libre.licensing@cloudwatt.com> * * Author: Loic Dachary <loic@dachary.org> * * 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. * */ #include <stdio.h> #include "arch/probe.h" /* flags we export */ int ceph_arch_intel_pclmul = 0; int ceph_arch_intel_sse42 = 0; int ceph_arch_intel_sse41 = 0; int ceph_arch_intel_ssse3 = 0; int ceph_arch_intel_sse3 = 0; int ceph_arch_intel_sse2 = 0; int ceph_arch_intel_aesni = 0; #ifdef __x86_64__ #include <cpuid.h> /* http://en.wikipedia.org/wiki/CPUID#EAX.3D1:_Processor_Info_and_Feature_Bits */ #define CPUID_PCLMUL (1 << 1) #define CPUID_SSE42 (1 << 20) #define CPUID_SSE41 (1 << 19) #define CPUID_SSSE3 (1 << 9) #define CPUID_SSE3 (1) #define CPUID_SSE2 (1 << 26) #define CPUID_AESNI (1 << 25) int ceph_arch_intel_probe(void) { /* i know how to check this on x86_64... */ unsigned int eax, ebx, ecx = 0, edx = 0; if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx)) { return 1; } if ((ecx & CPUID_PCLMUL) != 0) { ceph_arch_intel_pclmul = 1; } if ((ecx & CPUID_SSE42) != 0) { ceph_arch_intel_sse42 = 1; } if ((ecx & CPUID_SSE41) != 0) { ceph_arch_intel_sse41 = 1; } if ((ecx & CPUID_SSSE3) != 0) { ceph_arch_intel_ssse3 = 1; } if ((ecx & CPUID_SSE3) != 0) { ceph_arch_intel_sse3 = 1; } if ((edx & CPUID_SSE2) != 0) { ceph_arch_intel_sse2 = 1; } if ((ecx & CPUID_AESNI) != 0) { ceph_arch_intel_aesni = 1; } return 0; } #else // __x86_64__ int ceph_arch_intel_probe(void) { /* no features */ return 0; } #endif // __x86_64__
1,883
22.259259
81
c
null
ceph-main/src/arch/intel.h
#ifndef CEPH_ARCH_INTEL_H #define CEPH_ARCH_INTEL_H #ifdef __cplusplus extern "C" { #endif extern int ceph_arch_intel_pclmul; /* true if we have PCLMUL features */ extern int ceph_arch_intel_sse42; /* true if we have sse 4.2 features */ extern int ceph_arch_intel_sse41; /* true if we have sse 4.1 features */ extern int ceph_arch_intel_ssse3; /* true if we have ssse 3 features */ extern int ceph_arch_intel_sse3; /* true if we have sse 3 features */ extern int ceph_arch_intel_sse2; /* true if we have sse 2 features */ extern int ceph_arch_intel_aesni; /* true if we have aesni features */ extern int ceph_arch_intel_probe(void); #ifdef __cplusplus } #endif #endif
681
28.652174
73
h
null
ceph-main/src/arch/ppc.c
/* Copyright (C) 2017 International Business Machines Corp. * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include "arch/ppc.h" #include "arch/probe.h" /* flags we export */ int ceph_arch_ppc_crc32 = 0; #include <stdio.h> #ifdef HAVE_PPC64LE #include <sys/auxv.h> #include <asm/cputable.h> #endif /* HAVE_PPC64LE */ #ifndef PPC_FEATURE2_VEC_CRYPTO #define PPC_FEATURE2_VEC_CRYPTO 0x02000000 #endif #ifndef AT_HWCAP2 #define AT_HWCAP2 26 #endif int ceph_arch_ppc_probe(void) { ceph_arch_ppc_crc32 = 0; #ifdef HAVE_PPC64LE if (getauxval(AT_HWCAP2) & PPC_FEATURE2_VEC_CRYPTO) ceph_arch_ppc_crc32 = 1; #endif /* HAVE_PPC64LE */ return 0; }
889
20.707317
78
c
null
ceph-main/src/arch/ppc.h
/* Copyright (C) 2017 International Business Machines Corp. * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef CEPH_ARCH_PPC_H #define CEPH_ARCH_PPC_H #ifdef __cplusplus extern "C" { #endif extern int ceph_arch_ppc_crc32; extern int ceph_arch_ppc_probe(void); #ifdef __cplusplus } #endif #endif
540
20.64
64
h
null
ceph-main/src/auth/Auth.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHTYPES_H #define CEPH_AUTHTYPES_H #include "Crypto.h" #include "common/entity_name.h" // The _MAX values are a bit wonky here because we are overloading the first // byte of the auth payload to identify both the type of authentication to be // used *and* the encoding version for the authenticator. So, we define a // range. enum { AUTH_MODE_NONE = 0, AUTH_MODE_AUTHORIZER = 1, AUTH_MODE_AUTHORIZER_MAX = 9, AUTH_MODE_MON = 10, AUTH_MODE_MON_MAX = 19, }; struct EntityAuth { CryptoKey key; std::map<std::string, ceph::buffer::list> caps; CryptoKey pending_key; ///< new but uncommitted key void encode(ceph::buffer::list& bl) const { __u8 struct_v = 3; using ceph::encode; encode(struct_v, bl); encode((uint64_t)CEPH_AUTH_UID_DEFAULT, bl); encode(key, bl); encode(caps, bl); encode(pending_key, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); if (struct_v >= 2) { uint64_t old_auid; decode(old_auid, bl); } decode(key, bl); decode(caps, bl); if (struct_v >= 3) { decode(pending_key, bl); } } }; WRITE_CLASS_ENCODER(EntityAuth) inline std::ostream& operator<<(std::ostream& out, const EntityAuth& a) { out << "auth(key=" << a.key; if (!a.pending_key.empty()) { out << " pending_key=" << a.pending_key; } out << ")"; return out; } struct AuthCapsInfo { bool allow_all; ceph::buffer::list caps; AuthCapsInfo() : allow_all(false) {} void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); __u8 a = (__u8)allow_all; encode(a, bl); encode(caps, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); __u8 a; decode(a, bl); allow_all = (bool)a; decode(caps, bl); } }; WRITE_CLASS_ENCODER(AuthCapsInfo) /* * The ticket (if properly validated) authorizes the principal use * services as described by 'caps' during the specified validity * period. */ struct AuthTicket { EntityName name; uint64_t global_id; /* global instance id */ utime_t created, renew_after, expires; AuthCapsInfo caps; __u32 flags; AuthTicket() : global_id(0), flags(0){} void init_timestamps(utime_t now, double ttl) { created = now; expires = now; expires += ttl; renew_after = now; renew_after += ttl / 2.0; } void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 2; encode(struct_v, bl); encode(name, bl); encode(global_id, bl); encode((uint64_t)CEPH_AUTH_UID_DEFAULT, bl); encode(created, bl); encode(expires, bl); encode(caps, bl); encode(flags, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(name, bl); decode(global_id, bl); if (struct_v >= 2) { uint64_t old_auid; decode(old_auid, bl); } decode(created, bl); decode(expires, bl); decode(caps, bl); decode(flags, bl); } }; WRITE_CLASS_ENCODER(AuthTicket) /* * abstract authorizer class */ struct AuthAuthorizer { __u32 protocol; ceph::buffer::list bl; CryptoKey session_key; explicit AuthAuthorizer(__u32 p) : protocol(p) {} virtual ~AuthAuthorizer() {} virtual bool verify_reply(ceph::buffer::list::const_iterator& reply, std::string *connection_secret) = 0; virtual bool add_challenge(CephContext *cct, const ceph::buffer::list& challenge) = 0; }; struct AuthAuthorizerChallenge { virtual ~AuthAuthorizerChallenge() {} }; struct AuthConnectionMeta { uint32_t auth_method = CEPH_AUTH_UNKNOWN; //< CEPH_AUTH_* /// client: initial empty, but populated if server said bad method std::vector<uint32_t> allowed_methods; int auth_mode = AUTH_MODE_NONE; ///< AUTH_MODE_* int con_mode = 0; ///< negotiated mode bool is_mode_crc() const { return con_mode == CEPH_CON_MODE_CRC; } bool is_mode_secure() const { return con_mode == CEPH_CON_MODE_SECURE; } CryptoKey session_key; ///< per-ticket key size_t get_connection_secret_length() const { switch (con_mode) { case CEPH_CON_MODE_CRC: return 0; case CEPH_CON_MODE_SECURE: return 16 * 4; } return 0; } std::string connection_secret; ///< per-connection key std::unique_ptr<AuthAuthorizer> authorizer; std::unique_ptr<AuthAuthorizerChallenge> authorizer_challenge; ///< set if msgr1 peer doesn't support CEPHX_V2 bool skip_authorizer_challenge = false; }; /* * Key management */ #define KEY_ROTATE_NUM 3 /* prev, current, next */ struct ExpiringCryptoKey { CryptoKey key; utime_t expiration; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(key, bl); encode(expiration, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(key, bl); decode(expiration, bl); } }; WRITE_CLASS_ENCODER(ExpiringCryptoKey) inline std::ostream& operator<<(std::ostream& out, const ExpiringCryptoKey& c) { return out << c.key << " expires " << c.expiration; } struct RotatingSecrets { std::map<uint64_t, ExpiringCryptoKey> secrets; version_t max_ver; RotatingSecrets() : max_ver(0) {} void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(secrets, bl); encode(max_ver, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(secrets, bl); decode(max_ver, bl); } uint64_t add(ExpiringCryptoKey& key) { secrets[++max_ver] = key; while (secrets.size() > KEY_ROTATE_NUM) secrets.erase(secrets.begin()); return max_ver; } bool need_new_secrets() const { return secrets.size() < KEY_ROTATE_NUM; } bool need_new_secrets(const utime_t& now) const { return secrets.size() < KEY_ROTATE_NUM || current().expiration <= now; } ExpiringCryptoKey& previous() { return secrets.begin()->second; } ExpiringCryptoKey& current() { auto p = secrets.begin(); ++p; return p->second; } const ExpiringCryptoKey& current() const { auto p = secrets.begin(); ++p; return p->second; } ExpiringCryptoKey& next() { return secrets.rbegin()->second; } bool empty() { return secrets.empty(); } void dump(); }; WRITE_CLASS_ENCODER(RotatingSecrets) class KeyStore { public: virtual ~KeyStore() {} virtual bool get_secret(const EntityName& name, CryptoKey& secret) const = 0; virtual bool get_service_secret(uint32_t service_id, uint64_t secret_id, CryptoKey& secret) const = 0; }; inline bool auth_principal_needs_rotating_keys(EntityName& name) { uint32_t ty(name.get_type()); return ((ty == CEPH_ENTITY_TYPE_OSD) || (ty == CEPH_ENTITY_TYPE_MDS) || (ty == CEPH_ENTITY_TYPE_MGR)); } #endif
7,619
22.8125
79
h
null
ceph-main/src/auth/AuthAuthorizeHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHAUTHORIZEHANDLER_H #define CEPH_AUTHAUTHORIZEHANDLER_H #include "Auth.h" #include "include/common_fwd.h" #include "include/types.h" #include "common/ceph_mutex.h" // Different classes of session crypto handling #define SESSION_CRYPTO_NONE 0 #define SESSION_SYMMETRIC_AUTHENTICATE 1 #define SESSION_SYMMETRIC_ENCRYPT 2 class KeyRing; struct AuthAuthorizeHandler { virtual ~AuthAuthorizeHandler() {} virtual bool verify_authorizer( CephContext *cct, const KeyStore& keys, const ceph::buffer::list& authorizer_data, size_t connection_secret_required_len, ceph::buffer::list *authorizer_reply, EntityName *entity_name, uint64_t *global_id, AuthCapsInfo *caps_info, CryptoKey *session_key, std::string *connection_secret, std::unique_ptr<AuthAuthorizerChallenge> *challenge) = 0; virtual int authorizer_session_crypto() = 0; }; #endif
1,331
26.75
71
h
null
ceph-main/src/auth/AuthClient.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <cstdint> #include <vector> #include "include/buffer_fwd.h" class AuthConnectionMeta; class Connection; class CryptoKey; class AuthClient { public: virtual ~AuthClient() {} /// Build an authentication request to begin the handshake virtual int get_auth_request( Connection *con, AuthConnectionMeta *auth_meta, uint32_t *method, std::vector<uint32_t> *preferred_modes, ceph::buffer::list *out) = 0; /// Handle server's request to continue the handshake virtual int handle_auth_reply_more( Connection *con, AuthConnectionMeta *auth_meta, const ceph::buffer::list& bl, ceph::buffer::list *reply) = 0; /// Handle server's indication that authentication succeeded virtual int handle_auth_done( Connection *con, AuthConnectionMeta *auth_meta, uint64_t global_id, uint32_t con_mode, const ceph::buffer::list& bl, CryptoKey *session_key, std::string *connection_secret) = 0; /// Handle server's indication that the previous auth attempt failed virtual int handle_auth_bad_method( Connection *con, AuthConnectionMeta *auth_meta, uint32_t old_auth_method, int result, const std::vector<uint32_t>& allowed_methods, const std::vector<uint32_t>& allowed_modes) = 0; };
1,390
25.75
70
h
null
ceph-main/src/auth/AuthClientHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHCLIENTHANDLER_H #define CEPH_AUTHCLIENTHANDLER_H #include "auth/Auth.h" #include "include/common_fwd.h" class RotatingKeyRing; class AuthClientHandler { protected: CephContext *cct; EntityName name; uint64_t global_id; uint32_t want; uint32_t have; uint32_t need; public: explicit AuthClientHandler(CephContext *cct_) : cct(cct_), global_id(0), want(CEPH_ENTITY_TYPE_AUTH), have(0), need(0) {} virtual ~AuthClientHandler() {} virtual AuthClientHandler* clone() const = 0; void init(const EntityName& n) { name = n; } void set_want_keys(__u32 keys) { want = keys | CEPH_ENTITY_TYPE_AUTH; validate_tickets(); } virtual int get_protocol() const = 0; virtual void reset() = 0; virtual void prepare_build_request() = 0; virtual void build_initial_request(ceph::buffer::list *bl) const { // this is empty for methods cephx and none. } virtual int build_request(ceph::buffer::list& bl) const = 0; virtual int handle_response(int ret, ceph::buffer::list::const_iterator& iter, CryptoKey *session_key, std::string *connection_secret) = 0; virtual bool build_rotating_request(ceph::buffer::list& bl) const = 0; virtual AuthAuthorizer *build_authorizer(uint32_t service_id) const = 0; virtual bool need_tickets() = 0; virtual void set_global_id(uint64_t id) = 0; static AuthClientHandler* create(CephContext* cct, int proto, RotatingKeyRing* rkeys); protected: virtual void validate_tickets() = 0; }; #endif
1,947
25.324324
88
h
null
ceph-main/src/auth/AuthMethodList.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHMETHODLIST_H #define CEPH_AUTHMETHODLIST_H #include "include/common_fwd.h" #include "include/int_types.h" #include <list> #include <set> #include <string> class AuthMethodList { std::list<__u32> auth_supported; public: AuthMethodList(CephContext *cct, std::string str); bool is_supported_auth(int auth_type); int pick(const std::set<__u32>& supported); const std::list<__u32>& get_supported_set() const { return auth_supported; } void remove_supported_auth(int auth_type); }; #endif
955
21.761905
71
h
null
ceph-main/src/auth/AuthRegistry.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <map> #include <vector> #include "AuthAuthorizeHandler.h" #include "AuthMethodList.h" #include "common/ceph_mutex.h" #include "common/ceph_context.h" #include "common/config_cacher.h" class AuthRegistry : public md_config_obs_t { CephContext *cct; mutable ceph::mutex lock = ceph::make_mutex("AuthRegistry::lock"); std::map<int,AuthAuthorizeHandler*> authorize_handlers; bool _no_keyring_disabled_cephx = false; // CEPH_AUTH_* std::vector<uint32_t> cluster_methods; std::vector<uint32_t> service_methods; std::vector<uint32_t> client_methods; // CEPH_CON_MODE_* std::vector<uint32_t> mon_cluster_modes; std::vector<uint32_t> mon_service_modes; std::vector<uint32_t> mon_client_modes; std::vector<uint32_t> cluster_modes; std::vector<uint32_t> service_modes; std::vector<uint32_t> client_modes; void _parse_method_list(const std::string& str, std::vector<uint32_t> *v); void _parse_mode_list(const std::string& str, std::vector<uint32_t> *v); void _refresh_config(); public: AuthRegistry(CephContext *cct); ~AuthRegistry(); void refresh_config() { std::scoped_lock l(lock); _refresh_config(); } void get_supported_methods(int peer_type, std::vector<uint32_t> *methods, std::vector<uint32_t> *modes=nullptr) const; bool is_supported_method(int peer_type, int method) const; bool any_supported_methods(int peer_type) const; void get_supported_modes(int peer_type, uint32_t auth_method, std::vector<uint32_t> *modes) const; uint32_t pick_mode(int peer_type, uint32_t auth_method, const std::vector<uint32_t>& preferred_modes); static bool is_secure_method(uint32_t method) { return (method == CEPH_AUTH_CEPHX); } static bool is_secure_mode(uint32_t mode) { return (mode == CEPH_CON_MODE_SECURE); } AuthAuthorizeHandler *get_handler(int peer_type, int method); const char** get_tracked_conf_keys() const override; void handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) override; bool no_keyring_disabled_cephx() { std::scoped_lock l(lock); return _no_keyring_disabled_cephx; } };
2,310
27.182927
76
h
null
ceph-main/src/auth/AuthServer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "AuthRegistry.h" #include "include/common_fwd.h" #include <vector> class Connection; class AuthServer { public: AuthRegistry auth_registry; AuthServer(CephContext *cct) : auth_registry(cct) {} virtual ~AuthServer() {} /// Get authentication methods and connection modes for the given peer type virtual void get_supported_auth_methods( int peer_type, std::vector<uint32_t> *methods, std::vector<uint32_t> *modes = nullptr) { auth_registry.get_supported_methods(peer_type, methods, modes); } /// Get support connection modes for the given peer type and auth method virtual uint32_t pick_con_mode( int peer_type, uint32_t auth_method, const std::vector<uint32_t>& preferred_modes) { return auth_registry.pick_mode(peer_type, auth_method, preferred_modes); } /// return an AuthAuthorizeHandler for the given peer type and auth method AuthAuthorizeHandler *get_auth_authorize_handler( int peer_type, int auth_method) { return auth_registry.get_handler(peer_type, auth_method); } /// Handle an authentication request on an incoming connection virtual int handle_auth_request( Connection *con, AuthConnectionMeta *auth_meta, bool more, ///< true if this is not the first part of the handshake uint32_t auth_method, const ceph::buffer::list& bl, ceph::buffer::list *reply) = 0; };
1,509
28.038462
81
h
null
ceph-main/src/auth/AuthServiceHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHSERVICEHANDLER_H #define CEPH_AUTHSERVICEHANDLER_H #include <stddef.h> // for NULL #include <stdint.h> // for uint64_t #include "common/entity_name.h" // for EntityName #include "include/common_fwd.h" #include "include/buffer_fwd.h" // for ceph::buffer::list class KeyServer; class CryptoKey; struct AuthCapsInfo; enum class global_id_status_t { NONE, // fresh client (global_id == 0); waiting for CephXAuthenticate NEW_PENDING, // connected client; new enough to correctly reclaim global_id NEW_OK, // connected client; unknown whether it can reclaim global_id correctly NEW_NOT_EXPOSED, // reconnecting client (global_id != 0); waiting for CephXAuthenticate RECLAIM_PENDING, // reconnected client; correctly reclaimed global_id RECLAIM_OK, // reconnected client; did not properly prove prior global_id ownership RECLAIM_INSECURE }; std::ostream& operator<<(std::ostream& os, global_id_status_t global_id_status); struct AuthServiceHandler { protected: CephContext *cct; EntityName entity_name; uint64_t global_id = 0; global_id_status_t global_id_status = global_id_status_t::NONE; public: explicit AuthServiceHandler(CephContext *cct_) : cct(cct_) {} virtual ~AuthServiceHandler() { } int start_session(const EntityName& entity_name, uint64_t global_id, bool is_new_global_id, ceph::buffer::list *result, AuthCapsInfo *caps); virtual int handle_request(ceph::buffer::list::const_iterator& indata, size_t connection_secret_required_length, ceph::buffer::list *result, AuthCapsInfo *caps, CryptoKey *session_key, std::string *connection_secret) = 0; const EntityName& get_entity_name() { return entity_name; } uint64_t get_global_id() { return global_id; } global_id_status_t get_global_id_status() { return global_id_status; } private: virtual int do_start_session(bool is_new_global_id, ceph::buffer::list *result, AuthCapsInfo *caps) = 0; }; extern AuthServiceHandler *get_auth_service_handler(int type, CephContext *cct, KeyServer *ks); #endif
2,573
29.642857
95
h
null
ceph-main/src/auth/AuthSessionHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHSESSIONHANDLER_H #define CEPH_AUTHSESSIONHANDLER_H #include "include/common_fwd.h" #include "include/types.h" #include "Auth.h" #define SESSION_SIGNATURE_FAILURE -1 // Defines the security applied to ongoing messages in a session, once the session is established. PLR class Message; struct AuthSessionHandler { virtual ~AuthSessionHandler() = default; virtual int sign_message(Message *message) = 0; virtual int check_message_signature(Message *message) = 0; }; struct DummyAuthSessionHandler : AuthSessionHandler { int sign_message(Message*) final { return 0; } int check_message_signature(Message*) final { return 0; } }; struct DecryptionError : public std::exception {}; extern AuthSessionHandler *get_auth_session_handler( CephContext *cct, int protocol, const CryptoKey& key, uint64_t features); #endif
1,290
23.826923
102
h
null
ceph-main/src/auth/Crypto.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTH_CRYPTO_H #define CEPH_AUTH_CRYPTO_H #include "include/common_fwd.h" #include "include/types.h" #include "include/utime.h" #include "include/buffer.h" #include <string> class CryptoKeyContext; namespace ceph { class Formatter; } /* * Random byte stream generator suitable for cryptographic use */ class CryptoRandom { public: CryptoRandom(); // throws on failure ~CryptoRandom(); /// copy up to 256 random bytes into the given buffer. throws on failure void get_bytes(char *buf, int len); private: static int open_urandom(); const int fd; }; /* * some per-key context that is specific to a particular crypto backend */ class CryptoKeyHandler { public: // The maximum size of a single block for all descendants of the class. static constexpr std::size_t MAX_BLOCK_SIZE {16}; // A descendant pick-ups one from these and passes it to the ctor template. typedef std::integral_constant<std::size_t, 0> BLOCK_SIZE_0B; typedef std::integral_constant<std::size_t, 16> BLOCK_SIZE_16B; struct in_slice_t { const std::size_t length; const unsigned char* const buf; }; struct out_slice_t { const std::size_t max_length; unsigned char* const buf; }; ceph::bufferptr secret; template <class BlockSizeT> CryptoKeyHandler(BlockSizeT) { static_assert(BlockSizeT::value <= MAX_BLOCK_SIZE); } virtual ~CryptoKeyHandler() {} virtual int encrypt(const ceph::buffer::list& in, ceph::buffer::list& out, std::string *error) const = 0; virtual int decrypt(const ceph::buffer::list& in, ceph::buffer::list& out, std::string *error) const = 0; // TODO: provide nullptr in the out::buf to get/estimate size requirements? // Or maybe dedicated methods? virtual std::size_t encrypt(const in_slice_t& in, const out_slice_t& out) const; virtual std::size_t decrypt(const in_slice_t& in, const out_slice_t& out) const; sha256_digest_t hmac_sha256(const ceph::bufferlist& in) const; }; /* * match encoding of struct ceph_secret */ class CryptoKey { protected: __u16 type; utime_t created; ceph::buffer::ptr secret; // must set this via set_secret()! // cache a pointer to the implementation-specific key handler, so we // don't have to create it for every crypto operation. mutable std::shared_ptr<CryptoKeyHandler> ckh; int _set_secret(int type, const ceph::buffer::ptr& s); public: CryptoKey() : type(0) { } CryptoKey(int t, utime_t c, ceph::buffer::ptr& s) : created(c) { _set_secret(t, s); } ~CryptoKey() { } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& bl); void clear() { *this = CryptoKey(); } int get_type() const { return type; } utime_t get_created() const { return created; } void print(std::ostream& out) const; int set_secret(int type, const ceph::buffer::ptr& s, utime_t created); const ceph::buffer::ptr& get_secret() { return secret; } const ceph::buffer::ptr& get_secret() const { return secret; } bool empty() const { return ckh.get() == nullptr; } void encode_base64(std::string& s) const { ceph::buffer::list bl; encode(bl); ceph::bufferlist e; bl.encode_base64(e); e.append('\0'); s = e.c_str(); } std::string encode_base64() const { std::string s; encode_base64(s); return s; } void decode_base64(const std::string& s) { ceph::buffer::list e; e.append(s); ceph::buffer::list bl; bl.decode_base64(e); auto p = std::cbegin(bl); decode(p); } void encode_formatted(std::string label, ceph::Formatter *f, ceph::buffer::list &bl); void encode_plaintext(ceph::buffer::list &bl); // -- int create(CephContext *cct, int type); int encrypt(CephContext *cct, const ceph::buffer::list& in, ceph::buffer::list& out, std::string *error) const { ceph_assert(ckh); // Bad key? return ckh->encrypt(in, out, error); } int decrypt(CephContext *cct, const ceph::buffer::list& in, ceph::buffer::list& out, std::string *error) const { ceph_assert(ckh); // Bad key? return ckh->decrypt(in, out, error); } using in_slice_t = CryptoKeyHandler::in_slice_t; using out_slice_t = CryptoKeyHandler::out_slice_t; std::size_t encrypt(CephContext*, const in_slice_t& in, const out_slice_t& out) { ceph_assert(ckh); return ckh->encrypt(in, out); } std::size_t decrypt(CephContext*, const in_slice_t& in, const out_slice_t& out) { ceph_assert(ckh); return ckh->encrypt(in, out); } sha256_digest_t hmac_sha256(CephContext*, const ceph::buffer::list& in) { ceph_assert(ckh); return ckh->hmac_sha256(in); } static constexpr std::size_t get_max_outbuf_size(std::size_t want_size) { return want_size + CryptoKeyHandler::MAX_BLOCK_SIZE; } void to_str(std::string& s) const; }; WRITE_CLASS_ENCODER(CryptoKey) inline std::ostream& operator<<(std::ostream& out, const CryptoKey& k) { k.print(out); return out; } /* * Driver for a particular algorithm * * To use these functions, you need to call ceph::crypto::init(), see * common/ceph_crypto.h. common_init_finish does this for you. */ class CryptoHandler { public: virtual ~CryptoHandler() {} virtual int get_type() const = 0; virtual int create(CryptoRandom *random, ceph::buffer::ptr& secret) = 0; virtual int validate_secret(const ceph::buffer::ptr& secret) = 0; virtual CryptoKeyHandler *get_key_handler(const ceph::buffer::ptr& secret, std::string& error) = 0; static CryptoHandler *create(int type); }; #endif
6,046
25.995536
77
h
null
ceph-main/src/auth/DummyAuth.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "AuthClient.h" #include "AuthServer.h" class DummyAuthClientServer : public AuthClient, public AuthServer { public: DummyAuthClientServer(CephContext *cct) : AuthServer(cct) {} // client int get_auth_request( Connection *con, AuthConnectionMeta *auth_meta, uint32_t *method, std::vector<uint32_t> *preferred_modes, bufferlist *out) override { *method = CEPH_AUTH_NONE; *preferred_modes = { CEPH_CON_MODE_CRC }; return 0; } int handle_auth_reply_more( Connection *con, AuthConnectionMeta *auth_meta, const bufferlist& bl, bufferlist *reply) override { ceph_abort(); } int handle_auth_done( Connection *con, AuthConnectionMeta *auth_meta, uint64_t global_id, uint32_t con_mode, const bufferlist& bl, CryptoKey *session_key, std::string *connection_secret) { return 0; } int handle_auth_bad_method( Connection *con, AuthConnectionMeta *auth_meta, uint32_t old_auth_method, int result, const std::vector<uint32_t>& allowed_methods, const std::vector<uint32_t>& allowed_modes) override { ceph_abort(); } // server int handle_auth_request( Connection *con, AuthConnectionMeta *auth_meta, bool more, uint32_t auth_method, const bufferlist& bl, bufferlist *reply) override { return 1; } };
1,471
22
70
h
null
ceph-main/src/auth/KeyRing.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_KEYRING_H #define CEPH_KEYRING_H #include "auth/Auth.h" #include "include/common_fwd.h" class KeyRing : public KeyStore { std::map<EntityName, EntityAuth> keys; int set_modifier(const char *type, const char *val, EntityName& name, std::map<std::string, ceph::buffer::list>& caps); public: void decode_plaintext(ceph::buffer::list::const_iterator& bl); /* Create a KeyRing from a Ceph context. * We will use the configuration stored inside the context. */ int from_ceph_context(CephContext *cct); std::map<EntityName, EntityAuth>& get_keys() { return keys; } // yuck int load(CephContext *cct, const std::string &filename); void print(std::ostream& out); // accessors bool exists(const EntityName& name) const { auto p = keys.find(name); return p != keys.end(); } bool get_auth(const EntityName& name, EntityAuth &a) const { std::map<EntityName, EntityAuth>::const_iterator k = keys.find(name); if (k == keys.end()) return false; a = k->second; return true; } bool get_secret(const EntityName& name, CryptoKey& secret) const override { std::map<EntityName, EntityAuth>::const_iterator k = keys.find(name); if (k == keys.end()) return false; secret = k->second.key; return true; } bool get_service_secret(uint32_t service_id, uint64_t secret_id, CryptoKey& secret) const override { return false; } bool get_caps(const EntityName& name, const std::string& type, AuthCapsInfo& caps) const { std::map<EntityName, EntityAuth>::const_iterator k = keys.find(name); if (k == keys.end()) return false; std::map<std::string,ceph::buffer::list>::const_iterator i = k->second.caps.find(type); if (i != k->second.caps.end()) { caps.caps = i->second; } return true; } size_t size() const { return keys.size(); } // modifiers void add(const EntityName& name, const EntityAuth &a) { keys[name] = a; } void add(const EntityName& name, const CryptoKey &k) { EntityAuth a; a.key = k; keys[name] = a; } void add(const EntityName& name, const CryptoKey &k, const CryptoKey &pk) { EntityAuth a; a.key = k; a.pending_key = pk; keys[name] = a; } void remove(const EntityName& name) { keys.erase(name); } void set_caps(const EntityName& name, std::map<std::string, ceph::buffer::list>& caps) { keys[name].caps = caps; } void set_key(EntityName& ename, CryptoKey& key) { keys[ename].key = key; } void import(CephContext *cct, KeyRing& other); // decode as plaintext void decode(ceph::buffer::list::const_iterator& bl); void encode_plaintext(ceph::buffer::list& bl); void encode_formatted(std::string label, ceph::Formatter *f, ceph::buffer::list& bl); }; // don't use WRITE_CLASS_ENCODER macro because we don't have an encode // macro. don't juse encode_plaintext in that case because it is not // wrappable; it assumes it gets the entire ceph::buffer::list. static inline void decode(KeyRing& kr, ceph::buffer::list::const_iterator& p) { kr.decode(p); } #endif
3,520
29.617391
121
h
null
ceph-main/src/auth/RotatingKeyRing.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_ROTATINGKEYRING_H #define CEPH_ROTATINGKEYRING_H #include "common/ceph_mutex.h" #include "auth/Auth.h" #include "include/common_fwd.h" /* * mediate access to a service's keyring and rotating secrets */ class KeyRing; class RotatingKeyRing : public KeyStore { CephContext *cct; uint32_t service_id; RotatingSecrets secrets; KeyRing *keyring; mutable ceph::mutex lock; public: RotatingKeyRing(CephContext *cct_, uint32_t s, KeyRing *kr) : cct(cct_), service_id(s), keyring(kr), lock{ceph::make_mutex("RotatingKeyRing::lock")} {} bool need_new_secrets() const; bool need_new_secrets(utime_t now) const; void set_secrets(RotatingSecrets&& s); void dump_rotating() const; bool get_secret(const EntityName& name, CryptoKey& secret) const override; bool get_service_secret(uint32_t service_id, uint64_t secret_id, CryptoKey& secret) const override; KeyRing *get_keyring(); }; #endif
1,376
24.5
76
h
null
ceph-main/src/auth/cephx/CephxAuthorizeHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_CEPHXAUTHORIZEHANDLER_H #define CEPH_CEPHXAUTHORIZEHANDLER_H #include "auth/AuthAuthorizeHandler.h" #include "include/common_fwd.h" struct CephxAuthorizeHandler : public AuthAuthorizeHandler { bool verify_authorizer( CephContext *cct, const KeyStore& keys, const ceph::buffer::list& authorizer_data, size_t connection_secret_required_len, ceph::buffer::list *authorizer_reply, EntityName *entity_name, uint64_t *global_id, AuthCapsInfo *caps_info, CryptoKey *session_key, std::string *connection_secret, std::unique_ptr<AuthAuthorizerChallenge> *challenge) override; int authorizer_session_crypto() override; }; #endif
1,114
26.875
71
h
null
ceph-main/src/auth/cephx/CephxClientHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_CEPHXCLIENTHANDLER_H #define CEPH_CEPHXCLIENTHANDLER_H #include "auth/AuthClientHandler.h" #include "CephxProtocol.h" #include "auth/RotatingKeyRing.h" #include "include/common_fwd.h" class KeyRing; class CephxClientHandler : public AuthClientHandler { bool starting; /* envelope protocol parameters */ uint64_t server_challenge; CephXTicketManager tickets; CephXTicketHandler* ticket_handler; RotatingKeyRing* rotating_secrets; KeyRing *keyring; public: CephxClientHandler(CephContext *cct_, RotatingKeyRing *rsecrets) : AuthClientHandler(cct_), starting(false), server_challenge(0), tickets(cct_), ticket_handler(NULL), rotating_secrets(rsecrets), keyring(rsecrets->get_keyring()) { reset(); } CephxClientHandler* clone() const override { return new CephxClientHandler(*this); } void reset() override; void prepare_build_request() override; int build_request(ceph::buffer::list& bl) const override; int handle_response(int ret, ceph::buffer::list::const_iterator& iter, CryptoKey *session_key, std::string *connection_secret) override; bool build_rotating_request(ceph::buffer::list& bl) const override; int get_protocol() const override { return CEPH_AUTH_CEPHX; } AuthAuthorizer *build_authorizer(uint32_t service_id) const override; bool need_tickets() override; void set_global_id(uint64_t id) override { global_id = id; tickets.global_id = id; } private: void validate_tickets() override; bool _need_tickets() const; }; #endif
2,017
24.544304
72
h
null
ceph-main/src/auth/cephx/CephxKeyServer.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_KEYSSERVER_H #define CEPH_KEYSSERVER_H #include "auth/KeyRing.h" #include "CephxProtocol.h" #include "common/ceph_mutex.h" #include "include/common_fwd.h" struct KeyServerData { version_t version; /* for each entity */ std::map<EntityName, EntityAuth> secrets; KeyRing *extra_secrets; /* for each service type */ version_t rotating_ver; std::map<uint32_t, RotatingSecrets> rotating_secrets; explicit KeyServerData(KeyRing *extra) : version(0), extra_secrets(extra), rotating_ver(0) {} void encode(ceph::buffer::list& bl) const { __u8 struct_v = 1; using ceph::encode; encode(struct_v, bl); encode(version, bl); encode(rotating_ver, bl); encode(secrets, bl); encode(rotating_secrets, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(version, bl); decode(rotating_ver, bl); decode(secrets, bl); decode(rotating_secrets, bl); } void encode_rotating(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(rotating_ver, bl); encode(rotating_secrets, bl); } void decode_rotating(ceph::buffer::list& rotating_bl) { using ceph::decode; auto iter = rotating_bl.cbegin(); __u8 struct_v; decode(struct_v, iter); decode(rotating_ver, iter); decode(rotating_secrets, iter); } bool contains(const EntityName& name) const { return (secrets.find(name) != secrets.end()); } void clear_secrets() { version = 0; secrets.clear(); rotating_ver = 0; rotating_secrets.clear(); } void add_auth(const EntityName& name, EntityAuth& auth) { secrets[name] = auth; } void remove_secret(const EntityName& name) { auto iter = secrets.find(name); if (iter == secrets.end()) return; secrets.erase(iter); } bool get_service_secret(CephContext *cct, uint32_t service_id, CryptoKey& secret, uint64_t& secret_id, double& ttl) const; bool get_service_secret(CephContext *cct, uint32_t service_id, uint64_t secret_id, CryptoKey& secret) const; bool get_auth(const EntityName& name, EntityAuth& auth) const; bool get_secret(const EntityName& name, CryptoKey& secret) const; bool get_caps(CephContext *cct, const EntityName& name, const std::string& type, AuthCapsInfo& caps) const; std::map<EntityName, EntityAuth>::iterator secrets_begin() { return secrets.begin(); } std::map<EntityName, EntityAuth>::const_iterator secrets_begin() const { return secrets.begin(); } std::map<EntityName, EntityAuth>::iterator secrets_end() { return secrets.end(); } std::map<EntityName, EntityAuth>::const_iterator secrets_end() const { return secrets.end(); } std::map<EntityName, EntityAuth>::iterator find_name(const EntityName& name) { return secrets.find(name); } std::map<EntityName, EntityAuth>::const_iterator find_name(const EntityName& name) const { return secrets.find(name); } // -- incremental updates -- typedef enum { AUTH_INC_NOP, AUTH_INC_ADD, AUTH_INC_DEL, AUTH_INC_SET_ROTATING, } IncrementalOp; struct Incremental { IncrementalOp op; ceph::buffer::list rotating_bl; // if SET_ROTATING. otherwise, EntityName name; EntityAuth auth; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); __u32 _op = (__u32)op; encode(_op, bl); if (op == AUTH_INC_SET_ROTATING) { encode(rotating_bl, bl); } else { encode(name, bl); encode(auth, bl); } } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); __u32 _op; decode(_op, bl); op = (IncrementalOp)_op; ceph_assert(op >= AUTH_INC_NOP && op <= AUTH_INC_SET_ROTATING); if (op == AUTH_INC_SET_ROTATING) { decode(rotating_bl, bl); } else { decode(name, bl); decode(auth, bl); } } }; void apply_incremental(Incremental& inc) { switch (inc.op) { case AUTH_INC_ADD: add_auth(inc.name, inc.auth); break; case AUTH_INC_DEL: remove_secret(inc.name); break; case AUTH_INC_SET_ROTATING: decode_rotating(inc.rotating_bl); break; case AUTH_INC_NOP: break; default: ceph_abort(); } } }; WRITE_CLASS_ENCODER(KeyServerData) WRITE_CLASS_ENCODER(KeyServerData::Incremental) class KeyServer : public KeyStore { CephContext *cct; KeyServerData data; std::map<EntityName, CryptoKey> used_pending_keys; mutable ceph::mutex lock; int _rotate_secret(uint32_t service_id, KeyServerData &pending_data); void _dump_rotating_secrets(); int _build_session_auth_info(uint32_t service_id, const AuthTicket& parent_ticket, CephXSessionAuthInfo& info, double ttl); bool _get_service_caps(const EntityName& name, uint32_t service_id, AuthCapsInfo& caps) const; public: KeyServer(CephContext *cct_, KeyRing *extra_secrets); bool generate_secret(CryptoKey& secret); bool get_secret(const EntityName& name, CryptoKey& secret) const override; bool get_auth(const EntityName& name, EntityAuth& auth) const; bool get_caps(const EntityName& name, const std::string& type, AuthCapsInfo& caps) const; bool get_active_rotating_secret(const EntityName& name, CryptoKey& secret) const; void note_used_pending_key(const EntityName& name, const CryptoKey& key); void clear_used_pending_keys(); std::map<EntityName,CryptoKey> get_used_pending_keys(); int start_server(); void rotate_timeout(double timeout); void dump(); int build_session_auth_info(uint32_t service_id, const AuthTicket& parent_ticket, CephXSessionAuthInfo& info); int build_session_auth_info(uint32_t service_id, const AuthTicket& parent_ticket, const CryptoKey& service_secret, uint64_t secret_id, CephXSessionAuthInfo& info); /* get current secret for specific service type */ bool get_service_secret(uint32_t service_id, CryptoKey& secret, uint64_t& secret_id, double& ttl) const; bool get_service_secret(uint32_t service_id, uint64_t secret_id, CryptoKey& secret) const override; bool generate_secret(EntityName& name, CryptoKey& secret); void encode(ceph::buffer::list& bl) const { using ceph::encode; encode(data, bl); } void decode(ceph::buffer::list::const_iterator& bl) { std::scoped_lock l{lock}; using ceph::decode; decode(data, bl); } bool contains(const EntityName& name) const; int encode_secrets(ceph::Formatter *f, std::stringstream *ds) const; void encode_formatted(std::string label, ceph::Formatter *f, ceph::buffer::list &bl); void encode_plaintext(ceph::buffer::list &bl); int list_secrets(std::stringstream& ds) const { return encode_secrets(NULL, &ds); } version_t get_ver() const { std::scoped_lock l{lock}; return data.version; } void clear_secrets() { std::scoped_lock l{lock}; data.clear_secrets(); } void apply_data_incremental(KeyServerData::Incremental& inc) { std::scoped_lock l{lock}; data.apply_incremental(inc); } void set_ver(version_t ver) { std::scoped_lock l{lock}; data.version = ver; } void add_auth(const EntityName& name, EntityAuth& auth) { std::scoped_lock l{lock}; data.add_auth(name, auth); } void remove_secret(const EntityName& name) { std::scoped_lock l{lock}; data.remove_secret(name); } bool has_secrets() { auto b = data.secrets_begin(); return (b != data.secrets_end()); } int get_num_secrets() { std::scoped_lock l{lock}; return data.secrets.size(); } void clone_to(KeyServerData& dst) const { std::scoped_lock l{lock}; dst = data; } void export_keyring(KeyRing& keyring) { std::scoped_lock l{lock}; for (auto p = data.secrets.begin(); p != data.secrets.end(); ++p) { keyring.add(p->first, p->second); } } bool prepare_rotating_update(ceph::buffer::list& rotating_bl); bool get_rotating_encrypted(const EntityName& name, ceph::buffer::list& enc_bl) const; ceph::mutex& get_lock() const { return lock; } bool get_service_caps(const EntityName& name, uint32_t service_id, AuthCapsInfo& caps) const; std::map<EntityName, EntityAuth>::iterator secrets_begin() { return data.secrets_begin(); } std::map<EntityName, EntityAuth>::iterator secrets_end() { return data.secrets_end(); } }; WRITE_CLASS_ENCODER(KeyServer) #endif
9,074
27.009259
91
h
null
ceph-main/src/auth/cephx/CephxProtocol.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_CEPHXPROTOCOL_H #define CEPH_CEPHXPROTOCOL_H /* Ceph X protocol See doc/dev/cephx.rst */ /* authenticate requests */ #define CEPHX_GET_AUTH_SESSION_KEY 0x0100 #define CEPHX_GET_PRINCIPAL_SESSION_KEY 0x0200 #define CEPHX_GET_ROTATING_KEY 0x0400 #define CEPHX_REQUEST_TYPE_MASK 0x0F00 #define CEPHX_CRYPT_ERR 1 #include "auth/Auth.h" #include <errno.h> #include <sstream> #include "include/common_fwd.h" /* * Authentication */ // initial server -> client challenge struct CephXServerChallenge { uint64_t server_challenge; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(server_challenge, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(server_challenge, bl); } }; WRITE_CLASS_ENCODER(CephXServerChallenge) // request/reply headers, for subsequent exchanges. struct CephXRequestHeader { __u16 request_type; void encode(ceph::buffer::list& bl) const { using ceph::encode; encode(request_type, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; decode(request_type, bl); } }; WRITE_CLASS_ENCODER(CephXRequestHeader) struct CephXResponseHeader { uint16_t request_type; int32_t status; void encode(ceph::buffer::list& bl) const { using ceph::encode; encode(request_type, bl); encode(status, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; decode(request_type, bl); decode(status, bl); } }; WRITE_CLASS_ENCODER(CephXResponseHeader) struct CephXTicketBlob { uint64_t secret_id; ceph::buffer::list blob; CephXTicketBlob() : secret_id(0) {} void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(secret_id, bl); encode(blob, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(secret_id, bl); decode(blob, bl); } }; WRITE_CLASS_ENCODER(CephXTicketBlob) // client -> server response to challenge struct CephXAuthenticate { uint64_t client_challenge; uint64_t key; CephXTicketBlob old_ticket; uint32_t other_keys = 0; // replaces CephXServiceTicketRequest bool old_ticket_may_be_omitted; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 3; encode(struct_v, bl); encode(client_challenge, bl); encode(key, bl); encode(old_ticket, bl); encode(other_keys, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(client_challenge, bl); decode(key, bl); decode(old_ticket, bl); if (struct_v >= 2) { decode(other_keys, bl); } // v2 and v3 encodings are the same, but: // - some clients that send v1 or v2 don't populate old_ticket // on reconnects (but do on renewals) // - any client that sends v3 or later is expected to populate // old_ticket both on reconnects and renewals old_ticket_may_be_omitted = struct_v < 3; } }; WRITE_CLASS_ENCODER(CephXAuthenticate) struct CephXChallengeBlob { uint64_t server_challenge, client_challenge; void encode(ceph::buffer::list& bl) const { using ceph::encode; encode(server_challenge, bl); encode(client_challenge, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; decode(server_challenge, bl); decode(client_challenge, bl); } }; WRITE_CLASS_ENCODER(CephXChallengeBlob) void cephx_calc_client_server_challenge(CephContext *cct, CryptoKey& secret, uint64_t server_challenge, uint64_t client_challenge, uint64_t *key, std::string &error); /* * getting service tickets */ struct CephXSessionAuthInfo { uint32_t service_id; uint64_t secret_id; AuthTicket ticket; CryptoKey session_key; CryptoKey service_secret; utime_t validity; }; extern bool cephx_build_service_ticket_blob(CephContext *cct, CephXSessionAuthInfo& ticket_info, CephXTicketBlob& blob); extern void cephx_build_service_ticket_request(CephContext *cct, uint32_t keys, ceph::buffer::list& request); extern bool cephx_build_service_ticket_reply(CephContext *cct, CryptoKey& principal_secret, std::vector<CephXSessionAuthInfo> ticket_info, bool should_encrypt_ticket, CryptoKey& ticket_enc_key, ceph::buffer::list& reply); struct CephXServiceTicketRequest { uint32_t keys; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(keys, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(keys, bl); } }; WRITE_CLASS_ENCODER(CephXServiceTicketRequest) /* * Authorize */ struct CephXAuthorizeReply { uint64_t nonce_plus_one; std::string connection_secret; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; if (connection_secret.size()) { struct_v = 2; } encode(struct_v, bl); encode(nonce_plus_one, bl); if (struct_v >= 2) { struct_v = 2; encode(connection_secret, bl); } } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(nonce_plus_one, bl); if (struct_v >= 2) { decode(connection_secret, bl); } } }; WRITE_CLASS_ENCODER(CephXAuthorizeReply) struct CephXAuthorizer : public AuthAuthorizer { private: CephContext *cct; public: uint64_t nonce; ceph::buffer::list base_bl; explicit CephXAuthorizer(CephContext *cct_) : AuthAuthorizer(CEPH_AUTH_CEPHX), cct(cct_), nonce(0) {} bool build_authorizer(); bool verify_reply(ceph::buffer::list::const_iterator& reply, std::string *connection_secret) override; bool add_challenge(CephContext *cct, const ceph::buffer::list& challenge) override; }; /* * TicketHandler */ struct CephXTicketHandler { uint32_t service_id; CryptoKey session_key; CephXTicketBlob ticket; // opaque to us utime_t renew_after, expires; bool have_key_flag; CephXTicketHandler(CephContext *cct_, uint32_t service_id_) : service_id(service_id_), have_key_flag(false), cct(cct_) { } // to build our ServiceTicket bool verify_service_ticket_reply(CryptoKey& principal_secret, ceph::buffer::list::const_iterator& indata); // to access the service CephXAuthorizer *build_authorizer(uint64_t global_id) const; bool have_key(); bool need_key() const; void invalidate_ticket() { have_key_flag = false; } private: CephContext *cct; }; struct CephXTicketManager { typedef std::map<uint32_t, CephXTicketHandler> tickets_map_t; tickets_map_t tickets_map; uint64_t global_id; explicit CephXTicketManager(CephContext *cct_) : global_id(0), cct(cct_) {} bool verify_service_ticket_reply(CryptoKey& principal_secret, ceph::buffer::list::const_iterator& indata); CephXTicketHandler& get_handler(uint32_t type) { tickets_map_t::iterator i = tickets_map.find(type); if (i != tickets_map.end()) return i->second; CephXTicketHandler newTicketHandler(cct, type); std::pair < tickets_map_t::iterator, bool > res = tickets_map.insert(std::make_pair(type, newTicketHandler)); ceph_assert(res.second); return res.first->second; } CephXAuthorizer *build_authorizer(uint32_t service_id) const; bool have_key(uint32_t service_id); bool need_key(uint32_t service_id) const; void set_have_need_key(uint32_t service_id, uint32_t& have, uint32_t& need); void validate_tickets(uint32_t mask, uint32_t& have, uint32_t& need); void invalidate_ticket(uint32_t service_id); private: CephContext *cct; }; /* A */ struct CephXServiceTicket { CryptoKey session_key; utime_t validity; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(session_key, bl); encode(validity, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(session_key, bl); decode(validity, bl); } }; WRITE_CLASS_ENCODER(CephXServiceTicket) /* B */ struct CephXServiceTicketInfo { AuthTicket ticket; CryptoKey session_key; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(ticket, bl); encode(session_key, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(ticket, bl); decode(session_key, bl); } }; WRITE_CLASS_ENCODER(CephXServiceTicketInfo) struct CephXAuthorizeChallenge : public AuthAuthorizerChallenge { uint64_t server_challenge; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 1; encode(struct_v, bl); encode(server_challenge, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(server_challenge, bl); } }; WRITE_CLASS_ENCODER(CephXAuthorizeChallenge) struct CephXAuthorize { uint64_t nonce; bool have_challenge = false; uint64_t server_challenge_plus_one = 0; void encode(ceph::buffer::list& bl) const { using ceph::encode; __u8 struct_v = 2; encode(struct_v, bl); encode(nonce, bl); encode(have_challenge, bl); encode(server_challenge_plus_one, bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 struct_v; decode(struct_v, bl); decode(nonce, bl); if (struct_v >= 2) { decode(have_challenge, bl); decode(server_challenge_plus_one, bl); } } }; WRITE_CLASS_ENCODER(CephXAuthorize) /* * Decode an extract ticket */ bool cephx_decode_ticket(CephContext *cct, KeyStore *keys, uint32_t service_id, const CephXTicketBlob& ticket_blob, CephXServiceTicketInfo& ticket_info); /* * Verify authorizer and generate reply authorizer */ extern bool cephx_verify_authorizer( CephContext *cct, const KeyStore& keys, ceph::buffer::list::const_iterator& indata, size_t connection_secret_required_len, CephXServiceTicketInfo& ticket_info, std::unique_ptr<AuthAuthorizerChallenge> *challenge, std::string *connection_secret, ceph::buffer::list *reply_bl); /* * encode+encrypt macros */ static constexpr uint64_t AUTH_ENC_MAGIC = 0xff009cad8826aa55ull; template <typename T> void decode_decrypt_enc_bl(CephContext *cct, T& t, CryptoKey key, const ceph::buffer::list& bl_enc, std::string &error) { uint64_t magic; ceph::buffer::list bl; if (key.decrypt(cct, bl_enc, bl, &error) < 0) return; auto iter2 = bl.cbegin(); __u8 struct_v; using ceph::decode; decode(struct_v, iter2); decode(magic, iter2); if (magic != AUTH_ENC_MAGIC) { std::ostringstream oss; oss << "bad magic in decode_decrypt, " << magic << " != " << AUTH_ENC_MAGIC; error = oss.str(); return; } decode(t, iter2); } template <typename T> void encode_encrypt_enc_bl(CephContext *cct, const T& t, const CryptoKey& key, ceph::buffer::list& out, std::string &error) { ceph::buffer::list bl; __u8 struct_v = 1; using ceph::encode; encode(struct_v, bl); uint64_t magic = AUTH_ENC_MAGIC; encode(magic, bl); encode(t, bl); key.encrypt(cct, bl, out, &error); } template <typename T> int decode_decrypt(CephContext *cct, T& t, const CryptoKey& key, ceph::buffer::list::const_iterator& iter, std::string &error) { ceph::buffer::list bl_enc; using ceph::decode; try { decode(bl_enc, iter); decode_decrypt_enc_bl(cct, t, key, bl_enc, error); } catch (ceph::buffer::error &e) { error = "error decoding block for decryption"; } if (!error.empty()) return CEPHX_CRYPT_ERR; return 0; } template <typename T> int encode_encrypt(CephContext *cct, const T& t, const CryptoKey& key, ceph::buffer::list& out, std::string &error) { using ceph::encode; ceph::buffer::list bl_enc; encode_encrypt_enc_bl(cct, t, key, bl_enc, error); if (!error.empty()){ return CEPHX_CRYPT_ERR; } encode(bl_enc, out); return 0; } #endif
13,084
23.782197
85
h
null
ceph-main/src/auth/cephx/CephxServiceHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_CEPHXSERVICEHANDLER_H #define CEPH_CEPHXSERVICEHANDLER_H #include "auth/AuthServiceHandler.h" #include "auth/Auth.h" class KeyServer; struct CephXAuthenticate; struct CephXServiceTicketInfo; class CephxServiceHandler : public AuthServiceHandler { KeyServer *key_server; uint64_t server_challenge; public: CephxServiceHandler(CephContext *cct_, KeyServer *ks) : AuthServiceHandler(cct_), key_server(ks), server_challenge(0) {} ~CephxServiceHandler() override {} int handle_request( ceph::buffer::list::const_iterator& indata, size_t connection_secret_required_length, ceph::buffer::list *result_bl, AuthCapsInfo *caps, CryptoKey *session_key, std::string *connection_secret) override; private: int do_start_session(bool is_new_global_id, ceph::buffer::list *result_bl, AuthCapsInfo *caps) override; int verify_old_ticket(const CephXAuthenticate& req, CephXServiceTicketInfo& old_ticket_info, bool& should_enc_ticket); void build_cephx_response_header(int request_type, int status, ceph::buffer::list& bl); }; #endif
1,544
27.090909
71
h
null
ceph-main/src/auth/cephx/CephxSessionHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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 "auth/AuthSessionHandler.h" #include "auth/Auth.h" #include "include/common_fwd.h" class Message; class CephxSessionHandler : public AuthSessionHandler { CephContext *cct; int protocol; CryptoKey key; // per mon authentication uint64_t features; int _calc_signature(Message *m, uint64_t *psig); public: CephxSessionHandler(CephContext *cct, const CryptoKey& session_key, const uint64_t features) : cct(cct), protocol(CEPH_AUTH_CEPHX), key(session_key), features(features) { } ~CephxSessionHandler() override = default; int sign_message(Message *m) override; int check_message_signature(Message *m) override ; };
1,128
24.088889
70
h
null
ceph-main/src/auth/none/AuthNoneAuthorizeHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHNONEAUTHORIZEHANDLER_H #define CEPH_AUTHNONEAUTHORIZEHANDLER_H #include "auth/AuthAuthorizeHandler.h" #include "include/common_fwd.h" struct AuthNoneAuthorizeHandler : public AuthAuthorizeHandler { bool verify_authorizer( CephContext *cct, const KeyStore& keys, const ceph::buffer::list& authorizer_data, size_t connection_secret_required_len, ceph::buffer::list *authorizer_reply, EntityName *entity_name, uint64_t *global_id, AuthCapsInfo *caps_info, CryptoKey *session_key, std::string *connection_secret, std::unique_ptr<AuthAuthorizerChallenge> *challenge) override; int authorizer_session_crypto() override; }; #endif
1,123
27.1
71
h
null
ceph-main/src/auth/none/AuthNoneClientHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHNONECLIENTHANDLER_H #define CEPH_AUTHNONECLIENTHANDLER_H #include "auth/AuthClientHandler.h" #include "AuthNoneProtocol.h" #include "common/ceph_context.h" #include "common/config.h" class AuthNoneClientHandler : public AuthClientHandler { public: AuthNoneClientHandler(CephContext *cct_) : AuthClientHandler(cct_) {} AuthNoneClientHandler* clone() const override { return new AuthNoneClientHandler(*this); } void reset() override { } void prepare_build_request() override {} int build_request(ceph::buffer::list& bl) const override { return 0; } int handle_response(int ret, ceph::buffer::list::const_iterator& iter, CryptoKey *session_key, std::string *connection_secret) override { return 0; } bool build_rotating_request(ceph::buffer::list& bl) const override { return false; } int get_protocol() const override { return CEPH_AUTH_NONE; } AuthAuthorizer *build_authorizer(uint32_t service_id) const override { AuthNoneAuthorizer *auth = new AuthNoneAuthorizer(); if (auth) { auth->build_authorizer(cct->_conf->name, global_id); } return auth; } bool need_tickets() override { return false; } void set_global_id(uint64_t id) override { global_id = id; } private: void validate_tickets() override {} }; #endif
1,751
27.258065
86
h
null
ceph-main/src/auth/none/AuthNoneProtocol.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHNONEPROTOCOL_H #define CEPH_AUTHNONEPROTOCOL_H #include "auth/Auth.h" #include "include/common_fwd.h" struct AuthNoneAuthorizer : public AuthAuthorizer { AuthNoneAuthorizer() : AuthAuthorizer(CEPH_AUTH_NONE) { } bool build_authorizer(const EntityName &ename, uint64_t global_id) { __u8 struct_v = 1; // see AUTH_MODE_* in Auth.h using ceph::encode; encode(struct_v, bl); encode(ename, bl); encode(global_id, bl); return 0; } bool verify_reply(ceph::buffer::list::const_iterator& reply, std::string *connection_secret) override { return true; } bool add_challenge(CephContext *cct, const ceph::buffer::list& ch) override { return true; } }; #endif
1,142
28.307692
79
h
null
ceph-main/src/auth/none/AuthNoneServiceHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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_AUTHNONESERVICEHANDLER_H #define CEPH_AUTHNONESERVICEHANDLER_H #include "auth/AuthServiceHandler.h" #include "auth/Auth.h" #include "include/common_fwd.h" class AuthNoneServiceHandler : public AuthServiceHandler { public: explicit AuthNoneServiceHandler(CephContext *cct_) : AuthServiceHandler(cct_) {} ~AuthNoneServiceHandler() override {} int handle_request(ceph::buffer::list::const_iterator& indata, size_t connection_secret_required_length, ceph::buffer::list *result_bl, AuthCapsInfo *caps, CryptoKey *session_key, std::string *connection_secret) override { return 0; } private: int do_start_session(bool is_new_global_id, ceph::buffer::list *result_bl, AuthCapsInfo *caps) override { caps->allow_all = true; return 1; } }; #endif
1,268
26
71
h
null
ceph-main/src/auth/none/AuthNoneSessionHandler.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) 2004-2009 Sage Weil <sage@newdream.net> * * 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 "auth/AuthSessionHandler.h" struct AuthNoneSessionHandler : DummyAuthSessionHandler { };
529
25.5
71
h
null
ceph-main/src/blk/BlockDevice.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) 2015 XSky <haomai@xsky.com> * * Author: Haomai Wang <haomaiwang@gmail.com> * * 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_BLK_BLOCKDEVICE_H #define CEPH_BLK_BLOCKDEVICE_H #include <atomic> #include <condition_variable> #include <list> #include <map> #include <mutex> #include <set> #include <string> #include <vector> #include "acconfig.h" #include "common/ceph_mutex.h" #include "include/common_fwd.h" #include "extblkdev/ExtBlkDevInterface.h" #if defined(HAVE_LIBAIO) || defined(HAVE_POSIXAIO) #include "aio/aio.h" #endif #include "include/ceph_assert.h" #include "include/buffer.h" #include "include/interval_set.h" #define SPDK_PREFIX "spdk:" #if defined(__linux__) #if !defined(F_SET_FILE_RW_HINT) #define F_LINUX_SPECIFIC_BASE 1024 #define F_SET_FILE_RW_HINT (F_LINUX_SPECIFIC_BASE + 14) #endif // These values match Linux definition // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/uapi/linux/fcntl.h#n56 #define WRITE_LIFE_NOT_SET 0 // No hint information set #define WRITE_LIFE_NONE 1 // No hints about write life time #define WRITE_LIFE_SHORT 2 // Data written has a short life time #define WRITE_LIFE_MEDIUM 3 // Data written has a medium life time #define WRITE_LIFE_LONG 4 // Data written has a long life time #define WRITE_LIFE_EXTREME 5 // Data written has an extremely long life time #define WRITE_LIFE_MAX 6 #else // On systems don't have WRITE_LIFE_* only use one FD // And all files are created equal #define WRITE_LIFE_NOT_SET 0 // No hint information set #define WRITE_LIFE_NONE 0 // No hints about write life time #define WRITE_LIFE_SHORT 0 // Data written has a short life time #define WRITE_LIFE_MEDIUM 0 // Data written has a medium life time #define WRITE_LIFE_LONG 0 // Data written has a long life time #define WRITE_LIFE_EXTREME 0 // Data written has an extremely long life time #define WRITE_LIFE_MAX 1 #endif enum struct blk_access_mode_t { DIRECT, BUFFERED }; blk_access_mode_t buffermode(bool buffered); std::ostream& operator<<(std::ostream& os, const blk_access_mode_t buffered); /// track in-flight io struct IOContext { enum { FLAG_DONT_CACHE = 1 }; private: ceph::mutex lock = ceph::make_mutex("IOContext::lock"); ceph::condition_variable cond; int r = 0; public: CephContext* cct; void *priv; #ifdef HAVE_SPDK void *nvme_task_first = nullptr; void *nvme_task_last = nullptr; std::atomic_int total_nseg = {0}; #endif #if defined(HAVE_LIBAIO) || defined(HAVE_POSIXAIO) std::list<aio_t> pending_aios; ///< not yet submitted std::list<aio_t> running_aios; ///< submitting or submitted #endif std::atomic_int num_pending = {0}; std::atomic_int num_running = {0}; bool allow_eio; uint32_t flags = 0; // FLAG_* explicit IOContext(CephContext* cct, void *p, bool allow_eio = false) : cct(cct), priv(p), allow_eio(allow_eio) {} // no copying IOContext(const IOContext& other) = delete; IOContext &operator=(const IOContext& other) = delete; bool has_pending_aios() { return num_pending.load(); } void release_running_aios(); void aio_wait(); uint64_t get_num_ios() const; void try_aio_wake() { assert(num_running >= 1); std::lock_guard l(lock); if (num_running.fetch_sub(1) == 1) { // we might have some pending IOs submitted after the check // as there is no lock protection for aio_submit. // Hence we might have false conditional trigger. // aio_wait has to handle that hence do not care here. cond.notify_all(); } } void set_return_value(int _r) { r = _r; } int get_return_value() const { return r; } bool skip_cache() const { return flags & FLAG_DONT_CACHE; } }; class BlockDevice { public: CephContext* cct; typedef void (*aio_callback_t)(void *handle, void *aio); private: ceph::mutex ioc_reap_lock = ceph::make_mutex("BlockDevice::ioc_reap_lock"); std::vector<IOContext*> ioc_reap_queue; std::atomic_int ioc_reap_count = {0}; enum class block_device_t { unknown, #if defined(HAVE_LIBAIO) || defined(HAVE_POSIXAIO) aio, #if defined(HAVE_LIBZBD) hm_smr, #endif #endif #if defined(HAVE_SPDK) spdk, #endif #if defined(HAVE_BLUESTORE_PMEM) pmem, #endif }; static block_device_t detect_device_type(const std::string& path); static block_device_t device_type_from_name(const std::string& blk_dev_name); static BlockDevice *create_with_type(block_device_t device_type, CephContext* cct, const std::string& path, aio_callback_t cb, void *cbpriv, aio_callback_t d_cb, void *d_cbpriv); protected: uint64_t size = 0; uint64_t block_size = 0; uint64_t optimal_io_size = 0; bool support_discard = false; bool rotational = true; bool lock_exclusive = true; // HM-SMR specific properties. In HM-SMR drives the LBA space is divided into // fixed-size zones. Typically, the first few zones are randomly writable; // they form a conventional region of the drive. The remaining zones must be // written sequentially and they must be reset before rewritten. For example, // a 14 TB HGST HSH721414AL drive has 52156 zones each of size is 256 MiB. // The zones 0-523 are randomly writable and they form the conventional region // of the drive. The zones 524-52155 are sequential zones. uint64_t conventional_region_size = 0; uint64_t zone_size = 0; public: aio_callback_t aio_callback; void *aio_callback_priv; BlockDevice(CephContext* cct, aio_callback_t cb, void *cbpriv) : cct(cct), aio_callback(cb), aio_callback_priv(cbpriv) {} virtual ~BlockDevice() = default; static BlockDevice *create( CephContext* cct, const std::string& path, aio_callback_t cb, void *cbpriv, aio_callback_t d_cb, void *d_cbpriv); virtual bool supported_bdev_label() { return true; } virtual bool is_rotational() { return rotational; } // HM-SMR-specific calls virtual bool is_smr() const { return false; } virtual uint64_t get_zone_size() const { ceph_assert(is_smr()); return zone_size; } virtual uint64_t get_conventional_region_size() const { ceph_assert(is_smr()); return conventional_region_size; } virtual void reset_all_zones() { ceph_assert(is_smr()); } virtual void reset_zone(uint64_t zone) { ceph_assert(is_smr()); } virtual std::vector<uint64_t> get_zones() { ceph_assert(is_smr()); return std::vector<uint64_t>(); } virtual void aio_submit(IOContext *ioc) = 0; void set_no_exclusive_lock() { lock_exclusive = false; } uint64_t get_size() const { return size; } uint64_t get_block_size() const { return block_size; } uint64_t get_optimal_io_size() const { return optimal_io_size; } /// hook to provide utilization of thinly-provisioned device virtual int get_ebd_state(ExtBlkDevState &state) const { return -ENOENT; } virtual int collect_metadata(const std::string& prefix, std::map<std::string,std::string> *pm) const = 0; virtual int get_devname(std::string *out) const { return -ENOENT; } virtual int get_devices(std::set<std::string> *ls) const { std::string s; if (get_devname(&s) == 0) { ls->insert(s); } return 0; } virtual int get_numa_node(int *node) const { return -EOPNOTSUPP; } virtual int read( uint64_t off, uint64_t len, ceph::buffer::list *pbl, IOContext *ioc, bool buffered) = 0; virtual int read_random( uint64_t off, uint64_t len, char *buf, bool buffered) = 0; virtual int write( uint64_t off, ceph::buffer::list& bl, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) = 0; virtual int aio_read( uint64_t off, uint64_t len, ceph::buffer::list *pbl, IOContext *ioc) = 0; virtual int aio_write( uint64_t off, ceph::buffer::list& bl, IOContext *ioc, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) = 0; virtual int flush() = 0; virtual bool try_discard(interval_set<uint64_t> &to_release, bool async=true) { return false; } virtual void discard_drain() { return; } // for managing buffered readers/writers virtual int invalidate_cache(uint64_t off, uint64_t len) = 0; virtual int open(const std::string& path) = 0; virtual void close() = 0; struct hugepaged_raw_marker_t {}; protected: bool is_valid_io(uint64_t off, uint64_t len) const; }; #endif //CEPH_BLK_BLOCKDEVICE_H
8,853
28.029508
117
h
null
ceph-main/src/blk/aio/aio.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "acconfig.h" #if defined(HAVE_LIBAIO) #include <libaio.h> #elif defined(HAVE_POSIXAIO) #include <aio.h> #include <sys/event.h> #endif #include <boost/intrusive/list.hpp> #include <boost/container/small_vector.hpp> #include "include/buffer.h" #include "include/types.h" struct aio_t { #if defined(HAVE_LIBAIO) struct iocb iocb{}; // must be first element; see shenanigans in aio_queue_t #elif defined(HAVE_POSIXAIO) // static long aio_listio_max = -1; union { struct aiocb aiocb; struct aiocb *aiocbp; } aio; int n_aiocb; #endif void *priv; int fd; boost::container::small_vector<iovec,4> iov; uint64_t offset, length; long rval; ceph::buffer::list bl; ///< write payload (so that it remains stable for duration) boost::intrusive::list_member_hook<> queue_item; aio_t(void *p, int f) : priv(p), fd(f), offset(0), length(0), rval(-1000) { } void pwritev(uint64_t _offset, uint64_t len) { offset = _offset; length = len; #if defined(HAVE_LIBAIO) io_prep_pwritev(&iocb, fd, &iov[0], iov.size(), offset); #elif defined(HAVE_POSIXAIO) n_aiocb = iov.size(); aio.aiocbp = (struct aiocb*)calloc(iov.size(), sizeof(struct aiocb)); for (int i = 0; i < iov.size(); i++) { aio.aiocbp[i].aio_fildes = fd; aio.aiocbp[i].aio_offset = offset; aio.aiocbp[i].aio_buf = iov[i].iov_base; aio.aiocbp[i].aio_nbytes = iov[i].iov_len; aio.aiocbp[i].aio_lio_opcode = LIO_WRITE; offset += iov[i].iov_len; } #endif } void preadv(uint64_t _offset, uint64_t len) { offset = _offset; length = len; #if defined(HAVE_LIBAIO) io_prep_preadv(&iocb, fd, &iov[0], iov.size(), offset); #elif defined(HAVE_POSIXAIO) n_aiocb = iov.size(); aio.aiocbp = (struct aiocb*)calloc(iov.size(), sizeof(struct aiocb)); for (size_t i = 0; i < iov.size(); i++) { aio.aiocbp[i].aio_fildes = fd; aio.aiocbp[i].aio_buf = iov[i].iov_base; aio.aiocbp[i].aio_nbytes = iov[i].iov_len; aio.aiocbp[i].aio_offset = offset; aio.aiocbp[i].aio_lio_opcode = LIO_READ; offset += iov[i].iov_len; } #endif } long get_return_value() { return rval; } }; std::ostream& operator<<(std::ostream& os, const aio_t& aio); typedef boost::intrusive::list< aio_t, boost::intrusive::member_hook< aio_t, boost::intrusive::list_member_hook<>, &aio_t::queue_item> > aio_list_t; struct io_queue_t { typedef std::list<aio_t>::iterator aio_iter; virtual ~io_queue_t() {}; virtual int init(std::vector<int> &fds) = 0; virtual void shutdown() = 0; virtual int submit_batch(aio_iter begin, aio_iter end, uint16_t aios_size, void *priv, int *retries) = 0; virtual int get_next_completed(int timeout_ms, aio_t **paio, int max) = 0; }; struct aio_queue_t final : public io_queue_t { int max_iodepth; #if defined(HAVE_LIBAIO) io_context_t ctx; #elif defined(HAVE_POSIXAIO) int ctx; #endif explicit aio_queue_t(unsigned max_iodepth) : max_iodepth(max_iodepth), ctx(0) { } ~aio_queue_t() final { ceph_assert(ctx == 0); } int init(std::vector<int> &fds) final { (void)fds; ceph_assert(ctx == 0); #if defined(HAVE_LIBAIO) int r = io_setup(max_iodepth, &ctx); if (r < 0) { if (ctx) { io_destroy(ctx); ctx = 0; } } return r; #elif defined(HAVE_POSIXAIO) ctx = kqueue(); if (ctx < 0) return -errno; else return 0; #endif } void shutdown() final { if (ctx) { #if defined(HAVE_LIBAIO) int r = io_destroy(ctx); #elif defined(HAVE_POSIXAIO) int r = close(ctx); #endif ceph_assert(r == 0); ctx = 0; } } int submit_batch(aio_iter begin, aio_iter end, uint16_t aios_size, void *priv, int *retries) final; int get_next_completed(int timeout_ms, aio_t **paio, int max) final; };
3,965
23.7875
85
h
null
ceph-main/src/blk/kernel/KernelDevice.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) 2014 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_BLK_KERNELDEVICE_H #define CEPH_BLK_KERNELDEVICE_H #include <atomic> #include "include/types.h" #include "include/interval_set.h" #include "common/Thread.h" #include "include/utime.h" #include "aio/aio.h" #include "BlockDevice.h" #include "extblkdev/ExtBlkDevPlugin.h" #define RW_IO_MAX (INT_MAX & CEPH_PAGE_MASK) class KernelDevice : public BlockDevice { protected: std::string path; private: std::vector<int> fd_directs, fd_buffereds; bool enable_wrt = true; bool aio, dio; ExtBlkDevInterfaceRef ebd_impl; // structure for retrieving compression state from extended block device std::string devname; ///< kernel dev name (/sys/block/$devname), if any ceph::mutex debug_lock = ceph::make_mutex("KernelDevice::debug_lock"); interval_set<uint64_t> debug_inflight; std::atomic<bool> io_since_flush = {false}; ceph::mutex flush_mutex = ceph::make_mutex("KernelDevice::flush_mutex"); std::unique_ptr<io_queue_t> io_queue; aio_callback_t discard_callback; void *discard_callback_priv; bool aio_stop; bool discard_started; bool discard_stop; ceph::mutex discard_lock = ceph::make_mutex("KernelDevice::discard_lock"); ceph::condition_variable discard_cond; bool discard_running = false; interval_set<uint64_t> discard_queued; interval_set<uint64_t> discard_finishing; struct AioCompletionThread : public Thread { KernelDevice *bdev; explicit AioCompletionThread(KernelDevice *b) : bdev(b) {} void *entry() override { bdev->_aio_thread(); return NULL; } } aio_thread; struct DiscardThread : public Thread { KernelDevice *bdev; explicit DiscardThread(KernelDevice *b) : bdev(b) {} void *entry() override { bdev->_discard_thread(); return NULL; } } discard_thread; std::atomic_int injecting_crash; virtual int _post_open() { return 0; } // hook for child implementations virtual void _pre_close() { } // hook for child implementations void _aio_thread(); void _discard_thread(); int _queue_discard(interval_set<uint64_t> &to_release); bool try_discard(interval_set<uint64_t> &to_release, bool async = true) override; int _aio_start(); void _aio_stop(); void _discard_start(); void _discard_stop(); void _aio_log_start(IOContext *ioc, uint64_t offset, uint64_t length); void _aio_log_finish(IOContext *ioc, uint64_t offset, uint64_t length); int _sync_write(uint64_t off, ceph::buffer::list& bl, bool buffered, int write_hint); int _lock(); int direct_read_unaligned(uint64_t off, uint64_t len, char *buf); // stalled aio debugging aio_list_t debug_queue; ceph::mutex debug_queue_lock = ceph::make_mutex("KernelDevice::debug_queue_lock"); aio_t *debug_oldest = nullptr; utime_t debug_stall_since; void debug_aio_link(aio_t& aio); void debug_aio_unlink(aio_t& aio); int choose_fd(bool buffered, int write_hint) const; ceph::unique_leakable_ptr<buffer::raw> create_custom_aligned(size_t len, IOContext* ioc) const; public: KernelDevice(CephContext* cct, aio_callback_t cb, void *cbpriv, aio_callback_t d_cb, void *d_cbpriv); void aio_submit(IOContext *ioc) override; void discard_drain() override; int collect_metadata(const std::string& prefix, std::map<std::string,std::string> *pm) const override; int get_devname(std::string *s) const override { if (devname.empty()) { return -ENOENT; } *s = devname; return 0; } int get_devices(std::set<std::string> *ls) const override; int get_ebd_state(ExtBlkDevState &state) const override; int read(uint64_t off, uint64_t len, ceph::buffer::list *pbl, IOContext *ioc, bool buffered) override; int aio_read(uint64_t off, uint64_t len, ceph::buffer::list *pbl, IOContext *ioc) override; int read_random(uint64_t off, uint64_t len, char *buf, bool buffered) override; int write(uint64_t off, ceph::buffer::list& bl, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) override; int aio_write(uint64_t off, ceph::buffer::list& bl, IOContext *ioc, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) override; int flush() override; int _discard(uint64_t offset, uint64_t len); // for managing buffered readers/writers int invalidate_cache(uint64_t off, uint64_t len) override; int open(const std::string& path) override; void close() override; }; #endif
4,767
29.369427
111
h
null
ceph-main/src/blk/kernel/io_uring.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "acconfig.h" #include "include/types.h" #include "aio/aio.h" struct ioring_data; struct ioring_queue_t final : public io_queue_t { std::unique_ptr<ioring_data> d; unsigned iodepth = 0; bool hipri = false; bool sq_thread = false; typedef std::list<aio_t>::iterator aio_iter; // Returns true if arch is x86-64 and kernel supports io_uring static bool supported(); ioring_queue_t(unsigned iodepth_, bool hipri_, bool sq_thread_); ~ioring_queue_t() final; int init(std::vector<int> &fds) final; void shutdown() final; int submit_batch(aio_iter begin, aio_iter end, uint16_t aios_size, void *priv, int *retries) final; int get_next_completed(int timeout_ms, aio_t **paio, int max) final; };
861
24.352941
70
h
null
ceph-main/src/blk/pmem/PMEMDevice.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) 2015 Intel <jianpeng.ma@intel.com> * * Author: Jianpeng Ma <jianpeng.ma@intel.com> * * 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_BLK_PMEMDEVICE_H #define CEPH_BLK_PMEMDEVICE_H #include <atomic> #include <map> #include <string> #include "os/fs/FS.h" #include "include/interval_set.h" #include "aio/aio.h" #include "BlockDevice.h" class PMEMDevice : public BlockDevice { int fd; char *addr; //the address of mmap std::string path; bool devdax_device = false; ceph::mutex debug_lock = ceph::make_mutex("PMEMDevice::debug_lock"); interval_set<uint64_t> debug_inflight; std::atomic_int injecting_crash; int _lock(); public: PMEMDevice(CephContext *cct, aio_callback_t cb, void *cbpriv); bool supported_bdev_label() override { return !devdax_device; } void aio_submit(IOContext *ioc) override; int collect_metadata(const std::string& prefix, std::map<std::string,std::string> *pm) const override; static bool support(const std::string& path); int read(uint64_t off, uint64_t len, bufferlist *pbl, IOContext *ioc, bool buffered) override; int aio_read(uint64_t off, uint64_t len, bufferlist *pbl, IOContext *ioc) override; int read_random(uint64_t off, uint64_t len, char *buf, bool buffered) override; int write(uint64_t off, bufferlist& bl, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) override; int aio_write(uint64_t off, bufferlist& bl, IOContext *ioc, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) override; int flush() override; // for managing buffered readers/writers int invalidate_cache(uint64_t off, uint64_t len) override; int open(const std::string &path) override; void close() override; private: bool is_valid_io(uint64_t off, uint64_t len) const { return (len > 0 && off < size && off + len <= size); } }; #endif
2,206
26.936709
104
h
null
ceph-main/src/blk/spdk/NVMEDevice.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) 2015 XSky <haomai@xsky.com> * * Author: Haomai Wang <haomaiwang@gmail.com> * * 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_BLK_NVMEDEVICE #define CEPH_BLK_NVMEDEVICE #include <queue> #include <map> #include <limits> // since _Static_assert introduced in c11 #define _Static_assert static_assert #include "include/interval_set.h" #include "common/ceph_time.h" #include "BlockDevice.h" enum class IOCommand { READ_COMMAND, WRITE_COMMAND, FLUSH_COMMAND }; class SharedDriverData; class SharedDriverQueueData; class NVMEDevice : public BlockDevice { /** * points to pinned, physically contiguous memory region; * contains 4KB IDENTIFY structure for controller which is * target for CONTROLLER IDENTIFY command during initialization */ SharedDriverData *driver; std::string name; public: SharedDriverData *get_driver() { return driver; } NVMEDevice(CephContext* cct, aio_callback_t cb, void *cbpriv); bool supported_bdev_label() override { return false; } static bool support(const std::string& path); void aio_submit(IOContext *ioc) override; int read(uint64_t off, uint64_t len, bufferlist *pbl, IOContext *ioc, bool buffered) override; int aio_read( uint64_t off, uint64_t len, bufferlist *pbl, IOContext *ioc) override; int aio_write(uint64_t off, bufferlist& bl, IOContext *ioc, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) override; int write(uint64_t off, bufferlist& bl, bool buffered, int write_hint = WRITE_LIFE_NOT_SET) override; int flush() override; int read_random(uint64_t off, uint64_t len, char *buf, bool buffered) override; // for managing buffered readers/writers int invalidate_cache(uint64_t off, uint64_t len) override; int open(const std::string& path) override; void close() override; int collect_metadata(const std::string& prefix, std::map<std::string,std::string> *pm) const override; }; #endif
2,323
26.341176
104
h
null
ceph-main/src/blk/zoned/HMSMRDevice.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) 2014 Red Hat * Copyright (C) 2020 Abutalib Aghayev * * 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_BLK_HMSMRDEVICE_H #define CEPH_BLK_HMSMRDEVICE_H #include <atomic> #include "include/types.h" #include "include/interval_set.h" #include "common/Thread.h" #include "include/utime.h" #include "aio/aio.h" #include "BlockDevice.h" #include "../kernel/KernelDevice.h" class HMSMRDevice final : public KernelDevice { int zbd_fd = -1; ///< fd for the zoned block device public: HMSMRDevice(CephContext* cct, aio_callback_t cb, void *cbpriv, aio_callback_t d_cb, void *d_cbpriv); static bool support(const std::string& path); // open/close hooks for libzbd int _post_open() override; void _pre_close() override; // smr-specific methods bool is_smr() const final { return true; } void reset_all_zones() override; void reset_zone(uint64_t zone) override; std::vector<uint64_t> get_zones() override; }; #endif //CEPH_BLK_HMSMRDEVICE_H
1,323
23.981132
70
h
null
ceph-main/src/client/ClientSnapRealm.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLIENT_SNAPREALM_H #define CEPH_CLIENT_SNAPREALM_H #include "include/types.h" #include "common/snap_types.h" #include "include/xlist.h" struct Inode; struct SnapRealm { inodeno_t ino; int nref; snapid_t created; snapid_t seq; inodeno_t parent; snapid_t parent_since; std::vector<snapid_t> prior_parent_snaps; // snaps prior to parent_since std::vector<snapid_t> my_snaps; SnapRealm *pparent; std::set<SnapRealm*> pchildren; utime_t last_modified; uint64_t change_attr; private: SnapContext cached_snap_context; // my_snaps + parent snaps + past_parent_snaps friend std::ostream& operator<<(std::ostream& out, const SnapRealm& r); public: xlist<Inode*> inodes_with_caps; explicit SnapRealm(inodeno_t i) : ino(i), nref(0), created(0), seq(0), pparent(NULL), last_modified(utime_t()), change_attr(0) { } void build_snap_context(); void invalidate_cache() { cached_snap_context.clear(); } const SnapContext& get_snap_context() { if (cached_snap_context.seq == 0) build_snap_context(); return cached_snap_context; } void dump(Formatter *f) const; }; inline std::ostream& operator<<(std::ostream& out, const SnapRealm& r) { return out << "snaprealm(" << r.ino << " nref=" << r.nref << " c=" << r.created << " seq=" << r.seq << " parent=" << r.parent << " my_snaps=" << r.my_snaps << " cached_snapc=" << r.cached_snap_context << " last_modified=" << r.last_modified << " change_attr=" << r.change_attr << ")"; } #endif
1,649
24.384615
101
h
null
ceph-main/src/client/Delegation.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef _CEPH_CLIENT_DELEGATION_H #define _CEPH_CLIENT_DELEGATION_H #include "common/Clock.h" #include "common/Timer.h" #include "include/cephfs/ceph_ll_client.h" /* Commands for manipulating delegation state */ #ifndef CEPH_DELEGATION_NONE # define CEPH_DELEGATION_NONE 0 # define CEPH_DELEGATION_RD 1 # define CEPH_DELEGATION_WR 2 #endif /* Converts CEPH_DELEGATION_* to cap mask */ int ceph_deleg_caps_for_type(unsigned type); /* * A delegation is a container for holding caps on behalf of a client that * wants to be able to rely on them until recalled. */ class Delegation { public: Delegation(Fh *_fh, unsigned _type, ceph_deleg_cb_t _cb, void *_priv); ~Delegation(); Fh *get_fh() { return fh; } unsigned get_type() { return type; } bool is_recalled() { return !recall_time.is_zero(); } void reinit(unsigned _type, ceph_deleg_cb_t _recall_cb, void *_priv); void recall(bool skip_read); private: // Filehandle against which it was acquired Fh *fh; // opaque token that will be passed to the callback void *priv; // CEPH_DELEGATION_* type unsigned type; // callback into application to recall delegation ceph_deleg_cb_t recall_cb; // time of first recall utime_t recall_time; // timer for unreturned delegations Context *timeout_event; void arm_timeout(); void disarm_timeout(); }; #endif /* _CEPH_CLIENT_DELEGATION_H */
1,493
24.758621
74
h
null
ceph-main/src/client/Dentry.h
#ifndef CEPH_CLIENT_DENTRY_H #define CEPH_CLIENT_DENTRY_H #include "include/lru.h" #include "include/xlist.h" #include "mds/mdstypes.h" #include "Inode.h" #include "InodeRef.h" #include "Dir.h" class Dentry : public LRUObject { public: explicit Dentry(Dir *_dir, const std::string &_name) : dir(_dir), name(_name), inode_xlist_link(this) { auto r = dir->dentries.insert(make_pair(name, this)); ceph_assert(r.second); dir->num_null_dentries++; } ~Dentry() { ceph_assert(ref == 0); ceph_assert(dir == nullptr); } /* * ref==1 -> cached, unused * ref >1 -> pinned in lru */ void get() { ceph_assert(ref > 0); if (++ref == 2) lru_pin(); //cout << "dentry.get on " << this << " " << name << " now " << ref << std::endl; } void put() { ceph_assert(ref > 0); if (--ref == 1) lru_unpin(); //cout << "dentry.put on " << this << " " << name << " now " << ref << std::endl; if (ref == 0) delete this; } void link(InodeRef in) { inode = in; inode->dentries.push_back(&inode_xlist_link); if (inode->is_dir()) { if (inode->dir) get(); // dir -> dn pin if (inode->ll_ref) get(); // ll_ref -> dn pin } dir->num_null_dentries--; } void unlink(void) { if (inode->is_dir()) { if (inode->dir) put(); // dir -> dn pin if (inode->ll_ref) put(); // ll_ref -> dn pin } ceph_assert(inode_xlist_link.get_list() == &inode->dentries); inode_xlist_link.remove_myself(); inode.reset(); dir->num_null_dentries++; } void mark_primary() { if (inode && inode->dentries.front() != this) inode->dentries.push_front(&inode_xlist_link); } void detach(void) { ceph_assert(!inode); auto p = dir->dentries.find(name); ceph_assert(p != dir->dentries.end()); dir->dentries.erase(p); dir->num_null_dentries--; dir = nullptr; } void dump(Formatter *f) const; friend std::ostream &operator<<(std::ostream &oss, const Dentry &Dentry); Dir *dir; const std::string name; InodeRef inode; int ref = 1; // 1 if there's a dir beneath me. int64_t offset = 0; mds_rank_t lease_mds = -1; utime_t lease_ttl; uint64_t lease_gen = 0; ceph_seq_t lease_seq = 0; int cap_shared_gen = 0; std::string alternate_name; bool is_renaming = false; private: xlist<Dentry *>::item inode_xlist_link; }; #endif
2,430
23.069307
85
h
null
ceph-main/src/client/Fh.h
#ifndef CEPH_CLIENT_FH_H #define CEPH_CLIENT_FH_H #include "common/Readahead.h" #include "include/types.h" #include "InodeRef.h" #include "UserPerm.h" #include "mds/flock.h" class Inode; // file handle for any open file state struct Fh { InodeRef inode; int flags; uint64_t gen; UserPerm actor_perms; // perms I opened the file with // the members above once ininitalized in the constructor // they won't change, and putting them under the client_lock // makes no sense. int _ref = 1; loff_t pos = 0; int mode; // the mode i opened the file with bool pos_locked = false; // pos is currently in use std::list<ceph::condition_variable*> pos_waiters; // waiters for pos Readahead readahead; // file lock std::unique_ptr<ceph_lock_state_t> fcntl_locks; std::unique_ptr<ceph_lock_state_t> flock_locks; bool has_any_filelocks() { return (fcntl_locks && !fcntl_locks->empty()) || (flock_locks && !flock_locks->empty()); } // IO error encountered by any writeback on this Inode while // this Fh existed (i.e. an fsync on another Fh will still show // up as an async_err here because it could have been the same // bytes we wrote via this Fh). int async_err = {0}; int take_async_err() { int e = async_err; async_err = 0; return e; } Fh() = delete; Fh(InodeRef in, int flags, int cmode, uint64_t gen, const UserPerm &perms); ~Fh(); void get() { ++_ref; } int put() { return --_ref; } }; #endif
1,539
22.333333
77
h
null
ceph-main/src/client/Inode.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLIENT_INODE_H #define CEPH_CLIENT_INODE_H #include <numeric> #include "include/compat.h" #include "include/ceph_assert.h" #include "include/types.h" #include "include/xlist.h" #include "mds/flock.h" #include "mds/mdstypes.h" // hrm #include "include/cephfs/types.h" #include "osdc/ObjectCacher.h" #include "InodeRef.h" #include "MetaSession.h" #include "UserPerm.h" #include "Delegation.h" class Client; class Dentry; class Dir; struct SnapRealm; struct Inode; class MetaRequest; class filepath; class Fh; class Cap { public: Cap() = delete; Cap(Inode &i, MetaSession *s) : inode(i), session(s), gen(s->cap_gen), cap_item(this) { s->caps.push_back(&cap_item); } ~Cap() { cap_item.remove_myself(); } void touch(void) { // move to back of LRU session->caps.push_back(&cap_item); } void dump(Formatter *f) const; Inode &inode; MetaSession *session; uint64_t cap_id = 0; unsigned issued = 0; unsigned implemented = 0; unsigned wanted = 0; // as known to mds. uint64_t seq = 0; uint64_t issue_seq = 0; __u32 mseq = 0; // migration seq __u32 gen; UserPerm latest_perms; private: /* Note that this Cap will not move (see Inode::caps): * * Section 23.1.2#8 * The insert members shall not affect the validity of iterators and * references to the container, and the erase members shall invalidate only * iterators and references to the erased elements. */ xlist<Cap *>::item cap_item; }; struct CapSnap { //snapid_t follows; // map key InodeRef in; SnapContext context; int issued = 0, dirty = 0; uint64_t size = 0; utime_t ctime, btime, mtime, atime; version_t time_warp_seq = 0; uint64_t change_attr = 0; uint32_t mode = 0; uid_t uid = 0; gid_t gid = 0; std::map<std::string,bufferptr> xattrs; version_t xattr_version = 0; bufferlist inline_data; version_t inline_version = 0; bool writing = false, dirty_data = false; uint64_t flush_tid = 0; int64_t cap_dirtier_uid = -1; int64_t cap_dirtier_gid = -1; explicit CapSnap(Inode *i) : in(i) {} void dump(Formatter *f) const; }; // inode flags #define I_COMPLETE (1 << 0) #define I_DIR_ORDERED (1 << 1) #define I_SNAPDIR_OPEN (1 << 2) #define I_KICK_FLUSH (1 << 3) #define I_CAP_DROPPED (1 << 4) #define I_ERROR_FILELOCK (1 << 5) struct Inode : RefCountedObject { ceph::coarse_mono_time hold_caps_until; Client *client; // -- the actual inode -- inodeno_t ino; // ORDER DEPENDENCY: oset snapid_t snapid; ino_t faked_ino = 0; uint32_t rdev = 0; // if special file // affected by any inode change... utime_t ctime; // inode change time utime_t btime; // birth time // perm (namespace permissions) uint32_t mode = 0; uid_t uid = 0; gid_t gid = 0; // nlink int32_t nlink = 0; // file (data access) ceph_dir_layout dir_layout{}; file_layout_t layout; uint64_t size = 0; // on directory, # dentries uint32_t truncate_seq = 1; uint64_t truncate_size = -1; utime_t mtime; // file data modify time. utime_t atime; // file data access time. uint32_t time_warp_seq = 0; // count of (potential) mtime/atime timewarps (i.e., utimes()) uint64_t change_attr = 0; uint64_t max_size = 0; // max size we can write to // dirfrag, recursive accountin frag_info_t dirstat; nest_info_t rstat; // special stuff version_t version = 0; // auth only version_t xattr_version = 0; utime_t snap_btime; // snapshot creation (birth) time std::map<std::string, std::string> snap_metadata; // inline data version_t inline_version = 0; bufferlist inline_data; std::vector<uint8_t> fscrypt_auth; std::vector<uint8_t> fscrypt_file; bool is_fscrypt_enabled() { return !!fscrypt_auth.size(); } bool is_root() const { return ino == CEPH_INO_ROOT; } bool is_symlink() const { return (mode & S_IFMT) == S_IFLNK; } bool is_dir() const { return (mode & S_IFMT) == S_IFDIR; } bool is_file() const { return (mode & S_IFMT) == S_IFREG; } bool has_dir_layout() const { return layout != file_layout_t(); } __u32 hash_dentry_name(const std::string &dn) { int which = dir_layout.dl_dir_hash; if (!which) which = CEPH_STR_HASH_LINUX; ceph_assert(ceph_str_hash_valid(which)); return ceph_str_hash(which, dn.data(), dn.length()); } unsigned flags = 0; quota_info_t quota; bool is_complete_and_ordered() { static const unsigned wants = I_COMPLETE | I_DIR_ORDERED; return (flags & wants) == wants; } // about the dir (if this is one!) Dir *dir = 0; // if i'm a dir. fragtree_t dirfragtree; uint64_t dir_release_count = 1; uint64_t dir_ordered_count = 1; bool dir_hashed = false; bool dir_replicated = false; // per-mds caps std::map<mds_rank_t, Cap> caps; // mds -> Cap Cap *auth_cap = 0; int64_t cap_dirtier_uid = -1; int64_t cap_dirtier_gid = -1; unsigned dirty_caps = 0; unsigned flushing_caps = 0; std::map<ceph_tid_t, int> flushing_cap_tids; int shared_gen = 0; int cache_gen = 0; int snap_caps = 0; int snap_cap_refs = 0; xlist<Inode*>::item delay_cap_item, dirty_cap_item, flushing_cap_item; SnapRealm *snaprealm = 0; xlist<Inode*>::item snaprealm_item; InodeRef snapdir_parent; // only if we are a snapdir inode std::map<snapid_t,CapSnap> cap_snaps; // pending flush to mds //int open_by_mode[CEPH_FILE_MODE_NUM]; std::map<int,int> open_by_mode; std::map<int,int> cap_refs; ObjectCacher::ObjectSet oset; // ORDER DEPENDENCY: ino uint64_t reported_size = 0; uint64_t wanted_max_size = 0; uint64_t requested_max_size = 0; uint64_t ll_ref = 0; // separate ref count for ll client xlist<Dentry *> dentries; // if i'm linked to a dentry. std::string symlink; // symlink content, if it's a symlink std::map<std::string,bufferptr> xattrs; std::map<frag_t,int> fragmap; // known frag -> mds mappings std::map<frag_t, std::vector<mds_rank_t>> frag_repmap; // non-auth mds mappings std::list<ceph::condition_variable*> waitfor_caps; std::list<ceph::condition_variable*> waitfor_commit; std::list<ceph::condition_variable*> waitfor_deleg; Dentry *get_first_parent() { ceph_assert(!dentries.empty()); return *dentries.begin(); } void make_long_path(filepath& p); void make_short_path(filepath& p); void make_nosnap_relative_path(filepath& p); // The ref count. 1 for each dentry, fh, inode_map, // cwd that links to me. void iget() { get(); } void iput(int n=1) { ceph_assert(n >= 0); while (n--) put(); } void ll_get() { ll_ref++; } void ll_put(uint64_t n=1) { ceph_assert(ll_ref >= n); ll_ref -= n; } // file locks std::unique_ptr<ceph_lock_state_t> fcntl_locks; std::unique_ptr<ceph_lock_state_t> flock_locks; bool has_any_filelocks() { return (fcntl_locks && !fcntl_locks->empty()) || (flock_locks && !flock_locks->empty()); } std::list<Delegation> delegations; xlist<MetaRequest*> unsafe_ops; std::set<Fh*> fhs; mds_rank_t dir_pin = MDS_RANK_NONE; Inode() = delete; Inode(Client *c, vinodeno_t vino, file_layout_t *newlayout) : client(c), ino(vino.ino), snapid(vino.snapid), delay_cap_item(this), dirty_cap_item(this), flushing_cap_item(this), snaprealm_item(this), oset((void *)this, newlayout->pool_id, this->ino) {} ~Inode(); vinodeno_t vino() const { return vinodeno_t(ino, snapid); } struct Compare { bool operator() (Inode* const & left, Inode* const & right) { if (left->ino.val < right->ino.val) { return (left->snapid.val < right->snapid.val); } return false; } }; bool check_mode(const UserPerm& perms, unsigned want); // CAPS -------- void get_open_ref(int mode); bool put_open_ref(int mode); void get_cap_ref(int cap); int put_cap_ref(int cap); bool is_any_caps(); bool cap_is_valid(const Cap &cap) const; int caps_issued(int *implemented = 0) const; void try_touch_cap(mds_rank_t mds); bool caps_issued_mask(unsigned mask, bool allow_impl=false); int caps_used(); int caps_file_wanted(); int caps_wanted(); int caps_mds_wanted(); int caps_dirty(); const UserPerm *get_best_perms(); bool have_valid_size(); Dir *open_dir(); void add_fh(Fh *f) {fhs.insert(f);} void rm_fh(Fh *f) {fhs.erase(f);} void set_async_err(int r); void dump(Formatter *f) const; void break_all_delegs() { break_deleg(false); }; void recall_deleg(bool skip_read); bool has_recalled_deleg(); int set_deleg(Fh *fh, unsigned type, ceph_deleg_cb_t cb, void *priv); void unset_deleg(Fh *fh); void mark_caps_dirty(int caps); void mark_caps_clean(); private: // how many opens for write on this Inode? long open_count_for_write() { return (long)(open_by_mode[CEPH_FILE_MODE_RDWR] + open_by_mode[CEPH_FILE_MODE_WR]); }; // how many opens of any sort on this inode? long open_count() { return (long) std::accumulate(open_by_mode.begin(), open_by_mode.end(), 0, [] (int value, const std::map<int, int>::value_type& p) { return value + p.second; }); }; void break_deleg(bool skip_read); bool delegations_broken(bool skip_read); }; std::ostream& operator<<(std::ostream &out, const Inode &in); #endif
9,590
25.133515
95
h
null
ceph-main/src/client/MetaRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLIENT_METAREQUEST_H #define CEPH_CLIENT_METAREQUEST_H #include "include/types.h" #include "include/xlist.h" #include "include/filepath.h" #include "mds/mdstypes.h" #include "InodeRef.h" #include "UserPerm.h" #include "messages/MClientRequest.h" #include "messages/MClientReply.h" class Dentry; class dir_result_t; struct MetaRequest { private: InodeRef _inode, _old_inode, _other_inode; Dentry *_dentry = NULL; //associated with path Dentry *_old_dentry = NULL; //associated with path2 int abort_rc = 0; public: ceph::coarse_mono_time created = ceph::coarse_mono_clock::zero(); uint64_t tid = 0; utime_t op_stamp; ceph_mds_request_head head; filepath path, path2; std::string alternate_name; std::vector<uint8_t> fscrypt_auth; std::vector<uint8_t> fscrypt_file; bufferlist data; int inode_drop = 0; //the inode caps this operation will drop int inode_unless = 0; //unless we have these caps already int old_inode_drop = 0, old_inode_unless = 0; int dentry_drop = 0, dentry_unless = 0; int old_dentry_drop = 0, old_dentry_unless = 0; int other_inode_drop = 0, other_inode_unless = 0; std::vector<MClientRequest::Release> cap_releases; int regetattr_mask = 0; // getattr mask if i need to re-stat after a traceless reply utime_t sent_stamp; mds_rank_t mds = -1; // who i am asking mds_rank_t resend_mds = -1; // someone wants you to (re)send the request here bool send_to_auth = false; // must send to auth mds __u32 sent_on_mseq = 0; // mseq at last submission of this request int num_fwd = 0; // # of times i've been forwarded int retry_attempt = 0; std::atomic<uint64_t> ref = { 1 }; ceph::cref_t<MClientReply> reply = NULL; // the reply bool kick = false; bool success = false; // readdir result dir_result_t *dirp = NULL; //possible responses bool got_unsafe = false; xlist<MetaRequest*>::item item; xlist<MetaRequest*>::item unsafe_item; xlist<MetaRequest*>::item unsafe_dir_item; xlist<MetaRequest*>::item unsafe_target_item; ceph::condition_variable *caller_cond = NULL; // who to take up ceph::condition_variable *dispatch_cond = NULL; // who to kick back std::list<ceph::condition_variable*> waitfor_safe; InodeRef target; UserPerm perms; explicit MetaRequest(int op) : item(this), unsafe_item(this), unsafe_dir_item(this), unsafe_target_item(this) { memset(&head, 0, sizeof(head)); head.op = op; } ~MetaRequest(); /** * Prematurely terminate the request, such that callers * to make_request will receive `rc` as their result. */ void abort(int rc) { ceph_assert(rc != 0); abort_rc = rc; } /** * Whether abort() has been called for this request */ inline bool aborted() const { return abort_rc != 0; } /** * Given that abort() has been called for this request, what `rc` was * passed into it? */ int get_abort_code() const { return abort_rc; } void set_inode(Inode *in) { _inode = in; } Inode *inode() { return _inode.get(); } void take_inode(InodeRef *out) { out->swap(_inode); } void set_old_inode(Inode *in) { _old_inode = in; } Inode *old_inode() { return _old_inode.get(); } void take_old_inode(InodeRef *out) { out->swap(_old_inode); } void set_other_inode(Inode *in) { _other_inode = in; } Inode *other_inode() { return _other_inode.get(); } void take_other_inode(InodeRef *out) { out->swap(_other_inode); } void set_dentry(Dentry *d); Dentry *dentry(); void set_old_dentry(Dentry *d); Dentry *old_dentry(); MetaRequest* get() { ref++; return this; } /// psuedo-private put method; use Client::put_request() bool _put() { int v = --ref; return v == 0; } // normal fields void set_tid(ceph_tid_t t) { tid = t; } void set_oldest_client_tid(ceph_tid_t t) { head.oldest_client_tid = t; } void inc_num_fwd() { head.ext_num_fwd = head.ext_num_fwd + 1; } void set_retry_attempt(int a) { head.ext_num_retry = a; } void set_filepath(const filepath& fp) { path = fp; } void set_filepath2(const filepath& fp) { path2 = fp; } void set_alternate_name(std::string an) { alternate_name = an; } void set_string2(const char *s) { path2.set_path(std::string_view(s), 0); } void set_caller_perms(const UserPerm& _perms) { perms = _perms; head.caller_uid = perms.uid(); head.caller_gid = perms.gid(); } uid_t get_uid() { return perms.uid(); } uid_t get_gid() { return perms.gid(); } void set_data(const bufferlist &d) { data = d; } void set_dentry_wanted() { head.flags = head.flags | CEPH_MDS_FLAG_WANT_DENTRY; } int get_op() { return head.op; } ceph_tid_t get_tid() { return tid; } filepath& get_filepath() { return path; } filepath& get_filepath2() { return path2; } bool is_write() { return (head.op & CEPH_MDS_OP_WRITE) || (head.op == CEPH_MDS_OP_OPEN && (head.args.open.flags & (O_CREAT|O_TRUNC))); } bool can_forward() { if ((head.op & CEPH_MDS_OP_WRITE) || head.op == CEPH_MDS_OP_OPEN) // do not forward _any_ open request. return false; return true; } bool auth_is_best(int issued) { if (send_to_auth) return true; /* Any write op ? */ if (head.op & CEPH_MDS_OP_WRITE) return true; switch (head.op) { case CEPH_MDS_OP_OPEN: case CEPH_MDS_OP_READDIR: return true; case CEPH_MDS_OP_GETATTR: /* * If any 'x' caps is issued we can just choose the auth MDS * instead of the random replica MDSes. Because only when the * Locker is in LOCK_EXEC state will the loner client could * get the 'x' caps. And if we send the getattr requests to * any replica MDS it must auth pin and tries to rdlock from * the auth MDS, and then the auth MDS need to do the Locker * state transition to LOCK_SYNC. And after that the lock state * will change back. * * This cost much when doing the Locker state transition and * usually will need to revoke caps from clients. * * And for the 'Xs' caps for getxattr we will also choose the * auth MDS, because the MDS side code is buggy due to setxattr * won't notify the replica MDSes when the values changed and * the replica MDS will return the old values. Though we will * fix it in MDS code, but this still makes sense for old ceph. */ if (((head.args.getattr.mask & CEPH_CAP_ANY_SHARED) && (issued & CEPH_CAP_ANY_EXCL)) || (head.args.getattr.mask & (CEPH_STAT_RSTAT | CEPH_STAT_CAP_XATTR))) return true; default: return false; } } void dump(Formatter *f) const; }; #endif
6,922
28.088235
95
h
null
ceph-main/src/client/MetaSession.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLIENT_METASESSION_H #define CEPH_CLIENT_METASESSION_H #include "include/types.h" #include "include/utime.h" #include "include/xlist.h" #include "mds/MDSMap.h" #include "mds/mdstypes.h" #include "messages/MClientCapRelease.h" struct Cap; struct Inode; struct CapSnap; struct MetaRequest; struct MetaSession { mds_rank_t mds_num; ConnectionRef con; version_t seq = 0; uint64_t cap_gen = 0; utime_t cap_ttl, last_cap_renew_request; uint64_t cap_renew_seq = 0; entity_addrvec_t addrs; feature_bitset_t mds_features; feature_bitset_t mds_metric_flags; enum { STATE_NEW, // Unused STATE_OPENING, STATE_OPEN, STATE_CLOSING, STATE_CLOSED, STATE_STALE, STATE_REJECTED, } state = STATE_OPENING; enum { RECLAIM_NULL, RECLAIMING, RECLAIM_OK, RECLAIM_FAIL, } reclaim_state = RECLAIM_NULL; int mds_state = MDSMap::STATE_NULL; bool readonly = false; std::list<Context*> waiting_for_open; xlist<Cap*> caps; // dirty_list keeps all the dirty inodes before flushing in current session. xlist<Inode*> dirty_list; xlist<Inode*> flushing_caps; xlist<MetaRequest*> requests; xlist<MetaRequest*> unsafe_requests; std::set<ceph_tid_t> flushing_caps_tids; ceph::ref_t<MClientCapRelease> release; MetaSession(mds_rank_t mds_num, ConnectionRef con, const entity_addrvec_t& addrs) : mds_num(mds_num), con(con), addrs(addrs) { } xlist<Inode*> &get_dirty_list() { return dirty_list; } const char *get_state_name() const; void dump(Formatter *f, bool cap_dump=false) const; void enqueue_cap_release(inodeno_t ino, uint64_t cap_id, ceph_seq_t iseq, ceph_seq_t mseq, epoch_t osd_barrier); }; using MetaSessionRef = std::shared_ptr<MetaSession>; #endif
1,861
22.871795
83
h
null
ceph-main/src/client/ObjecterWriteback.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OSDC_OBJECTERWRITEBACKHANDLER_H #define CEPH_OSDC_OBJECTERWRITEBACKHANDLER_H #include "osdc/Objecter.h" #include "osdc/WritebackHandler.h" class ObjecterWriteback : public WritebackHandler { public: ObjecterWriteback(Objecter *o, Finisher *fin, ceph::mutex *lock) : m_objecter(o), m_finisher(fin), m_lock(lock) { } ~ObjecterWriteback() override {} void read(const object_t& oid, uint64_t object_no, const object_locator_t& oloc, uint64_t off, uint64_t len, snapid_t snapid, bufferlist *pbl, uint64_t trunc_size, __u32 trunc_seq, int op_flags, const ZTracer::Trace &parent_trace, Context *onfinish) override { m_objecter->read_trunc(oid, oloc, off, len, snapid, pbl, 0, trunc_size, trunc_seq, new C_OnFinisher(new C_Lock(m_lock, onfinish), m_finisher)); } bool may_copy_on_write(const object_t& oid, uint64_t read_off, uint64_t read_len, snapid_t snapid) override { return false; } ceph_tid_t write(const object_t& oid, const object_locator_t& oloc, uint64_t off, uint64_t len, const SnapContext& snapc, const bufferlist &bl, ceph::real_time mtime, uint64_t trunc_size, __u32 trunc_seq, ceph_tid_t journal_tid, const ZTracer::Trace &parent_trace, Context *oncommit) override { return m_objecter->write_trunc(oid, oloc, off, len, snapc, bl, mtime, 0, trunc_size, trunc_seq, new C_OnFinisher(new C_Lock(m_lock, oncommit), m_finisher)); } bool can_scattered_write() override { return true; } using WritebackHandler::write; ceph_tid_t write(const object_t& oid, const object_locator_t& oloc, std::vector<std::pair<uint64_t, bufferlist> >& io_vec, const SnapContext& snapc, ceph::real_time mtime, uint64_t trunc_size, __u32 trunc_seq, Context *oncommit) override { ObjectOperation op; for (auto& [offset, bl] : io_vec) op.write(offset, bl, trunc_size, trunc_seq); return m_objecter->mutate(oid, oloc, op, snapc, mtime, 0, new C_OnFinisher(new C_Lock(m_lock, oncommit), m_finisher)); } private: Objecter *m_objecter; Finisher *m_finisher; ceph::mutex *m_lock; }; #endif
2,406
32.901408
81
h
null
ceph-main/src/client/RWRef.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) 2020 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * * ============ * * This is a common read/write reference framework, which will work * simliarly to a RW lock, the difference here is that for the "readers" * they won't hold any lock but will increase a reference instead when * the "require" state is matched, or set a flag to tell the callers * that the "require" state is not matched and also there is no any * wait mechanism for "readers" to wait the state until it matches. It * will let the callers determine what to do next. * * The usage, such as in libcephfs's client/Client.cc case: * * The Readers: * * For the ll_read()/ll_write(), etc fucntions, they will work as * "readers", in the beginning they just need to define a RWRef * object and in RWRef constructor it will check if the state is * MOUNTED or MOUTING, if not it will fail and return directly with * doing nothing, or it will increase the reference and continue. * And when destructing the RWRef object, in the RWRef destructor * it will decrease the reference and notify the "writers" who maybe * waiting. * * The Writers: * * And for the _unmount() function , as a "writer", in the beginning * it will also just need to define a RWRef object and in RWRef * constructor it will update the state to next stage first, which then * will fail all the new comming "readers", and then wait for all the * "readers" to finish. * * With this we can get rid of the locks for all the "readers" and they * can run in parallel. And we won't have any potential deadlock issue * with RWRef, such as: * * With RWLock: * * ThreadA: ThreadB: * * write_lock<RWLock1>.lock(); another_lock.lock(); * state = NEXT_STATE; ... * another_lock.lock(); read_lock<RWLock1>.lock(); * ... if (state == STATE) { * ... * } * ... * * With RWRef: * * ThreadA: ThreadB: * * w = RWRef(myS, NEXT_STATE, false); another_lock.lock(); * another_lock.lock(); r = RWRef(myS, STATE); * ... if (r.is_state_satisfied()) { * ... * } * ... * * And also in ThreadA, if it needs to do the cond.wait(&another_lock), * it will goto sleep by holding the write_lock<RWLock1> for the RWLock * case, if the ThreadBs are for some IOs, they may stuck for a very long * time that may get timedout in the uplayer which may keep retrying. * With the RWRef, the ThreadB will fail or continue directly without any * stuck, and the uplayer will knew what next to do quickly. */ #ifndef CEPH_RWRef_Posix__H #define CEPH_RWRef_Posix__H #include <string> #include "include/ceph_assert.h" #include "common/ceph_mutex.h" /* The status mechanism info */ template<typename T> struct RWRefState { public: template <typename T1> friend class RWRef; /* * This will be status mechanism. Currently you need to define * it by yourself. */ T state; /* * User defined method to check whether the "require" state * is in the proper range we need. * * For example for the client/Client.cc: * In some reader operation cases we need to make sure the * client state is in mounting or mounted states, then it * will set the "require = mounting" in class RWRef's constructor. * Then the check_reader_state() should return truth if the * state is already in mouting or mounted state. */ virtual int check_reader_state(T require) const = 0; /* * User defined method to check whether the "require" state * is in the proper range we need. * * This will usually be the state migration check. */ virtual int check_writer_state(T require) const = 0; /* * User defined method to check whether the "require" * state is valid or not. */ virtual bool is_valid_state(T require) const = 0; int64_t get_state() const { std::scoped_lock l{lock}; return state; } bool check_current_state(T require) const { ceph_assert(is_valid_state(require)); std::scoped_lock l{lock}; return state == require; } RWRefState(T init_state, const char *lockname, uint64_t _reader_cnt=0) : state(init_state), lock(ceph::make_mutex(lockname)), reader_cnt(_reader_cnt) {} virtual ~RWRefState() {} private: mutable ceph::mutex lock; ceph::condition_variable cond; uint64_t reader_cnt = 0; }; template<typename T> class RWRef { public: RWRef(const RWRef& other) = delete; const RWRef& operator=(const RWRef& other) = delete; RWRef(RWRefState<T> &s, T require, bool ir=true) :S(s), is_reader(ir) { ceph_assert(S.is_valid_state(require)); std::scoped_lock l{S.lock}; if (likely(is_reader)) { // Readers will update the reader_cnt if (S.check_reader_state(require)) { S.reader_cnt++; satisfied = true; } } else { // Writers will update the state is_reader = false; /* * If the current state is not the same as "require" * then update the state and we are the first writer. * * Or if there already has one writer running or * finished, it will let user to choose to continue * or just break. */ if (S.check_writer_state(require)) { first_writer = true; S.state = require; } satisfied = true; } } /* * Whether the "require" state is in the proper range of * the states. */ bool is_state_satisfied() const { return satisfied; } /* * Update the state, and only the writer could do the update. */ void update_state(T new_state) { ceph_assert(!is_reader); ceph_assert(S.is_valid_state(new_state)); std::scoped_lock l{S.lock}; S.state = new_state; } /* * For current state whether we are the first writer or not */ bool is_first_writer() const { return first_writer; } /* * Will wait for all the in-flight "readers" to finish */ void wait_readers_done() { // Only writers can wait ceph_assert(!is_reader); std::unique_lock l{S.lock}; S.cond.wait(l, [this] { return !S.reader_cnt; }); } ~RWRef() { std::scoped_lock l{S.lock}; if (!is_reader) return; if (!satisfied) return; /* * Decrease the refcnt and notify the waiters */ if (--S.reader_cnt == 0) S.cond.notify_all(); } private: RWRefState<T> &S; bool satisfied = false; bool first_writer = false; bool is_reader = true; }; #endif // !CEPH_RWRef_Posix__H
7,286
28.742857
87
h
null
ceph-main/src/client/SyntheticClient.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) 2004-2006 Sage Weil <sage@newdream.net> * * 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_SYNTHETICCLIENT_H #define CEPH_SYNTHETICCLIENT_H #include <pthread.h> #include "Client.h" #include "include/Distribution.h" #include "Trace.h" #define SYNCLIENT_FIRST_POOL 0 #define SYNCLIENT_MODE_RANDOMWALK 1 #define SYNCLIENT_MODE_FULLWALK 2 #define SYNCLIENT_MODE_REPEATWALK 3 #define SYNCLIENT_MODE_MAKEDIRMESS 7 #define SYNCLIENT_MODE_MAKEDIRS 8 // dirs files depth #define SYNCLIENT_MODE_STATDIRS 9 // dirs files depth #define SYNCLIENT_MODE_READDIRS 10 // dirs files depth #define SYNCLIENT_MODE_MAKEFILES 11 // num count private #define SYNCLIENT_MODE_MAKEFILES2 12 // num count private #define SYNCLIENT_MODE_CREATESHARED 13 // num #define SYNCLIENT_MODE_OPENSHARED 14 // num count #define SYNCLIENT_MODE_RMFILE 19 #define SYNCLIENT_MODE_WRITEFILE 20 #define SYNCLIENT_MODE_READFILE 21 #define SYNCLIENT_MODE_WRITEBATCH 22 #define SYNCLIENT_MODE_WRSHARED 23 #define SYNCLIENT_MODE_READSHARED 24 #define SYNCLIENT_MODE_RDWRRANDOM 25 #define SYNCLIENT_MODE_RDWRRANDOM_EX 26 #define SYNCLIENT_MODE_LINKTEST 27 #define SYNCLIENT_MODE_OVERLOAD_OSD_0 28 // two args #define SYNCLIENT_MODE_DROPCACHE 29 #define SYNCLIENT_MODE_TRACE 30 #define SYNCLIENT_MODE_CREATEOBJECTS 35 #define SYNCLIENT_MODE_OBJECTRW 36 #define SYNCLIENT_MODE_OPENTEST 40 #define SYNCLIENT_MODE_OPTEST 41 #define SYNCLIENT_MODE_ONLY 50 #define SYNCLIENT_MODE_ONLYRANGE 51 #define SYNCLIENT_MODE_EXCLUDE 52 #define SYNCLIENT_MODE_EXCLUDERANGE 53 #define SYNCLIENT_MODE_UNTIL 55 #define SYNCLIENT_MODE_SLEEPUNTIL 56 #define SYNCLIENT_MODE_RANDOMSLEEP 61 #define SYNCLIENT_MODE_SLEEP 62 #define SYNCLIENT_MODE_DUMP 63 #define SYNCLIENT_MODE_LOOKUPHASH 70 #define SYNCLIENT_MODE_LOOKUPINO 71 #define SYNCLIENT_MODE_TRUNCATE 200 #define SYNCLIENT_MODE_FOO 100 #define SYNCLIENT_MODE_THRASHLINKS 101 #define SYNCLIENT_MODE_IMPORTFIND 300 #define SYNCLIENT_MODE_CHUNK 400 #define SYNCLIENT_MODE_MKSNAP 1000 #define SYNCLIENT_MODE_RMSNAP 1001 #define SYNCLIENT_MODE_MKSNAPFILE 1002 void parse_syn_options(std::vector<const char*>& args); extern int num_client; class SyntheticClient { StandaloneClient *client; int whoami; pthread_t thread_id; Distribution op_dist; void init_op_dist(); int get_op(); filepath cwd; std::map<std::string, struct stat*> contents; std::set<std::string> subdirs; bool did_readdir; std::set<int> open_files; void up(); void clear_dir() { contents.clear(); subdirs.clear(); did_readdir = false; } int get_random_fh() { int r = rand() % open_files.size(); std::set<int>::iterator it = open_files.begin(); while (r--) ++it; return *it; } filepath n1; const char *get_random_subdir() { ceph_assert(!subdirs.empty()); int r = ((rand() % subdirs.size()) + (rand() % subdirs.size())) / 2; // non-uniform distn std::set<std::string>::iterator it = subdirs.begin(); while (r--) ++it; n1 = cwd; n1.push_dentry( *it ); return n1.get_path().c_str(); } filepath n2; const char *get_random_sub() { ceph_assert(!contents.empty()); int r = ((rand() % contents.size()) + (rand() % contents.size())) / 2; // non-uniform distn if (cwd.depth() && cwd.last_dentry().length()) r += cwd.last_dentry().c_str()[0]; // slightly permuted r %= contents.size(); std::map<std::string,struct stat*>::iterator it = contents.begin(); while (r--) ++it; n2 = cwd; n2.push_dentry( it->first ); return n2.get_path().c_str(); } filepath sub; char sub_s[50]; const char *make_sub(const char *base) { snprintf(sub_s, sizeof(sub_s), "%s.%d", base, rand() % 100); std::string f = sub_s; sub = cwd; sub.push_dentry(f); return sub.c_str(); } public: SyntheticClient(StandaloneClient *client, int w = -1); int start_thread(); int join_thread(); int run(); bool run_me() { if (run_only >= 0) { if (run_only == client->get_nodeid()) return true; else return false; } return true; } void did_run_me() { run_only = -1; run_until = utime_t(); } // run() will do one of these things: std::list<int> modes; std::list<std::string> sargs; std::list<int> iargs; utime_t run_start; utime_t run_until; client_t run_only; client_t exclude; std::string get_sarg(int seq); int get_iarg() { int i = iargs.front(); iargs.pop_front(); return i; } bool time_to_stop() { utime_t now = ceph_clock_now(); if (0) std::cout << "time_to_stop .. now " << now << " until " << run_until << " start " << run_start << std::endl; if (run_until.sec() && now > run_until) return true; else return false; } std::string compose_path(std::string& prefix, char *rest) { return prefix + rest; } int full_walk(std::string& fromdir); int random_walk(int n); int dump_placement(std::string& fn); int make_dirs(const char *basedir, int dirs, int files, int depth); int stat_dirs(const char *basedir, int dirs, int files, int depth); int read_dirs(const char *basedir, int dirs, int files, int depth); int make_files(int num, int count, int priv, bool more); int link_test(); int create_shared(int num); int open_shared(int num, int count); int rm_file(std::string& fn); int write_file(std::string& fn, int mb, loff_t chunk); int write_fd(int fd, int size, int wrsize); int write_batch(int nfile, int mb, int chunk); int read_file(const std::string& fn, int mb, int chunk, bool ignoreprint=false); int create_objects(int nobj, int osize, int inflight); int object_rw(int nobj, int osize, int wrpc, int overlap, double rskew, double wskew); int read_random(std::string& fn, int mb, int chunk); int read_random_ex(std::string& fn, int mb, int chunk); int overload_osd_0(int n, int sie, int wrsize); int check_first_primary(int fd); int clean_dir(std::string& basedir); int play_trace(Trace& t, std::string& prefix, bool metadata_only=false); void make_dir_mess(const char *basedir, int n); void foo(); int thrash_links(const char *basedir, int dirs, int files, int depth, int n); void import_find(const char *basedir, const char *find, bool writedata); int lookup_hash(inodeno_t ino, inodeno_t dirino, const char *name, const UserPerm& perms); int lookup_ino(inodeno_t ino, const UserPerm& perms); int chunk_file(std::string &filename); void mksnap(const char *base, const char *name, const UserPerm& perms); void rmsnap(const char *base, const char *name, const UserPerm& perms); void mksnapfile(const char *dir); }; #endif
7,239
24.673759
101
h
null
ceph-main/src/client/UserPerm.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) 2016 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_CLIENT_USERPERM_H #define CEPH_CLIENT_USERPERM_H struct UserPerm { private: uid_t m_uid; gid_t m_gid; int gid_count; gid_t *gids; bool alloced_gids; void deep_copy_from(const UserPerm& b) { if (alloced_gids) { delete[] gids; alloced_gids = false; } m_uid = b.m_uid; m_gid = b.m_gid; gid_count = b.gid_count; if (gid_count > 0) { gids = new gid_t[gid_count]; alloced_gids = true; for (int i = 0; i < gid_count; ++i) { gids[i] = b.gids[i]; } } } public: UserPerm() : m_uid(-1), m_gid(-1), gid_count(0), gids(NULL), alloced_gids(false) {} UserPerm(uid_t uid, gid_t gid, int ngids=0, gid_t *gidlist=NULL) : m_uid(uid), m_gid(gid), gid_count(ngids), gids(gidlist), alloced_gids(false) {} UserPerm(const UserPerm& o) : UserPerm() { deep_copy_from(o); } UserPerm(UserPerm && o) { m_uid = o.m_uid; m_gid = o.m_gid; gid_count = o.gid_count; gids = o.gids; alloced_gids = o.alloced_gids; o.gids = NULL; o.gid_count = 0; } ~UserPerm() { if (alloced_gids) delete[] gids; } UserPerm& operator=(const UserPerm& o) { deep_copy_from(o); return *this; } uid_t uid() const { return m_uid != (uid_t)-1 ? m_uid : ::geteuid(); } gid_t gid() const { return m_gid != (gid_t)-1 ? m_gid : ::getegid(); } bool gid_in_groups(gid_t id) const { if (id == gid()) return true; for (int i = 0; i < gid_count; ++i) { if (id == gids[i]) return true; } return false; } int get_gids(const gid_t **_gids) const { *_gids = gids; return gid_count; } void init_gids(gid_t* _gids, int count) { gids = _gids; gid_count = count; alloced_gids = true; } void shallow_copy(const UserPerm& o) { m_uid = o.m_uid; m_gid = o.m_gid; gid_count = o.gid_count; gids = o.gids; alloced_gids = false; } }; #endif
2,311
23.595745
78
h
null
ceph-main/src/client/barrier.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * * Copyright (C) 2012 CohortFS, 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. * */ #ifndef BARRIER_H #define BARRIER_H #include "include/types.h" #include <boost/intrusive/list.hpp> #define BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS #include <boost/icl/interval_set.hpp> #include "common/ceph_mutex.h" class Client; typedef boost::icl::interval<uint64_t>::type barrier_interval; /* * we keep count of uncommitted writes on the inode, so that * ll_commit_blocks can do the right thing. * * This is just a hacked copy of Ceph's sync callback. */ enum CBlockSync_State { CBlockSync_State_None, /* initial state */ CBlockSync_State_Unclaimed, /* outstanding write */ CBlockSync_State_Committing, /* commit in progress */ CBlockSync_State_Completed, }; class BarrierContext; class C_Block_Sync; typedef boost::intrusive::list< C_Block_Sync, boost::intrusive::member_hook< C_Block_Sync, boost::intrusive::list_member_hook<>, &C_Block_Sync::intervals_hook > > BlockSyncList; class Barrier { private: ceph::condition_variable cond; boost::icl::interval_set<uint64_t> span; BlockSyncList write_list; public: boost::intrusive::list_member_hook<> active_commits_hook; Barrier(); ~Barrier(); friend class BarrierContext; }; typedef boost::intrusive::list< Barrier, boost::intrusive::member_hook< Barrier, boost::intrusive::list_member_hook<>, &Barrier::active_commits_hook > > BarrierList; class BarrierContext { private: Client *cl; uint64_t ino; ceph::mutex lock = ceph::make_mutex("BarrierContext"); // writes not claimed by a commit BlockSyncList outstanding_writes; // commits in progress, with their claimed writes BarrierList active_commits; public: BarrierContext(Client *c, uint64_t ino); void write_nobarrier(C_Block_Sync &cbs); void write_barrier(C_Block_Sync &cbs); void commit_barrier(barrier_interval &civ); void complete(C_Block_Sync &cbs); ~BarrierContext(); }; #endif
2,273
21.74
70
h
null
ceph-main/src/client/fuse_ll.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) 2004-2006 Sage Weil <sage@newdream.net> * * 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. * */ class CephFuse { public: CephFuse(Client *c, int fd); ~CephFuse(); int init(int argc, const char *argv[]); int start(); int mount(); int loop(); void finalize(); class Handle; std::string get_mount_point() const; private: CephFuse::Handle *_handle; };
701
23.206897
71
h
null
ceph-main/src/client/ioctl.h
#ifndef FS_CEPH_IOCTL_H #define FS_CEPH_IOCTL_H #include "include/int_types.h" #if defined(__linux__) #include <linux/ioctl.h> #include <linux/types.h> #elif defined(__APPLE__) || defined(__FreeBSD__) #include <sys/ioctl.h> #include <sys/types.h> #endif #define CEPH_IOCTL_MAGIC 0x97 /* just use u64 to align sanely on all archs */ struct ceph_ioctl_layout { __u64 stripe_unit, stripe_count, object_size; __u64 data_pool; __s64 unused; }; #define CEPH_IOC_GET_LAYOUT _IOR(CEPH_IOCTL_MAGIC, 1, \ struct ceph_ioctl_layout) #define CEPH_IOC_SET_LAYOUT _IOW(CEPH_IOCTL_MAGIC, 2, \ struct ceph_ioctl_layout) #define CEPH_IOC_SET_LAYOUT_POLICY _IOW(CEPH_IOCTL_MAGIC, 5, \ struct ceph_ioctl_layout) /* * Extract identity, address of the OSD and object storing a given * file offset. */ struct ceph_ioctl_dataloc { __u64 file_offset; /* in+out: file offset */ __u64 object_offset; /* out: offset in object */ __u64 object_no; /* out: object # */ __u64 object_size; /* out: object size */ char object_name[64]; /* out: object name */ __u64 block_offset; /* out: offset in block */ __u64 block_size; /* out: block length */ __s64 osd; /* out: osd # */ struct sockaddr_storage osd_addr; /* out: osd address */ }; #define CEPH_IOC_GET_DATALOC _IOWR(CEPH_IOCTL_MAGIC, 3, \ struct ceph_ioctl_dataloc) #define CEPH_IOC_LAZYIO _IO(CEPH_IOCTL_MAGIC, 4) #endif
1,482
27.519231
66
h
null
ceph-main/src/client/posix_acl.h
#ifndef CEPH_POSIX_ACL #define CEPH_POSIX_ACL #define ACL_EA_VERSION 0x0002 #define ACL_USER_OBJ 0x01 #define ACL_USER 0x02 #define ACL_GROUP_OBJ 0x04 #define ACL_GROUP 0x08 #define ACL_MASK 0x10 #define ACL_OTHER 0x20 #define ACL_EA_ACCESS "system.posix_acl_access" #define ACL_EA_DEFAULT "system.posix_acl_default" typedef struct { ceph_le16 e_tag; ceph_le16 e_perm; ceph_le32 e_id; } acl_ea_entry; typedef struct { ceph_le32 a_version; acl_ea_entry a_entries[0]; } acl_ea_header; class UserPerm; int posix_acl_check(const void *xattr, size_t size); int posix_acl_equiv_mode(const void *xattr, size_t size, mode_t *mode_p); int posix_acl_inherit_mode(bufferptr& acl, mode_t *mode_p); int posix_acl_access_chmod(bufferptr& acl, mode_t mode); int posix_acl_permits(const bufferptr& acl, uid_t i_uid, gid_t i_gid, const UserPerm& groups, unsigned want); #endif
1,001
26.833333
73
h
null
ceph-main/src/client/test_ioctls.c
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <sys/socket.h> #include <netdb.h> #include "ioctl.h" char new_file_name[PATH_MAX]; int main(int argc, char **argv) { char *fn; int fd, err; struct ceph_ioctl_layout l; struct ceph_ioctl_dataloc dl; if (argc < 3) { printf("usage: ceph_test_ioctls <filename> <offset>\n"); return 1; } fn = argv[1]; fd = open(fn, O_CREAT|O_RDWR, 0644); if (fd < 0) { perror("couldn't open file"); return 1; } /* get layout */ err = ioctl(fd, CEPH_IOC_GET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_GET_LAYOUT error"); return 1; } printf("layout:\n stripe_unit %lld\n stripe_count %lld\n object_size %lld\n data_pool %lld\n", (long long)l.stripe_unit, (long long)l.stripe_count, (long long)l.object_size, (long long)l.data_pool); /* set layout */ l.stripe_unit = 1048576; l.stripe_count = 2; err = ioctl(fd, CEPH_IOC_SET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_SET_LAYOUT error"); return 1; } printf("set layout, writing to file\n"); printf("file %s\n", fn); /* get layout again */ err = ioctl(fd, CEPH_IOC_GET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_GET_LAYOUT error"); return 1; } printf("layout:\n stripe_unit %lld\n stripe_count %lld\n object_size %lld\n data_pool %lld\n", (long long)l.stripe_unit, (long long)l.stripe_count, (long long)l.object_size, (long long)l.data_pool); /* dataloc */ dl.file_offset = atoll(argv[2]); err = ioctl(fd, CEPH_IOC_GET_DATALOC, (unsigned long)&dl); if (err < 0) { perror("ioctl IOC_GET_DATALOC error"); return 1; } printf("dataloc:\n"); printf(" file_offset %lld (of object start)\n", (long long)dl.file_offset); printf(" object '%s'\n object_offset %lld\n object_size %lld object_no %lld\n", dl.object_name, (long long)dl.object_offset, (long long)dl.object_size, (long long)dl.object_no); printf(" block_offset %lld\n block_size %lld\n", (long long)dl.block_offset, (long long)dl.block_size); char buf[80]; getnameinfo((struct sockaddr *)&dl.osd_addr, sizeof(dl.osd_addr), buf, sizeof(buf), 0, 0, NI_NUMERICHOST); printf(" osd%lld %s\n", (long long)dl.osd, buf); if (argc < 4) return 0; /* set dir default layout */ printf("testing dir policy setting\n"); fd = open(argv[3], O_RDONLY); if (fd < 0) { perror("couldn't open dir"); return 1; } l.object_size = 1048576; l.stripe_count = 1; err = ioctl(fd, CEPH_IOC_SET_LAYOUT_POLICY, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_SET_LAYOUT_POLICY error"); return 1; } printf("set layout, creating file\n"); snprintf(new_file_name, sizeof(new_file_name), "%s/testfile", argv[3]); fd = open(new_file_name, O_CREAT | O_RDWR, 0644); if (fd < 0) { perror("couldn't open file"); return 1; } err = ioctl(fd, CEPH_IOC_GET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_GET_LAYOUT error"); return 1; } printf("layout:\n stripe_unit %lld\n stripe_count %lld\n object_size %lld\n data_pool %lld\n", (long long)l.stripe_unit, (long long)l.stripe_count, (long long)l.object_size, (long long)l.data_pool); return 0; }
3,691
29.01626
118
c
null
ceph-main/src/client/hypertable/CephBroker.h
/** -*- C++ -*- * Copyright (C) 2009-2011 New Dream Network * * This file is part of Hypertable. * * Hypertable is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Hypertable 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Hypertable. If not, see <http://www.gnu.org/licenses/> * * Authors: * Gregory Farnum <gfarnum@gmail.com> * Colin McCabe <cmccabe@alumni.cmu.edu> */ #ifndef HYPERTABLE_CEPHBROKER_H #define HYPERTABLE_CEPHBROKER_H extern "C" { #include <unistd.h> } #include <atomic> #include "Common/String.h" #include "Common/Properties.h" #include "DfsBroker/Lib/Broker.h" #include <cephfs/libcephfs.h> namespace Hypertable { using namespace DfsBroker; /** * */ class OpenFileDataCeph : public OpenFileData { public: OpenFileDataCeph(struct ceph_mount_info *cmount_, const String& fname, int _fd, int _flags); virtual ~OpenFileDataCeph(); struct ceph_mount_info *cmount; int fd; int flags; String filename; }; /** * */ class OpenFileDataCephPtr : public OpenFileDataPtr { public: OpenFileDataCephPtr() : OpenFileDataPtr() { } explicit OpenFileDataCephPtr(OpenFileDataCeph *ofdl) : OpenFileDataPtr(ofdl, true) { } OpenFileDataCeph *operator->() const { return static_cast<OpenFileDataCeph *>(get()); } }; /** * */ class CephBroker : public DfsBroker::Broker { public: explicit CephBroker(PropertiesPtr& cfg); virtual ~CephBroker(); virtual void open(ResponseCallbackOpen *cb, const char *fname, uint32_t flags, uint32_t bufsz); virtual void create(ResponseCallbackOpen *cb, const char *fname, uint32_t flags, int32_t bufsz, int16_t replication, int64_t blksz); virtual void close(ResponseCallback *cb, uint32_t fd); virtual void read(ResponseCallbackRead *cb, uint32_t fd, uint32_t amount); virtual void append(ResponseCallbackAppend *cb, uint32_t fd, uint32_t amount, const void *data, bool sync); virtual void seek(ResponseCallback *cb, uint32_t fd, uint64_t offset); virtual void remove(ResponseCallback *cb, const char *fname); virtual void length(ResponseCallbackLength *cb, const char *fname, bool); virtual void pread(ResponseCallbackRead *cb, uint32_t fd, uint64_t offset, uint32_t amount, bool); virtual void mkdirs(ResponseCallback *cb, const char *dname); virtual void rmdir(ResponseCallback *cb, const char *dname); virtual void flush(ResponseCallback *cb, uint32_t fd); virtual void status(ResponseCallback *cb); virtual void shutdown(ResponseCallback *cb); virtual void readdir(ResponseCallbackReaddir *cb, const char *dname); virtual void exists(ResponseCallbackExists *cb, const char *fname); virtual void rename(ResponseCallback *cb, const char *src, const char *dst); virtual void debug(ResponseCallback *, int32_t command, StaticBuffer &serialized_parameters); private: struct ceph_mount_info *cmount; static std::atomic<int> ms_next_fd; virtual void report_error(ResponseCallback *cb, int error); void make_abs_path(const char *fname, String& abs) { if (fname[0] == '/') abs = fname; else abs = m_root_dir + "/" + fname; } int rmdir_recursive(const char *directory); bool m_verbose; String m_root_dir; }; } #endif //HYPERTABLE_CEPH_BROKER_H
3,854
31.669492
91
h
null
ceph-main/src/cls/2pc_queue/cls_2pc_queue_const.h
#pragma once #define TPC_QUEUE_CLASS "2pc_queue" #define TPC_QUEUE_INIT "2pc_queue_init" #define TPC_QUEUE_GET_CAPACITY "2pc_queue_get_capacity" #define TPC_QUEUE_GET_TOPIC_STATS "2pc_queue_get_topic_stats" #define TPC_QUEUE_RESERVE "2pc_queue_reserve" #define TPC_QUEUE_COMMIT "2pc_queue_commit" #define TPC_QUEUE_ABORT "2pc_queue_abort" #define TPC_QUEUE_LIST_RESERVATIONS "2pc_queue_list_reservations" #define TPC_QUEUE_LIST_ENTRIES "2pc_queue_list_entries" #define TPC_QUEUE_REMOVE_ENTRIES "2pc_queue_remove_entries" #define TPC_QUEUE_EXPIRE_RESERVATIONS "2pc_queue_expire_reservations"
594
36.1875
69
h
null
ceph-main/src/cls/2pc_queue/cls_2pc_queue_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "include/types.h" #include "cls_2pc_queue_types.h" struct cls_2pc_queue_reserve_op { uint64_t size; uint32_t entries; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(size, bl); encode(entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(size, bl); decode(entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_queue_reserve_op) struct cls_2pc_queue_reserve_ret { cls_2pc_reservation::id_t id; // allocated reservation id void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_queue_reserve_ret) struct cls_2pc_queue_commit_op { cls_2pc_reservation::id_t id; // reservation to commit std::vector<ceph::buffer::list> bl_data_vec; // the data to enqueue void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(bl_data_vec, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); decode(bl_data_vec, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_queue_commit_op) struct cls_2pc_queue_abort_op { cls_2pc_reservation::id_t id; // reservation to abort void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_queue_abort_op) struct cls_2pc_queue_expire_op { // any reservation older than this time should expire ceph::coarse_real_time stale_time; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(stale_time, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(stale_time, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_queue_expire_op) struct cls_2pc_queue_reservations_ret { cls_2pc_reservations reservations; // reservation list (keyed by id) void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(reservations, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(reservations, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_queue_reservations_ret)
2,782
22.584746
70
h
null
ceph-main/src/cls/2pc_queue/cls_2pc_queue_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "include/types.h" struct cls_2pc_reservation { using id_t = uint32_t; inline static const id_t NO_ID{0}; uint64_t size; // how much size to reserve (bytes) ceph::coarse_real_time timestamp; // when the reservation was done (used for cleaning stale reservations) uint32_t entries; // how many entries are reserved cls_2pc_reservation(uint64_t _size, ceph::coarse_real_time _timestamp, uint32_t _entries) : size(_size), timestamp(_timestamp), entries(_entries) {} cls_2pc_reservation() = default; void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(size, bl); encode(timestamp, bl); encode(entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(size, bl); decode(timestamp, bl); if (struct_v >= 2) { decode(entries, bl); } DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_reservation) using cls_2pc_reservations = ceph::unordered_map<cls_2pc_reservation::id_t, cls_2pc_reservation>; struct cls_2pc_urgent_data { uint64_t reserved_size{0}; // pending reservations size in bytes cls_2pc_reservation::id_t last_id{cls_2pc_reservation::NO_ID}; // last allocated id cls_2pc_reservations reservations; // reservation list (keyed by id) bool has_xattrs{false}; uint32_t committed_entries{0}; // how many entries have been committed so far void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(reserved_size, bl); encode(last_id, bl); encode(reservations, bl); encode(has_xattrs, bl); encode(committed_entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(reserved_size, bl); decode(last_id, bl); decode(reservations, bl); decode(has_xattrs, bl); if (struct_v >= 2) { decode(committed_entries, bl); } DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_2pc_urgent_data)
2,160
28.60274
108
h
null
ceph-main/src/cls/cas/cls_cas_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_CAS_CLIENT_H #define CEPH_CLS_CAS_CLIENT_H #include "include/types.h" #include "include/rados/librados_fwd.hpp" #include "common/hobject.h" // // basic methods // /// create a chunk, or get additional reference if it already exists void cls_cas_chunk_create_or_get_ref( librados::ObjectWriteOperation& op, const hobject_t& soid, const bufferlist& data, bool verify=false); /// get ref on existing chunk void cls_cas_chunk_get_ref( librados::ObjectWriteOperation& op, const hobject_t& soid); /// drop reference on existing chunk void cls_cas_chunk_put_ref( librados::ObjectWriteOperation& op, const hobject_t& soid); // // advanced (used for scrub, repair, etc.) // /// check if a tiered rados object links to a chunk int cls_cas_references_chunk( librados::IoCtx& io_ctx, const std::string& oid, const std::string& chunk_oid); #endif
981
21.318182
70
h
null
ceph-main/src/cls/cas/cls_cas_internal.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <string> #include "boost/variant.hpp" #include "include/stringify.h" #include "common/Formatter.h" #include "common/hobject.h" #define CHUNK_REFCOUNT_ATTR "chunk_refs" // public type struct chunk_refs_t { enum { TYPE_BY_OBJECT = 1, TYPE_BY_HASH = 2, TYPE_BY_PARTIAL = 3, TYPE_BY_POOL = 4, TYPE_COUNT = 5, }; static const char *type_name(int t) { switch (t) { case TYPE_BY_OBJECT: return "by_object"; case TYPE_BY_HASH: return "by_hash"; case TYPE_BY_POOL: return "by_pool"; case TYPE_COUNT: return "count"; default: return "???"; } } struct refs_t { virtual ~refs_t() {} virtual uint8_t get_type() const = 0; virtual bool empty() const = 0; virtual uint64_t count() const = 0; virtual void get(const hobject_t& o) = 0; virtual bool put(const hobject_t& o) = 0; virtual void dump(Formatter *f) const = 0; virtual std::string describe_encoding() const { return type_name(get_type()); } }; std::unique_ptr<refs_t> r; chunk_refs_t() { clear(); } chunk_refs_t(const chunk_refs_t& other); chunk_refs_t& operator=(const chunk_refs_t&); void clear(); int get_type() const { return r->get_type(); } std::string describe_encoding() const { return r->describe_encoding(); } bool empty() const { return r->empty(); } uint64_t count() const { return r->count(); } void get(const hobject_t& o) { r->get(o); } bool put(const hobject_t& o) { bool ret = r->put(o); if (r->get_type() != TYPE_BY_OBJECT && r->count() == 0) { clear(); // reset to full resolution, yay } return ret; } void _encode_r(bufferlist& bl) const; void _encode_final(bufferlist& bl, bufferlist& t) const; void dynamic_encode(ceph::buffer::list& bl, size_t max); void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& p); void dump(Formatter *f) const { r->dump(f); } static void generate_test_instances(std::list<chunk_refs_t*>& ls) { ls.push_back(new chunk_refs_t()); } }; WRITE_CLASS_ENCODER(chunk_refs_t) // encoding specific types // these are internal and should generally not be used directly struct chunk_refs_by_object_t : public chunk_refs_t::refs_t { std::multiset<hobject_t> by_object; uint8_t get_type() const { return chunk_refs_t::TYPE_BY_OBJECT; } bool empty() const override { return by_object.empty(); } uint64_t count() const override { return by_object.size(); } void get(const hobject_t& o) override { by_object.insert(o); } bool put(const hobject_t& o) override { auto p = by_object.find(o); if (p == by_object.end()) { return false; } by_object.erase(p); return true; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(by_object, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(by_object, p); DECODE_FINISH(p); } void dump(Formatter *f) const override { f->dump_string("type", "by_object"); f->dump_unsigned("count", by_object.size()); f->open_array_section("refs"); for (auto& i : by_object) { f->dump_object("ref", i); } f->close_section(); } }; WRITE_CLASS_ENCODER(chunk_refs_by_object_t) struct chunk_refs_by_hash_t : public chunk_refs_t::refs_t { uint64_t total = 0; uint32_t hash_bits = 32; ///< how many bits of mask to encode std::map<std::pair<int64_t,uint32_t>,uint64_t> by_hash; chunk_refs_by_hash_t() {} chunk_refs_by_hash_t(const chunk_refs_by_object_t *o) { total = o->count(); for (auto& i : o->by_object) { by_hash[std::make_pair(i.pool, i.get_hash())]++; } } std::string describe_encoding() const { using namespace std::literals; return "by_hash("s + stringify(hash_bits) + " bits)"; } uint32_t mask() { // with the hobject_t reverse-bitwise sort, the least significant // hash values are actually the most significant, so preserve them // as we lose resolution. return 0xffffffff >> (32 - hash_bits); } bool shrink() { if (hash_bits <= 1) { return false; } hash_bits--; std::map<std::pair<int64_t,uint32_t>,uint64_t> old; old.swap(by_hash); auto m = mask(); for (auto& i : old) { by_hash[std::make_pair(i.first.first, i.first.second & m)] = i.second; } return true; } uint8_t get_type() const { return chunk_refs_t::TYPE_BY_HASH; } bool empty() const override { return by_hash.empty(); } uint64_t count() const override { return total; } void get(const hobject_t& o) override { by_hash[std::make_pair(o.pool, o.get_hash() & mask())]++; ++total; } bool put(const hobject_t& o) override { auto p = by_hash.find(std::make_pair(o.pool, o.get_hash() & mask())); if (p == by_hash.end()) { return false; } if (--p->second == 0) { by_hash.erase(p); } --total; return true; } DENC_HELPERS void bound_encode(size_t& p) const { p += 6 + sizeof(uint64_t) + by_hash.size() * (10 + 10); } void encode(::ceph::buffer::list::contiguous_appender& p) const { DENC_START(1, 1, p); denc_varint(total, p); denc_varint(hash_bits, p); denc_varint(by_hash.size(), p); int hash_bytes = (hash_bits + 7) / 8; for (auto& i : by_hash) { denc_signed_varint(i.first.first, p); // this may write some bytes past where we move cursor too; harmless! *(ceph_le32*)p.get_pos_add(hash_bytes) = i.first.second; denc_varint(i.second, p); } DENC_FINISH(p); } void decode(::ceph::buffer::ptr::const_iterator& p) { DENC_START(1, 1, p); denc_varint(total, p); denc_varint(hash_bits, p); uint64_t n; denc_varint(n, p); int hash_bytes = (hash_bits + 7) / 8; while (n--) { int64_t poolid; ceph_le32 hash; uint64_t count; denc_signed_varint(poolid, p); memcpy(&hash, p.get_pos_add(hash_bytes), hash_bytes); denc_varint(count, p); by_hash[std::make_pair(poolid, (uint32_t)hash)] = count; } DENC_FINISH(p); } void dump(Formatter *f) const override { f->dump_string("type", "by_hash"); f->dump_unsigned("count", total); f->dump_unsigned("hash_bits", hash_bits); f->open_array_section("refs"); for (auto& i : by_hash) { f->open_object_section("hash"); f->dump_int("pool", i.first.first); f->dump_unsigned("hash", i.first.second); f->dump_unsigned("count", i.second); f->close_section(); } f->close_section(); } }; WRITE_CLASS_DENC(chunk_refs_by_hash_t) struct chunk_refs_by_pool_t : public chunk_refs_t::refs_t { uint64_t total = 0; std::map<int64_t,uint64_t> by_pool; chunk_refs_by_pool_t() {} chunk_refs_by_pool_t(const chunk_refs_by_hash_t *o) { total = o->count(); for (auto& i : o->by_hash) { by_pool[i.first.first] += i.second; } } uint8_t get_type() const { return chunk_refs_t::TYPE_BY_POOL; } bool empty() const override { return by_pool.empty(); } uint64_t count() const override { return total; } void get(const hobject_t& o) override { ++by_pool[o.pool]; ++total; } bool put(const hobject_t& o) override { auto p = by_pool.find(o.pool); if (p == by_pool.end()) { return false; } --p->second; if (p->second == 0) { by_pool.erase(p); } --total; return true; } void bound_encode(size_t& p) const { p += 6 + sizeof(uint64_t) + by_pool.size() * (9 + 9); } DENC_HELPERS void encode(::ceph::buffer::list::contiguous_appender& p) const { DENC_START(1, 1, p); denc_varint(total, p); denc_varint(by_pool.size(), p); for (auto& i : by_pool) { denc_signed_varint(i.first, p); denc_varint(i.second, p); } DENC_FINISH(p); } void decode(::ceph::buffer::ptr::const_iterator& p) { DENC_START(1, 1, p); denc_varint(total, p); uint64_t n; denc_varint(n, p); while (n--) { int64_t poolid; uint64_t count; denc_signed_varint(poolid, p); denc_varint(count, p); by_pool[poolid] = count; } DENC_FINISH(p); } void dump(Formatter *f) const override { f->dump_string("type", "by_pool"); f->dump_unsigned("count", total); f->open_array_section("pools"); for (auto& i : by_pool) { f->open_object_section("pool"); f->dump_unsigned("pool_id", i.first); f->dump_unsigned("count", i.second); f->close_section(); } f->close_section(); } }; WRITE_CLASS_DENC(chunk_refs_by_pool_t) struct chunk_refs_count_t : public chunk_refs_t::refs_t { uint64_t total = 0; chunk_refs_count_t() {} chunk_refs_count_t(const refs_t *old) { total = old->count(); } uint8_t get_type() const { return chunk_refs_t::TYPE_COUNT; } bool empty() const override { return total == 0; } uint64_t count() const override { return total; } void get(const hobject_t& o) override { ++total; } bool put(const hobject_t& o) override { if (!total) { return false; } --total; return true; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(total, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(total, p); DECODE_FINISH(p); } void dump(Formatter *f) const override { f->dump_string("type", "count"); f->dump_unsigned("count", total); } }; WRITE_CLASS_ENCODER(chunk_refs_count_t)
9,743
23.857143
76
h
null
ceph-main/src/cls/cas/cls_cas_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_CAS_OPS_H #define CEPH_CLS_CAS_OPS_H #include "include/types.h" #include "common/hobject.h" #include "common/Formatter.h" struct cls_cas_chunk_create_or_get_ref_op { enum { FLAG_VERIFY = 1, // verify content bit-for-bit if chunk already exists }; hobject_t source; uint64_t flags = 0; bufferlist data; cls_cas_chunk_create_or_get_ref_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(source, bl); encode(flags, bl); encode(data, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(source, bl); decode(flags, bl); decode(data, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_object("source", source); f->dump_unsigned("flags", flags); f->dump_unsigned("data_len", data.length()); } static void generate_test_instances(std::list<cls_cas_chunk_create_or_get_ref_op*>& ls) { ls.push_back(new cls_cas_chunk_create_or_get_ref_op()); } }; WRITE_CLASS_ENCODER(cls_cas_chunk_create_or_get_ref_op) struct cls_cas_chunk_get_ref_op { hobject_t source; cls_cas_chunk_get_ref_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(source, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(source, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_object("source", source); } static void generate_test_instances(std::list<cls_cas_chunk_get_ref_op*>& ls) { ls.push_back(new cls_cas_chunk_get_ref_op()); } }; WRITE_CLASS_ENCODER(cls_cas_chunk_get_ref_op) struct cls_cas_chunk_put_ref_op { hobject_t source; cls_cas_chunk_put_ref_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(source, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(source, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_object("source", source); } static void generate_test_instances(std::list<cls_cas_chunk_put_ref_op*>& ls) { ls.push_back(new cls_cas_chunk_put_ref_op()); } }; WRITE_CLASS_ENCODER(cls_cas_chunk_put_ref_op) #endif
2,451
23.039216
91
h
null
ceph-main/src/cls/cephfs/cls_cephfs.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) 2015 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "include/encoding.h" /** * Value class for the xattr we'll use to accumulate * the highest object seen for a given inode */ class ObjCeiling { public: uint64_t id; uint64_t size; ObjCeiling() : id(0), size(0) {} ObjCeiling(uint64_t id_, uint64_t size_) : id(id_), size(size_) {} bool operator >(ObjCeiling const &rhs) const { return id > rhs.id; } void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(size, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &p) { DECODE_START(1, p); decode(id, p); decode(size, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(ObjCeiling) class AccumulateArgs { public: uint64_t obj_index; uint64_t obj_size; int64_t mtime; std::string obj_xattr_name; std::string mtime_xattr_name; std::string obj_size_xattr_name; AccumulateArgs( uint64_t obj_index_, uint64_t obj_size_, time_t mtime_, const std::string &obj_xattr_name_, const std::string &mtime_xattr_name_, const std::string &obj_size_xattr_name_) : obj_index(obj_index_), obj_size(obj_size_), mtime(mtime_), obj_xattr_name(obj_xattr_name_), mtime_xattr_name(mtime_xattr_name_), obj_size_xattr_name(obj_size_xattr_name_) {} AccumulateArgs() : obj_index(0), obj_size(0), mtime(0) {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(obj_xattr_name, bl); encode(mtime_xattr_name, bl); encode(obj_size_xattr_name, bl); encode(obj_index, bl); encode(obj_size, bl); encode(mtime, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(obj_xattr_name, bl); decode(mtime_xattr_name, bl); decode(obj_size_xattr_name, bl); decode(obj_index, bl); decode(obj_size, bl); decode(mtime, bl); DECODE_FINISH(bl); } }; class InodeTagFilterArgs { public: std::string scrub_tag; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(scrub_tag, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(scrub_tag, bl); DECODE_FINISH(bl); } }; class AccumulateResult { public: // Index of the highest-indexed object seen uint64_t ceiling_obj_index; // Size of the highest-index object seen uint64_t ceiling_obj_size; // Largest object seen uint64_t max_obj_size; // Non-default object pool id seen int64_t obj_pool_id; // Highest mtime seen int64_t max_mtime; AccumulateResult() : ceiling_obj_index(0), ceiling_obj_size(0), max_obj_size(0), obj_pool_id(-1), max_mtime(0) {} };
3,249
20.523179
70
h
null
ceph-main/src/cls/cephfs/cls_cephfs_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/rados/librados_fwd.hpp" #include "mds/mdstypes.h" #include "cls_cephfs.h" class AccumulateArgs; class ClsCephFSClient { public: static int accumulate_inode_metadata( librados::IoCtx &ctx, inodeno_t inode_no, const uint64_t obj_index, const uint64_t obj_size, const int64_t obj_pool_id, const time_t mtime); static int fetch_inode_accumulate_result( librados::IoCtx &ctx, const std::string &oid, inode_backtrace_t *backtrace, file_layout_t *layout, std::string *symlink, AccumulateResult *result); static int delete_inode_accumulate_result( librados::IoCtx &ctx, const std::string &oid); static void build_tag_filter( const std::string &scrub_tag, ceph::buffer::list *out_bl); };
907
23.540541
70
h
null
ceph-main/src/cls/cmpomap/client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include <optional> #include "include/rados/librados_fwd.hpp" #include "types.h" namespace cls::cmpomap { /// requests with too many key comparisons will be rejected with -E2BIG static constexpr uint32_t max_keys = 1000; /// process each of the omap value comparisons according to the same rules as /// cmpxattr(), and return -ECANCELED if a comparison is unsuccessful. for /// comparisons with Mode::U64, failure to decode an input value is reported /// as -EINVAL, an empty stored value is compared as 0, and failure to decode /// a stored value is reported as -EIO [[nodiscard]] int cmp_vals(librados::ObjectReadOperation& op, Mode mode, Op comparison, ComparisonMap values, std::optional<ceph::bufferlist> default_value); /// process each of the omap value comparisons according to the same rules as /// cmpxattr(). any key/value pairs that compare successfully are overwritten /// with the corresponding input value. for comparisons with Mode::U64, failure /// to decode an input value is reported as -EINVAL. an empty stored value is /// compared as 0, while decode failure of a stored value is treated as an /// unsuccessful comparison and is not reported as an error [[nodiscard]] int cmp_set_vals(librados::ObjectWriteOperation& writeop, Mode mode, Op comparison, ComparisonMap values, std::optional<ceph::bufferlist> default_value); /// process each of the omap value comparisons according to the same rules as /// cmpxattr(). any key/value pairs that compare successfully are removed. for /// comparisons with Mode::U64, failure to decode an input value is reported as /// -EINVAL. an empty stored value is compared as 0, while decode failure of a /// stored value is treated as an unsuccessful comparison and is not reported /// as an error [[nodiscard]] int cmp_rm_keys(librados::ObjectWriteOperation& writeop, Mode mode, Op comparison, ComparisonMap values); // bufferlist factories for comparison values inline ceph::bufferlist string_buffer(std::string_view value) { ceph::bufferlist bl; bl.append(value); return bl; } inline ceph::bufferlist u64_buffer(uint64_t value) { ceph::bufferlist bl; using ceph::encode; encode(value, bl); return bl; } } // namespace cls::cmpomap
2,780
39.304348
79
h
null
ceph-main/src/cls/cmpomap/ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include "types.h" #include "include/encoding.h" namespace cls::cmpomap { struct cmp_vals_op { Mode mode; Op comparison; ComparisonMap values; std::optional<ceph::bufferlist> default_value; }; inline void encode(const cmp_vals_op& o, ceph::bufferlist& bl, uint64_t f=0) { ENCODE_START(1, 1, bl); encode(o.mode, bl); encode(o.comparison, bl); encode(o.values, bl); encode(o.default_value, bl); ENCODE_FINISH(bl); } inline void decode(cmp_vals_op& o, ceph::bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(o.mode, bl); decode(o.comparison, bl); decode(o.values, bl); decode(o.default_value, bl); DECODE_FINISH(bl); } struct cmp_set_vals_op { Mode mode; Op comparison; ComparisonMap values; std::optional<ceph::bufferlist> default_value; }; inline void encode(const cmp_set_vals_op& o, ceph::bufferlist& bl, uint64_t f=0) { ENCODE_START(1, 1, bl); encode(o.mode, bl); encode(o.comparison, bl); encode(o.values, bl); encode(o.default_value, bl); ENCODE_FINISH(bl); } inline void decode(cmp_set_vals_op& o, ceph::bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(o.mode, bl); decode(o.comparison, bl); decode(o.values, bl); decode(o.default_value, bl); DECODE_FINISH(bl); } struct cmp_rm_keys_op { Mode mode; Op comparison; ComparisonMap values; }; inline void encode(const cmp_rm_keys_op& o, ceph::bufferlist& bl, uint64_t f=0) { ENCODE_START(1, 1, bl); encode(o.mode, bl); encode(o.comparison, bl); encode(o.values, bl); ENCODE_FINISH(bl); } inline void decode(cmp_rm_keys_op& o, ceph::bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(o.mode, bl); decode(o.comparison, bl); decode(o.values, bl); DECODE_FINISH(bl); } } // namespace cls::cmpomap
2,204
20.831683
80
h
null
ceph-main/src/cls/cmpomap/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) 2020 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include <string> #include <boost/container/flat_map.hpp> #include "include/rados.h" // CEPH_OSD_CMPXATTR_* #include "include/encoding.h" namespace cls::cmpomap { /// comparison operand type enum class Mode : uint8_t { String = CEPH_OSD_CMPXATTR_MODE_STRING, U64 = CEPH_OSD_CMPXATTR_MODE_U64, }; /// comparison operation, where the left-hand operand is the input value and /// the right-hand operand is the stored value (or the optional default) enum class Op : uint8_t { EQ = CEPH_OSD_CMPXATTR_OP_EQ, NE = CEPH_OSD_CMPXATTR_OP_NE, GT = CEPH_OSD_CMPXATTR_OP_GT, GTE = CEPH_OSD_CMPXATTR_OP_GTE, LT = CEPH_OSD_CMPXATTR_OP_LT, LTE = CEPH_OSD_CMPXATTR_OP_LTE, }; /// mapping of omap keys to value comparisons using ComparisonMap = boost::container::flat_map<std::string, ceph::bufferlist>; } // namespace cls::cmpomap
1,265
27.133333
80
h
null
ceph-main/src/cls/fifo/cls_fifo_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * Copyright (C) 2019 SUSE LLC * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <cstdint> #include <optional> #include <string> #include <vector> #include "include/buffer.h" #include "include/encoding.h" #include "include/types.h" #include "cls/fifo/cls_fifo_types.h" namespace rados::cls::fifo::op { struct create_meta { std::string id; std::optional<objv> version; struct { std::string name; std::string ns; } pool; std::optional<std::string> oid_prefix; std::uint64_t max_part_size{0}; std::uint64_t max_entry_size{0}; bool exclusive{false}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(version, bl); encode(pool.name, bl); encode(pool.ns, bl); encode(oid_prefix, bl); encode(max_part_size, bl); encode(max_entry_size, bl); encode(exclusive, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); decode(version, bl); decode(pool.name, bl); decode(pool.ns, bl); decode(oid_prefix, bl); decode(max_part_size, bl); decode(max_entry_size, bl); decode(exclusive, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(create_meta) struct get_meta { std::optional<objv> version; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(version, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(version, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(get_meta) struct get_meta_reply { fifo::info info; std::uint32_t part_header_size{0}; /* per entry extra data that is stored */ std::uint32_t part_entry_overhead{0}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(info, bl); encode(part_header_size, bl); encode(part_entry_overhead, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(info, bl); decode(part_header_size, bl); decode(part_entry_overhead, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(get_meta_reply) struct update_meta { objv version; std::optional<std::uint64_t> tail_part_num; std::optional<std::uint64_t> head_part_num; std::optional<std::uint64_t> min_push_part_num; std::optional<std::uint64_t> max_push_part_num; std::vector<journal_entry> journal_entries_add; std::vector<journal_entry> journal_entries_rm; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(version, bl); encode(tail_part_num, bl); encode(head_part_num, bl); encode(min_push_part_num, bl); encode(max_push_part_num, bl); encode(journal_entries_add, bl); encode(journal_entries_rm, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(version, bl); decode(tail_part_num, bl); decode(head_part_num, bl); decode(min_push_part_num, bl); decode(max_push_part_num, bl); decode(journal_entries_add, bl); decode(journal_entries_rm, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(update_meta) struct init_part { data_params params; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); std::string tag; encode(tag, bl); encode(params, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); std::string tag; decode(tag, bl); decode(params, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(init_part) struct push_part { std::deque<ceph::buffer::list> data_bufs; std::uint64_t total_len{0}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); std::string tag; encode(tag, bl); encode(data_bufs, bl); encode(total_len, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); std::string tag; decode(tag, bl); decode(data_bufs, bl); decode(total_len, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(push_part) struct trim_part { std::uint64_t ofs{0}; bool exclusive = false; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); std::optional<std::string> tag; encode(tag, bl); encode(ofs, bl); encode(exclusive, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); std::optional<std::string> tag; decode(tag, bl); decode(ofs, bl); decode(exclusive, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(trim_part) struct list_part { std::uint64_t ofs{0}; int max_entries{100}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); std::optional<std::string> tag; encode(tag, bl); encode(ofs, bl); encode(max_entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); std::optional<std::string> tag; decode(tag, bl); decode(ofs, bl); decode(max_entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(list_part) inline constexpr int MAX_LIST_ENTRIES = 512; struct list_part_reply { std::vector<part_list_entry> entries; bool more{false}; bool full_part{false}; /* whether part is full or still can be written to. A non full part is by definition head part */ void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); std::string tag; encode(tag, bl); encode(entries, bl); encode(more, bl); encode(full_part, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); std::string tag; decode(tag, bl); decode(entries, bl); decode(more, bl); decode(full_part, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(list_part_reply) struct get_part_info { void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(get_part_info) struct get_part_info_reply { part_header header; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(header, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(header, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(get_part_info_reply) inline constexpr auto CLASS = "fifo"; inline constexpr auto CREATE_META = "create_meta"; inline constexpr auto GET_META = "get_meta"; inline constexpr auto UPDATE_META = "update_meta"; inline constexpr auto INIT_PART = "init_part"; inline constexpr auto PUSH_PART = "push_part"; inline constexpr auto TRIM_PART = "trim_part"; inline constexpr auto LIST_PART = "part_list"; inline constexpr auto GET_PART_INFO = "get_part_info"; } // namespace rados::cls::fifo::op
7,461
22.916667
76
h
null
ceph-main/src/cls/fifo/cls_fifo_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <algorithm> #include <cstdint> #include <map> #include <optional> #include <ostream> #include <string> #include <vector> #include <boost/container/flat_set.hpp> #include <fmt/format.h> #if FMT_VERSION >= 90000 #include <fmt/ostream.h> #endif #include "include/buffer.h" #include "include/encoding.h" #include "include/types.h" #include "common/ceph_time.h" class JSONObj; namespace rados::cls::fifo { struct objv { std::string instance; std::uint64_t ver{0}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(instance, bl); encode(ver, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(instance, bl); decode(ver, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); bool operator ==(const objv& rhs) const { return (instance == rhs.instance && ver == rhs.ver); } bool operator !=(const objv& rhs) const { return (instance != rhs.instance || ver != rhs.ver); } bool same_or_later(const objv& rhs) const { return (instance == rhs.instance && ver >= rhs.ver); } bool empty() const { return instance.empty(); } std::string to_str() const { return fmt::format("{}{{{}}}", instance, ver); } }; WRITE_CLASS_ENCODER(objv) inline std::ostream& operator <<(std::ostream& os, const objv& objv) { return os << objv.to_str(); } struct data_params { std::uint64_t max_part_size{0}; std::uint64_t max_entry_size{0}; std::uint64_t full_size_threshold{0}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(max_part_size, bl); encode(max_entry_size, bl); encode(full_size_threshold, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(max_part_size, bl); decode(max_entry_size, bl); decode(full_size_threshold, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); auto operator <=>(const data_params&) const = default; }; WRITE_CLASS_ENCODER(data_params) inline std::ostream& operator <<(std::ostream& m, const data_params& d) { return m << "max_part_size: " << d.max_part_size << ", " << "max_entry_size: " << d.max_entry_size << ", " << "full_size_threshold: " << d.full_size_threshold; } struct journal_entry { enum class Op { unknown = -1, create = 1, set_head = 2, remove = 3, } op{Op::unknown}; std::int64_t part_num{-1}; bool valid() const { using enum Op; switch (op) { case create: [[fallthrough]]; case set_head: [[fallthrough]]; case remove: return part_num >= 0; default: return false; } } journal_entry() = default; journal_entry(Op op, std::int64_t part_num) : op(op), part_num(part_num) {} void encode(ceph::buffer::list& bl) const { ceph_assert(valid()); ENCODE_START(1, 1, bl); encode((int)op, bl); encode(part_num, bl); std::string part_tag; encode(part_tag, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); int i; decode(i, bl); op = static_cast<Op>(i); decode(part_num, bl); std::string part_tag; decode(part_tag, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const; auto operator <=>(const journal_entry&) const = default; }; WRITE_CLASS_ENCODER(journal_entry) inline std::ostream& operator <<(std::ostream& m, const journal_entry::Op& o) { switch (o) { case journal_entry::Op::unknown: return m << "Op::unknown"; case journal_entry::Op::create: return m << "Op::create"; case journal_entry::Op::set_head: return m << "Op::set_head"; case journal_entry::Op::remove: return m << "Op::remove"; } return m << "Bad value: " << static_cast<int>(o); } inline std::ostream& operator <<(std::ostream& m, const journal_entry& j) { return m << "op: " << j.op << ", " << "part_num: " << j.part_num; } // This is actually a useful builder, since otherwise we end up with // four uint64_ts in a row and only care about a subset at a time. class update { std::optional<std::int64_t> tail_part_num_; std::optional<std::int64_t> head_part_num_; std::optional<std::int64_t> min_push_part_num_; std::optional<std::int64_t> max_push_part_num_; std::vector<fifo::journal_entry> journal_entries_add_; std::vector<fifo::journal_entry> journal_entries_rm_; public: update&& tail_part_num(std::optional<std::int64_t> num) noexcept { tail_part_num_ = num; return std::move(*this); } auto tail_part_num() const noexcept { return tail_part_num_; } update&& head_part_num(std::optional<std::int64_t> num) noexcept { head_part_num_ = num; return std::move(*this); } auto head_part_num() const noexcept { return head_part_num_; } update&& min_push_part_num(std::optional<std::int64_t> num) noexcept { min_push_part_num_ = num; return std::move(*this); } auto min_push_part_num() const noexcept { return min_push_part_num_; } update&& max_push_part_num(std::optional<std::int64_t> num) noexcept { max_push_part_num_ = num; return std::move(*this); } auto max_push_part_num() const noexcept { return max_push_part_num_; } update&& journal_entry_add(fifo::journal_entry entry) { journal_entries_add_.push_back(std::move(entry)); return std::move(*this); } update&& journal_entries_add( std::optional<std::vector<fifo::journal_entry>>&& entries) { if (entries) { journal_entries_add_ = std::move(*entries); } else { journal_entries_add_.clear(); } return std::move(*this); } const auto& journal_entries_add() const & noexcept { return journal_entries_add_; } auto&& journal_entries_add() && noexcept { return std::move(journal_entries_add_); } update&& journal_entry_rm(fifo::journal_entry entry) { journal_entries_rm_.push_back(std::move(entry)); return std::move(*this); } update&& journal_entries_rm( std::optional<std::vector<fifo::journal_entry>>&& entries) { if (entries) { journal_entries_rm_ = std::move(*entries); } else { journal_entries_rm_.clear(); } return std::move(*this); } const auto& journal_entries_rm() const & noexcept { return journal_entries_rm_; } auto&& journal_entries_rm() && noexcept { return std::move(journal_entries_rm_); } friend std::ostream& operator <<(std::ostream& m, const update& u); }; inline std::ostream& operator <<(std::ostream& m, const update& u) { bool prev = false; if (u.tail_part_num_) { m << "tail_part_num: " << *u.tail_part_num_; prev = true; } if (u.head_part_num_) { if (prev) m << ", "; m << "head_part_num: " << *u.head_part_num_; prev = true; } if (u.min_push_part_num_) { if (prev) m << ", "; m << "min_push_part_num: " << *u.min_push_part_num_; prev = true; } if (u.max_push_part_num_) { if (prev) m << ", "; m << "max_push_part_num: " << *u.max_push_part_num_; prev = true; } if (!u.journal_entries_add_.empty()) { if (prev) m << ", "; m << "journal_entries_add: {" << u.journal_entries_add_ << "}"; prev = true; } if (!u.journal_entries_rm_.empty()) { if (prev) m << ", "; m << "journal_entries_rm: {" << u.journal_entries_rm_ << "}"; prev = true; } if (!prev) m << "(none)"; return m; } struct info { std::string id; objv version; std::string oid_prefix; data_params params; std::int64_t tail_part_num{0}; std::int64_t head_part_num{-1}; std::int64_t min_push_part_num{0}; std::int64_t max_push_part_num{-1}; boost::container::flat_set<journal_entry> journal; static_assert(journal_entry::Op::create < journal_entry::Op::set_head); // So we can get rid of the multimap without breaking compatibility void encode_journal(bufferlist& bl) const { using ceph::encode; assert(journal.size() <= std::numeric_limits<uint32_t>::max()); uint32_t n = static_cast<uint32_t>(journal.size()); encode(n, bl); for (const auto& entry : journal) { encode(entry.part_num, bl); encode(entry, bl); } } void decode_journal( bufferlist::const_iterator& p) { using enum journal_entry::Op; using ceph::decode; uint32_t n; decode(n, p); journal.clear(); while (n--) { decltype(journal_entry::part_num) dummy; decode(dummy, p); journal_entry e; decode(e, p); if (!e.valid()) { throw ceph::buffer::malformed_input(); } else { journal.insert(std::move(e)); } } } bool need_new_head() const { return (head_part_num < min_push_part_num); } bool need_new_part() const { return (max_push_part_num < min_push_part_num); } void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(version, bl); encode(oid_prefix, bl); encode(params, bl); encode(tail_part_num, bl); encode(head_part_num, bl); encode(min_push_part_num, bl); encode(max_push_part_num, bl); std::string head_tag; std::map<int64_t, std::string> tags; encode(tags, bl); encode(head_tag, bl); encode_journal(bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(id, bl); decode(version, bl); decode(oid_prefix, bl); decode(params, bl); decode(tail_part_num, bl); decode(head_part_num, bl); decode(min_push_part_num, bl); decode(max_push_part_num, bl); std::string head_tag; std::map<int64_t, std::string> tags; decode(tags, bl); decode(head_tag, bl); decode_journal(bl); DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); std::string part_oid(std::int64_t part_num) const { return fmt::format("{}.{}", oid_prefix, part_num); } bool apply_update(const update& update) { bool changed = false; if (update.tail_part_num() && (tail_part_num != *update.tail_part_num())) { tail_part_num = *update.tail_part_num(); changed = true; } if (update.min_push_part_num() && (min_push_part_num != *update.min_push_part_num())) { min_push_part_num = *update.min_push_part_num(); changed = true; } if (update.max_push_part_num() && (max_push_part_num != *update.max_push_part_num())) { max_push_part_num = *update.max_push_part_num(); changed = true; } for (const auto& entry : update.journal_entries_add()) { auto [iter, inserted] = journal.insert(entry); if (inserted) { changed = true; } } for (const auto& entry : update.journal_entries_rm()) { auto count = journal.erase(entry); if (count > 0) { changed = true; } } if (update.head_part_num() && (head_part_num != *update.head_part_num())) { head_part_num = *update.head_part_num(); changed = true; } if (changed) { ++version.ver; } return changed; } }; WRITE_CLASS_ENCODER(info) inline std::ostream& operator <<(std::ostream& m, const info& i) { return m << "id: " << i.id << ", " << "version: " << i.version << ", " << "oid_prefix: " << i.oid_prefix << ", " << "params: {" << i.params << "}, " << "tail_part_num: " << i.tail_part_num << ", " << "head_part_num: " << i.head_part_num << ", " << "min_push_part_num: " << i.min_push_part_num << ", " << "max_push_part_num: " << i.max_push_part_num << ", " << "journal: {" << i.journal; } struct part_list_entry { ceph::buffer::list data; std::uint64_t ofs = 0; ceph::real_time mtime; part_list_entry() {} part_list_entry(ceph::buffer::list&& data, uint64_t ofs, ceph::real_time mtime) : data(std::move(data)), ofs(ofs), mtime(mtime) {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(data, bl); encode(ofs, bl); encode(mtime, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(data, bl); decode(ofs, bl); decode(mtime, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(part_list_entry) inline std::ostream& operator <<(std::ostream& m, const part_list_entry& p) { using ceph::operator <<; return m << "data: " << p.data << ", " << "ofs: " << p.ofs << ", " << "mtime: " << p.mtime; } struct part_header { data_params params; std::uint64_t magic{0}; std::uint64_t min_ofs{0}; std::uint64_t last_ofs{0}; std::uint64_t next_ofs{0}; std::uint64_t min_index{0}; std::uint64_t max_index{0}; ceph::real_time max_time; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); std::string tag; encode(tag, bl); encode(params, bl); encode(magic, bl); encode(min_ofs, bl); encode(last_ofs, bl); encode(next_ofs, bl); encode(min_index, bl); encode(max_index, bl); encode(max_time, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); std::string tag; decode(tag, bl); decode(params, bl); decode(magic, bl); decode(min_ofs, bl); decode(last_ofs, bl); decode(next_ofs, bl); decode(min_index, bl); decode(max_index, bl); decode(max_time, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(part_header) inline std::ostream& operator <<(std::ostream& m, const part_header& p) { using ceph::operator <<; return m << "params: {" << p.params << "}, " << "magic: " << p.magic << ", " << "min_ofs: " << p.min_ofs << ", " << "last_ofs: " << p.last_ofs << ", " << "next_ofs: " << p.next_ofs << ", " << "min_index: " << p.min_index << ", " << "max_index: " << p.max_index << ", " << "max_time: " << p.max_time; } } // namespace rados::cls::fifo #if FMT_VERSION >= 90000 template<> struct fmt::formatter<rados::cls::fifo::info> : fmt::ostream_formatter {}; template<> struct fmt::formatter<rados::cls::fifo::part_header> : fmt::ostream_formatter {}; #endif
14,680
25.216071
81
h
null
ceph-main/src/cls/journal/cls_journal_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_JOURNAL_CLIENT_H #define CEPH_CLS_JOURNAL_CLIENT_H #include "include/rados/librados_fwd.hpp" #include "cls/journal/cls_journal_types.h" #include <set> #include <boost/optional.hpp> class Context; namespace cls { namespace journal { namespace client { void create(librados::ObjectWriteOperation *op, uint8_t order, uint8_t splay, int64_t pool_id); int create(librados::IoCtx &ioctx, const std::string &oid, uint8_t order, uint8_t splay, int64_t pool_id); void get_immutable_metadata(librados::IoCtx &ioctx, const std::string &oid, uint8_t *order, uint8_t *splay_width, int64_t *pool_id, Context *on_finish); void get_mutable_metadata(librados::IoCtx &ioctx, const std::string &oid, uint64_t *minimum_set, uint64_t *active_set, std::set<cls::journal::Client> *clients, Context *on_finish); void set_minimum_set(librados::ObjectWriteOperation *op, uint64_t object_set); void set_active_set(librados::ObjectWriteOperation *op, uint64_t object_set); // journal client helpers int get_client(librados::IoCtx &ioctx, const std::string &oid, const std::string &id, cls::journal::Client *client); void get_client_start(librados::ObjectReadOperation *op, const std::string &id); int get_client_finish(bufferlist::const_iterator *iter, cls::journal::Client *client); int client_register(librados::IoCtx &ioctx, const std::string &oid, const std::string &id, const bufferlist &data); void client_register(librados::ObjectWriteOperation *op, const std::string &id, const bufferlist &data); int client_update_data(librados::IoCtx &ioctx, const std::string &oid, const std::string &id, const bufferlist &data); void client_update_data(librados::ObjectWriteOperation *op, const std::string &id, const bufferlist &data); int client_update_state(librados::IoCtx &ioctx, const std::string &oid, const std::string &id, cls::journal::ClientState state); void client_update_state(librados::ObjectWriteOperation *op, const std::string &id, cls::journal::ClientState state); int client_unregister(librados::IoCtx &ioctx, const std::string &oid, const std::string &id); void client_unregister(librados::ObjectWriteOperation *op, const std::string &id); void client_commit(librados::ObjectWriteOperation *op, const std::string &id, const cls::journal::ObjectSetPosition &commit_position); int client_list(librados::IoCtx &ioctx, const std::string &oid, std::set<cls::journal::Client> *clients); void client_list(librados::IoCtx &ioctx, const std::string &oid, std::set<cls::journal::Client> *clients, Context *on_finish); // journal tag helpers int get_next_tag_tid(librados::IoCtx &ioctx, const std::string &oid, uint64_t *tag_tid); void get_next_tag_tid_start(librados::ObjectReadOperation *op); int get_next_tag_tid_finish(bufferlist::const_iterator *iter, uint64_t *tag_tid); int get_tag(librados::IoCtx &ioctx, const std::string &oid, uint64_t tag_tid, cls::journal::Tag *tag); void get_tag_start(librados::ObjectReadOperation *op, uint64_t tag_tid); int get_tag_finish(bufferlist::const_iterator *iter, cls::journal::Tag *tag); int tag_create(librados::IoCtx &ioctx, const std::string &oid, uint64_t tag_tid, uint64_t tag_class, const bufferlist &data); void tag_create(librados::ObjectWriteOperation *op, uint64_t tag_tid, uint64_t tag_class, const bufferlist &data); int tag_list(librados::IoCtx &ioctx, const std::string &oid, const std::string &client_id, boost::optional<uint64_t> tag_class, std::set<cls::journal::Tag> *tags); void tag_list_start(librados::ObjectReadOperation *op, uint64_t start_after_tag_tid, uint64_t max_return, const std::string &client_id, boost::optional<uint64_t> tag_class); int tag_list_finish(bufferlist::const_iterator *iter, std::set<cls::journal::Tag> *tags); // journal entry helpers void guard_append(librados::ObjectWriteOperation *op, uint64_t soft_max_size); void append(librados::ObjectWriteOperation *op, uint64_t soft_max_size, bufferlist &data); } // namespace client } // namespace journal } // namespace cls #endif // CEPH_CLS_JOURNAL_CLIENT_H
4,807
42.709091
80
h
null
ceph-main/src/cls/journal/cls_journal_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_JOURNAL_TYPES_H #define CEPH_CLS_JOURNAL_TYPES_H #include "include/int_types.h" #include "include/buffer_fwd.h" #include "include/encoding.h" #include <iosfwd> #include <list> #include <string> namespace ceph { class Formatter; } namespace cls { namespace journal { static const uint64_t JOURNAL_MAX_RETURN = 256; struct ObjectPosition { uint64_t object_number; uint64_t tag_tid; uint64_t entry_tid; ObjectPosition() : object_number(0), tag_tid(0), entry_tid(0) {} ObjectPosition(uint64_t _object_number, uint64_t _tag_tid, uint64_t _entry_tid) : object_number(_object_number), tag_tid(_tag_tid), entry_tid(_entry_tid) {} inline bool operator==(const ObjectPosition& rhs) const { return (object_number == rhs.object_number && tag_tid == rhs.tag_tid && entry_tid == rhs.entry_tid); } inline bool operator!=(const ObjectPosition& rhs) const { return !(*this == rhs); } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& iter); void dump(ceph::Formatter *f) const; inline bool operator<(const ObjectPosition &rhs) const { if (object_number != rhs.object_number) { return object_number < rhs.object_number; } else if (tag_tid != rhs.tag_tid) { return tag_tid < rhs.tag_tid; } return entry_tid < rhs.entry_tid; } static void generate_test_instances(std::list<ObjectPosition *> &o); }; typedef std::list<ObjectPosition> ObjectPositions; struct ObjectSetPosition { // stored in most-recent -> least recent committed entry order ObjectPositions object_positions; ObjectSetPosition() {} ObjectSetPosition(const ObjectPositions &_object_positions) : object_positions(_object_positions) {} void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& iter); void dump(ceph::Formatter *f) const; inline bool operator==(const ObjectSetPosition &rhs) const { return (object_positions == rhs.object_positions); } static void generate_test_instances(std::list<ObjectSetPosition *> &o); }; enum ClientState { CLIENT_STATE_CONNECTED = 0, CLIENT_STATE_DISCONNECTED = 1 }; struct Client { std::string id; ceph::buffer::list data; ObjectSetPosition commit_position; ClientState state; Client() : state(CLIENT_STATE_CONNECTED) {} Client(const std::string& _id, const ceph::buffer::list &_data, const ObjectSetPosition &_commit_position = ObjectSetPosition(), ClientState _state = CLIENT_STATE_CONNECTED) : id(_id), data(_data), commit_position(_commit_position), state(_state) {} inline bool operator==(const Client &rhs) const { return (id == rhs.id && data.contents_equal(rhs.data) && commit_position == rhs.commit_position && state == rhs.state); } inline bool operator<(const Client &rhs) const { return (id < rhs.id); } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& iter); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<Client *> &o); }; struct Tag { static const uint64_t TAG_CLASS_NEW = static_cast<uint64_t>(-1); uint64_t tid; uint64_t tag_class; ceph::buffer::list data; Tag() : tid(0), tag_class(0) {} Tag(uint64_t tid, uint64_t tag_class, const ceph::buffer::list &data) : tid(tid), tag_class(tag_class), data(data) {} inline bool operator==(const Tag &rhs) const { return (tid == rhs.tid && tag_class == rhs.tag_class && data.contents_equal(rhs.data)); } inline bool operator<(const Tag &rhs) const { return (tid < rhs.tid); } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& iter); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<Tag *> &o); }; WRITE_CLASS_ENCODER(ObjectPosition); WRITE_CLASS_ENCODER(ObjectSetPosition); WRITE_CLASS_ENCODER(Client); WRITE_CLASS_ENCODER(Tag); std::ostream &operator<<(std::ostream &os, const ClientState &state); std::ostream &operator<<(std::ostream &os, const ObjectPosition &object_position); std::ostream &operator<<(std::ostream &os, const ObjectSetPosition &object_set_position); std::ostream &operator<<(std::ostream &os, const Client &client); std::ostream &operator<<(std::ostream &os, const Tag &tag); } // namespace journal } // namespace cls #endif // CEPH_CLS_JOURNAL_TYPES_H
4,645
28.405063
80
h
null
ceph-main/src/cls/lock/cls_lock_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_LOCK_CLIENT_H #define CEPH_CLS_LOCK_CLIENT_H #include <chrono> #include "include/rados/librados_fwd.hpp" #include "cls/lock/cls_lock_types.h" namespace rados { namespace cls { namespace lock { extern void lock(librados::ObjectWriteOperation *rados_op, const std::string& name, ClsLockType type, const std::string& cookie, const std::string& tag, const std::string& description, const utime_t& duration, uint8_t flags); extern int lock(librados::IoCtx *ioctx, const std::string& oid, const std::string& name, ClsLockType type, const std::string& cookie, const std::string& tag, const std::string& description, const utime_t& duration, uint8_t flags); extern void unlock(librados::ObjectWriteOperation *rados_op, const std::string& name, const std::string& cookie); extern int unlock(librados::IoCtx *ioctx, const std::string& oid, const std::string& name, const std::string& cookie); extern int aio_unlock(librados::IoCtx *ioctx, const std::string& oid, const std::string& name, const std::string& cookie, librados::AioCompletion *completion); extern void break_lock(librados::ObjectWriteOperation *op, const std::string& name, const std::string& cookie, const entity_name_t& locker); extern int break_lock(librados::IoCtx *ioctx, const std::string& oid, const std::string& name, const std::string& cookie, const entity_name_t& locker); extern int list_locks(librados::IoCtx *ioctx, const std::string& oid, std::list<std::string> *locks); extern void get_lock_info_start(librados::ObjectReadOperation *rados_op, const std::string& name); extern int get_lock_info_finish(ceph::bufferlist::const_iterator *out, std::map<locker_id_t, locker_info_t> *lockers, ClsLockType *type, std::string *tag); extern int get_lock_info(librados::IoCtx *ioctx, const std::string& oid, const std::string& name, std::map<locker_id_t, locker_info_t> *lockers, ClsLockType *type, std::string *tag); extern void assert_locked(librados::ObjectOperation *rados_op, const std::string& name, ClsLockType type, const std::string& cookie, const std::string& tag); extern void set_cookie(librados::ObjectWriteOperation *rados_op, const std::string& name, ClsLockType type, const std::string& cookie, const std::string& tag, const std::string& new_cookie); class Lock { std::string name; std::string cookie; std::string tag; std::string description; utime_t duration; uint8_t flags; public: Lock(const std::string& _n) : name(_n), flags(0) {} void set_cookie(const std::string& c) { cookie = c; } void set_tag(const std::string& t) { tag = t; } void set_description(const std::string& desc) { description = desc; } void set_duration(const utime_t& e) { duration = e; } void set_duration(const ceph::timespan& d) { duration = utime_t(ceph::real_clock::zero() + d); } void set_may_renew(bool renew) { if (renew) { flags |= LOCK_FLAG_MAY_RENEW; flags &= ~LOCK_FLAG_MUST_RENEW; // if may then not must } else { flags &= ~LOCK_FLAG_MAY_RENEW; } } void set_must_renew(bool renew) { if (renew) { flags |= LOCK_FLAG_MUST_RENEW; flags &= ~LOCK_FLAG_MAY_RENEW; // if must then not may } else { flags &= ~LOCK_FLAG_MUST_RENEW; } } void assert_locked_shared(librados::ObjectOperation *rados_op); void assert_locked_exclusive(librados::ObjectOperation *rados_op); void assert_locked_exclusive_ephemeral(librados::ObjectOperation *rados_op); /* ObjectWriteOperation */ void lock_shared(librados::ObjectWriteOperation *ioctx); void lock_exclusive(librados::ObjectWriteOperation *ioctx); // Be careful when using an exclusive ephemeral lock; it is // intended strictly for cases when a lock object exists // solely for a lock in a given process and the object is no // longer needed when the lock is unlocked or expired, as the // cls back-end will make an effort to delete it. void lock_exclusive_ephemeral(librados::ObjectWriteOperation *ioctx); void unlock(librados::ObjectWriteOperation *ioctx); void break_lock(librados::ObjectWriteOperation *ioctx, const entity_name_t& locker); /* IoCtx */ int lock_shared(librados::IoCtx *ioctx, const std::string& oid); int lock_exclusive(librados::IoCtx *ioctx, const std::string& oid); // NB: see above comment on exclusive ephemeral locks int lock_exclusive_ephemeral(librados::IoCtx *ioctx, const std::string& oid); int unlock(librados::IoCtx *ioctx, const std::string& oid); int break_lock(librados::IoCtx *ioctx, const std::string& oid, const entity_name_t& locker); }; } // namespace lock } // namespace cls } // namespace rados #endif
5,196
35.598592
84
h
null
ceph-main/src/cls/lock/cls_lock_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_LOCK_OPS_H #define CEPH_CLS_LOCK_OPS_H #include "include/types.h" #include "include/utime.h" #include "cls/lock/cls_lock_types.h" struct cls_lock_lock_op { std::string name; ClsLockType type; std::string cookie; std::string tag; std::string description; utime_t duration; uint8_t flags; cls_lock_lock_op() : type(ClsLockType::NONE), flags(0) {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(name, bl); uint8_t t = (uint8_t)type; encode(t, bl); encode(cookie, bl); encode(tag, bl); encode(description, bl); encode(duration, bl); encode(flags, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(name, bl); uint8_t t; decode(t, bl); type = (ClsLockType)t; decode(cookie, bl); decode(tag, bl); decode(description, bl); decode(duration, bl); decode(flags, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_lock_op*>& o); }; WRITE_CLASS_ENCODER(cls_lock_lock_op) struct cls_lock_unlock_op { std::string name; std::string cookie; cls_lock_unlock_op() {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(name, bl); encode(cookie, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(name, bl); decode(cookie, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_unlock_op*>& o); }; WRITE_CLASS_ENCODER(cls_lock_unlock_op) struct cls_lock_break_op { std::string name; entity_name_t locker; std::string cookie; cls_lock_break_op() {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(name, bl); encode(locker, bl); encode(cookie, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(name, bl); decode(locker, bl); decode(cookie, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_break_op*>& o); }; WRITE_CLASS_ENCODER(cls_lock_break_op) struct cls_lock_get_info_op { std::string name; cls_lock_get_info_op() {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(name, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(name, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_get_info_op*>& o); }; WRITE_CLASS_ENCODER(cls_lock_get_info_op) struct cls_lock_get_info_reply { std::map<rados::cls::lock::locker_id_t, rados::cls::lock::locker_info_t> lockers; ClsLockType lock_type; std::string tag; cls_lock_get_info_reply() : lock_type(ClsLockType::NONE) {} void encode(ceph::buffer::list &bl, uint64_t features) const { ENCODE_START(1, 1, bl); encode(lockers, bl, features); uint8_t t = (uint8_t)lock_type; encode(t, bl); encode(tag, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(lockers, bl); uint8_t t; decode(t, bl); lock_type = (ClsLockType)t; decode(tag, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_get_info_reply*>& o); }; WRITE_CLASS_ENCODER_FEATURES(cls_lock_get_info_reply) struct cls_lock_list_locks_reply { std::list<std::string> locks; cls_lock_list_locks_reply() {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(locks, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(locks, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_list_locks_reply*>& o); }; WRITE_CLASS_ENCODER(cls_lock_list_locks_reply) struct cls_lock_assert_op { std::string name; ClsLockType type; std::string cookie; std::string tag; cls_lock_assert_op() : type(ClsLockType::NONE) {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(name, bl); uint8_t t = (uint8_t)type; encode(t, bl); encode(cookie, bl); encode(tag, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(name, bl); uint8_t t; decode(t, bl); type = (ClsLockType)t; decode(cookie, bl); decode(tag, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_assert_op*>& o); }; WRITE_CLASS_ENCODER(cls_lock_assert_op) struct cls_lock_set_cookie_op { std::string name; ClsLockType type; std::string cookie; std::string tag; std::string new_cookie; cls_lock_set_cookie_op() : type(ClsLockType::NONE) {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(name, bl); uint8_t t = (uint8_t)type; encode(t, bl); encode(cookie, bl); encode(tag, bl); encode(new_cookie, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(name, bl); uint8_t t; decode(t, bl); type = (ClsLockType)t; decode(cookie, bl); decode(tag, bl); decode(new_cookie, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<cls_lock_set_cookie_op*>& o); }; WRITE_CLASS_ENCODER(cls_lock_set_cookie_op) #endif
6,144
23.979675
83
h
null
ceph-main/src/cls/lock/cls_lock_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_LOCK_TYPES_H #define CEPH_CLS_LOCK_TYPES_H #include "include/encoding.h" #include "include/types.h" #include "include/utime.h" #include "msg/msg_types.h" /* lock flags */ #define LOCK_FLAG_MAY_RENEW 0x1 /* idempotent lock acquire */ #define LOCK_FLAG_MUST_RENEW 0x2 /* lock must already be acquired */ enum class ClsLockType { NONE = 0, EXCLUSIVE = 1, SHARED = 2, EXCLUSIVE_EPHEMERAL = 3, /* lock object is removed @ unlock */ }; inline const char *cls_lock_type_str(ClsLockType type) { switch (type) { case ClsLockType::NONE: return "none"; case ClsLockType::EXCLUSIVE: return "exclusive"; case ClsLockType::SHARED: return "shared"; case ClsLockType::EXCLUSIVE_EPHEMERAL: return "exclusive-ephemeral"; default: return "<unknown>"; } } inline bool cls_lock_is_exclusive(ClsLockType type) { return ClsLockType::EXCLUSIVE == type || ClsLockType::EXCLUSIVE_EPHEMERAL == type; } inline bool cls_lock_is_ephemeral(ClsLockType type) { return ClsLockType::EXCLUSIVE_EPHEMERAL == type; } inline bool cls_lock_is_valid(ClsLockType type) { return ClsLockType::SHARED == type || ClsLockType::EXCLUSIVE == type || ClsLockType::EXCLUSIVE_EPHEMERAL == type; } namespace rados { namespace cls { namespace lock { /* * locker_id_t: the locker id, needs to be unique in a single lock */ struct locker_id_t { entity_name_t locker; // locker's client name std::string cookie; // locker's cookie. locker_id_t() {} locker_id_t(entity_name_t& _n, const std::string& _c) : locker(_n), cookie(_c) {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(locker, bl); encode(cookie, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(locker, bl); decode(cookie, bl); DECODE_FINISH(bl); } bool operator<(const locker_id_t& rhs) const { if (locker == rhs.locker) return cookie.compare(rhs.cookie) < 0; if (locker < rhs.locker) return true; return false; } void dump(ceph::Formatter *f) const; friend std::ostream& operator<<(std::ostream& out, const locker_id_t& data) { out << data.locker; return out; } static void generate_test_instances(std::list<locker_id_t*>& o); }; WRITE_CLASS_ENCODER(locker_id_t) struct locker_info_t { utime_t expiration; // expiration: non-zero means epoch of locker expiration entity_addr_t addr; // addr: locker address std::string description; // description: locker description, may be empty locker_info_t() {} locker_info_t(const utime_t& _e, const entity_addr_t& _a, const std::string& _d) : expiration(_e), addr(_a), description(_d) {} void encode(ceph::buffer::list &bl, uint64_t features) const { ENCODE_START(1, 1, bl); encode(expiration, bl); encode(addr, bl, features); encode(description, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(expiration, bl); decode(addr, bl); decode(description, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; friend std::ostream& operator<<(std::ostream& out, const locker_info_t& data) { using ceph::operator <<; out << "{addr:" << data.addr << ", exp:"; const auto& exp = data.expiration; if (exp.is_zero()) { out << "never}"; } else { out << exp.to_real_time() << "}"; } return out; } static void generate_test_instances(std::list<locker_info_t *>& o); }; WRITE_CLASS_ENCODER_FEATURES(locker_info_t) struct lock_info_t { std::map<locker_id_t, locker_info_t> lockers; // map of lockers ClsLockType lock_type; // lock type (exclusive / shared) std::string tag; // tag: operations on lock can only succeed with this tag // as long as set of non expired lockers // is bigger than 0. void encode(ceph::buffer::list &bl, uint64_t features) const { ENCODE_START(1, 1, bl); encode(lockers, bl, features); uint8_t t = (uint8_t)lock_type; encode(t, bl); encode(tag, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(lockers, bl); uint8_t t; decode(t, bl); lock_type = (ClsLockType)t; decode(tag, bl); DECODE_FINISH(bl); } lock_info_t() : lock_type(ClsLockType::NONE) {} void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<lock_info_t *>& o); }; WRITE_CLASS_ENCODER_FEATURES(lock_info_t); } } } #endif
5,432
30.045714
104
h
null
ceph-main/src/cls/log/cls_log_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_LOG_CLIENT_H #define CEPH_CLS_LOG_CLIENT_H #include "include/rados/librados_fwd.hpp" #include "cls_log_types.h" /* * log objclass */ void cls_log_add_prepare_entry(cls_log_entry& entry, const utime_t& timestamp, const std::string& section, const std::string& name, ceph::buffer::list& bl); void cls_log_add(librados::ObjectWriteOperation& op, std::list<cls_log_entry>& entries, bool monotonic_inc); void cls_log_add(librados::ObjectWriteOperation& op, cls_log_entry& entry); void cls_log_add(librados::ObjectWriteOperation& op, const utime_t& timestamp, const std::string& section, const std::string& name, ceph::buffer::list& bl); void cls_log_list(librados::ObjectReadOperation& op, const utime_t& from, const utime_t& to, const std::string& in_marker, int max_entries, std::list<cls_log_entry>& entries, std::string *out_marker, bool *truncated); void cls_log_trim(librados::ObjectWriteOperation& op, const utime_t& from_time, const utime_t& to_time, const std::string& from_marker, const std::string& to_marker); // these overloads which call io_ctx.operate() should not be called in the rgw. // rgw_rados_operate() should be called after the overloads w/o calls to io_ctx.operate() #ifndef CLS_CLIENT_HIDE_IOCTX int cls_log_trim(librados::IoCtx& io_ctx, const std::string& oid, const utime_t& from_time, const utime_t& to_time, const std::string& from_marker, const std::string& to_marker); #endif void cls_log_info(librados::ObjectReadOperation& op, cls_log_header *header); #endif
1,710
41.775
115
h
null
ceph-main/src/cls/log/cls_log_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_LOG_OPS_H #define CEPH_CLS_LOG_OPS_H #include "cls_log_types.h" struct cls_log_add_op { std::list<cls_log_entry> entries; bool monotonic_inc; cls_log_add_op() : monotonic_inc(true) {} void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(entries, bl); encode(monotonic_inc, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(entries, bl); if (struct_v >= 2) { decode(monotonic_inc, bl); } DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_log_add_op) struct cls_log_list_op { utime_t from_time; std::string marker; /* if not empty, overrides from_time */ utime_t to_time; /* not inclusive */ int max_entries; /* upperbound to returned num of entries might return less than that and still be truncated */ cls_log_list_op() : max_entries(0) {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(from_time, bl); encode(marker, bl); encode(to_time, bl); encode(max_entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(from_time, bl); decode(marker, bl); decode(to_time, bl); decode(max_entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_log_list_op) struct cls_log_list_ret { std::list<cls_log_entry> entries; std::string marker; bool truncated; cls_log_list_ret() : truncated(false) {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(entries, bl); encode(marker, bl); encode(truncated, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(entries, bl); decode(marker, bl); decode(truncated, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_log_list_ret) /* * operation will return 0 when successfully removed but not done. Will return * -ENODATA when done, so caller needs to repeat sending request until that. */ struct cls_log_trim_op { utime_t from_time; utime_t to_time; /* inclusive */ std::string from_marker; std::string to_marker; cls_log_trim_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(from_time, bl); encode(to_time, bl); encode(from_marker, bl); encode(to_marker, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(from_time, bl); decode(to_time, bl); if (struct_v >= 2) { decode(from_marker, bl); decode(to_marker, bl); } DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_log_trim_op) struct cls_log_info_op { cls_log_info_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); // currently empty request ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); // currently empty request DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_log_info_op) struct cls_log_info_ret { cls_log_header header; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(header, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(header, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_log_info_ret) #endif
3,583
21.828025
78
h
null
ceph-main/src/cls/log/cls_log_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_LOG_TYPES_H #define CEPH_CLS_LOG_TYPES_H #include "include/encoding.h" #include "include/types.h" #include "include/utime.h" #include "common/ceph_json.h" #include "common/Formatter.h" class JSONObj; class JSONDecoder; struct cls_log_entry { std::string id; std::string section; std::string name; utime_t timestamp; ceph::buffer::list data; cls_log_entry() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(section, bl); encode(name, bl); encode(timestamp, bl); encode(data, bl); encode(id, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(section, bl); decode(name, bl); decode(timestamp, bl); decode(data, bl); if (struct_v >= 2) decode(id, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const { encode_json("section", section, f); encode_json("name", name, f); encode_json("timestamp", timestamp, f); encode_json("data", data, f); encode_json("id", id, f); } void decode_json(JSONObj* obj) { JSONDecoder::decode_json("section", section, obj); JSONDecoder::decode_json("name", name, obj); JSONDecoder::decode_json("timestamp", timestamp, obj); JSONDecoder::decode_json("data", data, obj); JSONDecoder::decode_json("id", id, obj); } static void generate_test_instances(std::list<cls_log_entry *>& l) { l.push_back(new cls_log_entry{}); l.push_back(new cls_log_entry); l.back()->id = "test_id"; l.back()->section = "test_section"; l.back()->name = "test_name"; l.back()->timestamp = utime_t(); ceph::buffer::list bl; ceph::encode(std::string("Test"), bl, 0); l.back()->data = bl; } }; WRITE_CLASS_ENCODER(cls_log_entry) struct cls_log_header { std::string max_marker; utime_t max_time; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(max_marker, bl); encode(max_time, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(max_marker, bl); decode(max_time, bl); DECODE_FINISH(bl); } }; inline bool operator ==(const cls_log_header& lhs, const cls_log_header& rhs) { return (lhs.max_marker == rhs.max_marker && lhs.max_time == rhs.max_time); } inline bool operator !=(const cls_log_header& lhs, const cls_log_header& rhs) { return !(lhs == rhs); } WRITE_CLASS_ENCODER(cls_log_header) #endif
2,619
23.485981
79
h
null
ceph-main/src/cls/numops/cls_numops_client.h
/* * Ceph - scalable distributed file system * * Copyright (C) 2015 CERN * * Author: Joaquim Rocha <joaquim.rocha@cern.ch> * * 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. * */ #ifndef CEPH_LIBRBD_CLS_NUMOPS_CLIENT_H #define CEPH_LIBRBD_CLS_NUMOPS_CLIENT_H #include "include/rados/librados_fwd.hpp" #include <string> namespace rados { namespace cls { namespace numops { extern int add(librados::IoCtx *ioctx, const std::string& oid, const std::string& key, double value_to_add); extern int sub(librados::IoCtx *ioctx, const std::string& oid, const std::string& key, double value_to_subtract); extern int mul(librados::IoCtx *ioctx, const std::string& oid, const std::string& key, double value_to_multiply); extern int div(librados::IoCtx *ioctx, const std::string& oid, const std::string& key, double value_to_divide); } // namespace numops } // namespace cls } // namespace rados #endif // CEPH_LIBRBD_CLS_NUMOPS_CLIENT_H
1,447
27.392157
70
h
null
ceph-main/src/cls/otp/cls_otp_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_OTP_CLIENT_H #define CEPH_CLS_OTP_CLIENT_H #include "include/rados/librados_fwd.hpp" #include "cls/otp/cls_otp_types.h" namespace rados { namespace cls { namespace otp { class OTP { public: static void create(librados::ObjectWriteOperation *op, const otp_info_t& config); static void set(librados::ObjectWriteOperation *op, const std::list<otp_info_t>& entries); static void remove(librados::ObjectWriteOperation *op, const std::string& id); static int get(librados::ObjectReadOperation *op, librados::IoCtx& ioctx, const std::string& oid, const std::string& id, otp_info_t *result); static int get_all(librados::ObjectReadOperation *op, librados::IoCtx& ioctx, const std::string& oid, std::list<otp_info_t> *result); // these overloads which call io_ctx.operate() or io_ctx.exec() should not be called in the rgw. // rgw_rados_operate() should be called after the overloads w/o calls to io_ctx.operate()/exec() #ifndef CLS_CLIENT_HIDE_IOCTX static int get(librados::ObjectReadOperation *op, librados::IoCtx& ioctx, const std::string& oid, const std::list<std::string> *ids, bool get_all, std::list<otp_info_t> *result); static int check(CephContext *cct, librados::IoCtx& ioctx, const std::string& oid, const std::string& id, const std::string& val, otp_check_t *result); static int get_current_time(librados::IoCtx& ioctx, const std::string& oid, ceph::real_time *result); #endif }; class TOTPConfig { otp_info_t config; public: TOTPConfig(const std::string& id, const std::string& seed) { config.type = OTP_TOTP; config.id = id; config.seed = seed; } void set_step_size(int step_size) { config.step_size = step_size; } void set_window(int window) { config.window = window; } void get_config(otp_info_t *conf) { *conf = config; } }; } // namespace otp } // namespace cls } // namespace rados #endif
2,404
38.42623
103
h
null
ceph-main/src/cls/otp/cls_otp_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_OTP_OPS_H #define CEPH_CLS_OTP_OPS_H #include "include/types.h" #include "include/utime.h" #include "cls/otp/cls_otp_types.h" struct cls_otp_set_otp_op { std::list<rados::cls::otp::otp_info_t> entries; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_set_otp_op) struct cls_otp_check_otp_op { std::string id; std::string val; std::string token; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(id, bl); encode(val, bl); encode(token, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(id, bl); decode(val, bl); decode(token, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_check_otp_op) struct cls_otp_get_result_op { std::string token; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(token, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(token, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_get_result_op) struct cls_otp_get_result_reply { rados::cls::otp::otp_check_t result; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(result, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(result, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_get_result_reply) struct cls_otp_remove_otp_op { std::list<std::string> ids; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(ids, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(ids, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_remove_otp_op) struct cls_otp_get_otp_op { bool get_all{false}; std::list<std::string> ids; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(get_all, bl); encode(ids, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(get_all, bl); decode(ids, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_get_otp_op) struct cls_otp_get_otp_reply { std::list<rados::cls::otp::otp_info_t> found_entries; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(found_entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(found_entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_get_otp_reply) struct cls_otp_get_current_time_op { void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_get_current_time_op) struct cls_otp_get_current_time_reply { ceph::real_time time; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(time, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(time, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_otp_get_current_time_reply) #endif
3,707
20.811765
70
h
null
ceph-main/src/cls/otp/cls_otp_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_OTP_TYPES_H #define CEPH_CLS_OTP_TYPES_H #include "include/encoding.h" #include "include/types.h" #define CLS_OTP_MAX_REPO_SIZE 100 class JSONObj; namespace rados { namespace cls { namespace otp { enum OTPType { OTP_UNKNOWN = 0, OTP_HOTP = 1, /* unsupported */ OTP_TOTP = 2, }; enum SeedType { OTP_SEED_UNKNOWN = 0, OTP_SEED_HEX = 1, OTP_SEED_BASE32 = 2, }; struct otp_info_t { OTPType type{OTP_TOTP}; std::string id; std::string seed; SeedType seed_type{OTP_SEED_UNKNOWN}; ceph::buffer::list seed_bin; /* parsed seed, built automatically by otp_set_op, * not being json encoded/decoded on purpose */ int32_t time_ofs{0}; uint32_t step_size{30}; /* num of seconds foreach otp to test */ uint32_t window{2}; /* num of otp after/before start otp to test */ otp_info_t() {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode((uint8_t)type, bl); /* if we ever implement anything other than TOTP * then we'll need to branch here */ encode(id, bl); encode(seed, bl); encode((uint8_t)seed_type, bl); encode(seed_bin, bl); encode(time_ofs, bl); encode(step_size, bl); encode(window, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); uint8_t t; decode(t, bl); type = (OTPType)t; decode(id, bl); decode(seed, bl); uint8_t st; decode(st, bl); seed_type = (SeedType)st; decode(seed_bin, bl); decode(time_ofs, bl); decode(step_size, bl); decode(window, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(rados::cls::otp::otp_info_t) enum OTPCheckResult { OTP_CHECK_UNKNOWN = 0, OTP_CHECK_SUCCESS = 1, OTP_CHECK_FAIL = 2, }; struct otp_check_t { std::string token; ceph::real_time timestamp; OTPCheckResult result{OTP_CHECK_UNKNOWN}; void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(token, bl); encode(timestamp, bl); encode((char)result, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(token, bl); decode(timestamp, bl); uint8_t t; decode(t, bl); result = (OTPCheckResult)t; DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(rados::cls::otp::otp_check_t) struct otp_repo_t { std::map<std::string, otp_info_t> entries; otp_repo_t() {} void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(rados::cls::otp::otp_repo_t) } } } WRITE_CLASS_ENCODER(rados::cls::otp::otp_info_t) WRITE_CLASS_ENCODER(rados::cls::otp::otp_check_t) WRITE_CLASS_ENCODER(rados::cls::otp::otp_repo_t) #endif
3,717
26.338235
87
h
null
ceph-main/src/cls/queue/cls_queue_client.h
#ifndef CEPH_CLS_QUEUE_CLIENT_H #define CEPH_CLS_QUEUE_CLIENT_H #include "include/rados/librados.hpp" #include "cls/queue/cls_queue_types.h" #include "cls_queue_ops.h" #include "common/ceph_time.h" void cls_queue_init(librados::ObjectWriteOperation& op, const std::string& queue_name, uint64_t size); int cls_queue_get_capacity(librados::IoCtx& io_ctx, const std::string& oid, uint64_t& size); void cls_queue_enqueue(librados::ObjectWriteOperation& op, uint32_t expiration_secs, std::vector<bufferlist> bl_data_vec); int cls_queue_list_entries(librados::IoCtx& io_ctx, const std::string& oid, const std::string& marker, uint32_t max, std::vector<cls_queue_entry>& entries, bool *truncated, std::string& next_marker); void cls_queue_remove_entries(librados::ObjectWriteOperation& op, const std::string& end_marker); #endif
845
48.764706
122
h
null
ceph-main/src/cls/queue/cls_queue_ops.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_QUEUE_OPS_H #define CEPH_CLS_QUEUE_OPS_H #include "cls/queue/cls_queue_types.h" struct cls_queue_init_op { uint64_t queue_size{0}; uint64_t max_urgent_data_size{0}; ceph::buffer::list bl_urgent_data; cls_queue_init_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(queue_size, bl); encode(max_urgent_data_size, bl); encode(bl_urgent_data, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(queue_size, bl); decode(max_urgent_data_size, bl); decode(bl_urgent_data, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_init_op) struct cls_queue_enqueue_op { std::vector<ceph::buffer::list> bl_data_vec; cls_queue_enqueue_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(bl_data_vec, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(bl_data_vec, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_enqueue_op) struct cls_queue_list_op { uint64_t max; std::string start_marker; cls_queue_list_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(max, bl); encode(start_marker, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(max, bl); decode(start_marker, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_list_op) struct cls_queue_list_ret { bool is_truncated; std::string next_marker; std::vector<cls_queue_entry> entries; cls_queue_list_ret() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(is_truncated, bl); encode(next_marker, bl); encode(entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(is_truncated, bl); decode(next_marker, bl); decode(entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_list_ret) struct cls_queue_remove_op { std::string end_marker; cls_queue_remove_op() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(end_marker, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(end_marker, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_remove_op) struct cls_queue_get_capacity_ret { uint64_t queue_capacity; cls_queue_get_capacity_ret() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(queue_capacity, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(queue_capacity, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_get_capacity_ret) struct cls_queue_get_stats_ret { uint64_t queue_size; uint32_t queue_entries; cls_queue_get_stats_ret() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(queue_size, bl); encode(queue_entries, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(queue_size, bl); decode(queue_entries, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_get_stats_ret) #endif /* CEPH_CLS_QUEUE_OPS_H */
3,588
21.154321
70
h
null
ceph-main/src/cls/queue/cls_queue_src.h
#ifndef CEPH_CLS_QUEUE_SRC_H #define CEPH_CLS_QUEUE_SRC_H #include "objclass/objclass.h" #include "cls/queue/cls_queue_types.h" #include "cls/queue/cls_queue_ops.h" int queue_write_head(cls_method_context_t hctx, cls_queue_head& head); int queue_read_head(cls_method_context_t hctx, cls_queue_head& head); int queue_init(cls_method_context_t hctx, const cls_queue_init_op& op); int queue_get_capacity(cls_method_context_t hctx, cls_queue_get_capacity_ret& op_ret); int queue_enqueue(cls_method_context_t hctx, cls_queue_enqueue_op& op, cls_queue_head& head); int queue_list_entries(cls_method_context_t hctx, const cls_queue_list_op& op, cls_queue_list_ret& op_ret, cls_queue_head& head); int queue_remove_entries(cls_method_context_t hctx, const cls_queue_remove_op& op, cls_queue_head& head); #endif /* CEPH_CLS_QUEUE_SRC_H */
832
48
129
h
null
ceph-main/src/cls/queue/cls_queue_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_QUEUE_TYPES_H #define CEPH_CLS_QUEUE_TYPES_H #include <errno.h> #include "include/types.h" //Size of head leaving out urgent data #define QUEUE_HEAD_SIZE_1K 1024 #define QUEUE_START_OFFSET_1K QUEUE_HEAD_SIZE_1K constexpr unsigned int QUEUE_HEAD_START = 0xDEAD; constexpr unsigned int QUEUE_ENTRY_START = 0xBEEF; constexpr unsigned int QUEUE_ENTRY_OVERHEAD = sizeof(uint16_t) + sizeof(uint64_t); struct cls_queue_entry { ceph::buffer::list data; std::string marker; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(data, bl); encode(marker, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(data, bl); decode(marker, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_entry) struct cls_queue_marker { uint64_t offset{0}; uint64_t gen{0}; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(gen, bl); encode(offset, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(gen, bl); decode(offset, bl); DECODE_FINISH(bl); } std::string to_str() { return std::to_string(gen) + '/' + std::to_string(offset); } int from_str(const char* str) { errno = 0; char* end = nullptr; gen = ::strtoull(str, &end, 10); if (errno) { return errno; } if (str == end || *end != '/') { // expects delimiter return -EINVAL; } str = end + 1; offset = ::strtoull(str, &end, 10); if (errno) { return errno; } if (str == end || *end != 0) { // expects null terminator return -EINVAL; } return 0; } }; WRITE_CLASS_ENCODER(cls_queue_marker) struct cls_queue_head { uint64_t max_head_size = QUEUE_HEAD_SIZE_1K; cls_queue_marker front{QUEUE_START_OFFSET_1K, 0}; cls_queue_marker tail{QUEUE_START_OFFSET_1K, 0}; uint64_t queue_size{0}; // size of queue requested by user, with head size added to it uint64_t max_urgent_data_size{0}; ceph::buffer::list bl_urgent_data; // special data known to application using queue void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(max_head_size, bl); encode(front, bl); encode(tail, bl); encode(queue_size, bl); encode(max_urgent_data_size, bl); encode(bl_urgent_data, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(max_head_size, bl); decode(front, bl); decode(tail, bl); decode(queue_size, bl); decode(max_urgent_data_size, bl); decode(bl_urgent_data, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(cls_queue_head) #endif
2,881
22.818182
88
h
null
ceph-main/src/cls/rbd/cls_rbd.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef __CEPH_CLS_RBD_H #define __CEPH_CLS_RBD_H #include "include/types.h" #include "include/buffer_fwd.h" #include "include/rbd_types.h" #include "common/Formatter.h" #include "cls/rbd/cls_rbd_types.h" /// information about our parent image, if any struct cls_rbd_parent { int64_t pool_id = -1; std::string pool_namespace; std::string image_id; snapid_t snap_id = CEPH_NOSNAP; std::optional<uint64_t> head_overlap = std::nullopt; cls_rbd_parent() { } cls_rbd_parent(const cls::rbd::ParentImageSpec& parent_image_spec, const std::optional<uint64_t>& head_overlap) : pool_id(parent_image_spec.pool_id), pool_namespace(parent_image_spec.pool_namespace), image_id(parent_image_spec.image_id), snap_id(parent_image_spec.snap_id), head_overlap(head_overlap) { } inline bool exists() const { return (pool_id >= 0 && !image_id.empty() && snap_id != CEPH_NOSNAP); } inline bool operator==(const cls_rbd_parent& rhs) const { return (pool_id == rhs.pool_id && pool_namespace == rhs.pool_namespace && image_id == rhs.image_id && snap_id == rhs.snap_id); } inline bool operator!=(const cls_rbd_parent& rhs) const { return !(*this == rhs); } void encode(ceph::buffer::list& bl, uint64_t features) const { // NOTE: remove support for version 1 after Nautilus EOLed uint8_t version = 1; if ((features & CEPH_FEATURE_SERVER_NAUTILUS) != 0ULL) { // break backwards compatability when using nautilus or later OSDs version = 2; } ENCODE_START(version, version, bl); encode(pool_id, bl); if (version >= 2) { encode(pool_namespace, bl); } encode(image_id, bl); encode(snap_id, bl); if (version == 1) { encode(head_overlap.value_or(0ULL), bl); } else { encode(head_overlap, bl); } ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(pool_id, bl); if (struct_v >= 2) { decode(pool_namespace, bl); } decode(image_id, bl); decode(snap_id, bl); if (struct_v == 1) { uint64_t overlap; decode(overlap, bl); head_overlap = overlap; } else { decode(head_overlap, bl); } DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_int("pool_id", pool_id); f->dump_string("pool_namespace", pool_namespace); f->dump_string("image_id", image_id); f->dump_unsigned("snap_id", snap_id); if (head_overlap) { f->dump_unsigned("head_overlap", *head_overlap); } } static void generate_test_instances(std::list<cls_rbd_parent*>& o) { o.push_back(new cls_rbd_parent{}); o.push_back(new cls_rbd_parent{{1, "", "image id", 234}, {}}); o.push_back(new cls_rbd_parent{{1, "", "image id", 234}, {123}}); o.push_back(new cls_rbd_parent{{1, "ns", "image id", 234}, {123}}); } }; WRITE_CLASS_ENCODER_FEATURES(cls_rbd_parent) struct cls_rbd_snap { snapid_t id = CEPH_NOSNAP; std::string name; uint64_t image_size = 0; uint8_t protection_status = RBD_PROTECTION_STATUS_UNPROTECTED; cls_rbd_parent parent; uint64_t flags = 0; utime_t timestamp; cls::rbd::SnapshotNamespace snapshot_namespace = { cls::rbd::UserSnapshotNamespace{}}; uint32_t child_count = 0; std::optional<uint64_t> parent_overlap = std::nullopt; cls_rbd_snap() { } cls_rbd_snap(snapid_t id, const std::string& name, uint64_t image_size, uint8_t protection_status, const cls_rbd_parent& parent, uint64_t flags, utime_t timestamp, const cls::rbd::SnapshotNamespace& snapshot_namespace, uint32_t child_count, const std::optional<uint64_t>& parent_overlap) : id(id), name(name), image_size(image_size), protection_status(protection_status), parent(parent), flags(flags), timestamp(timestamp), snapshot_namespace(snapshot_namespace), child_count(child_count), parent_overlap(parent_overlap) { } bool migrate_parent_format(uint64_t features) const { return (((features & CEPH_FEATURE_SERVER_NAUTILUS) != 0) && (parent.exists())); } void encode(ceph::buffer::list& bl, uint64_t features) const { // NOTE: remove support for versions < 8 after Nautilus EOLed uint8_t min_version = 1; if ((features & CEPH_FEATURE_SERVER_NAUTILUS) != 0ULL) { // break backwards compatability when using nautilus or later OSDs min_version = 8; } ENCODE_START(8, min_version, bl); encode(id, bl); encode(name, bl); encode(image_size, bl); if (min_version < 8) { uint64_t image_features = 0; encode(image_features, bl); // unused -- preserve ABI encode(parent, bl, features); } encode(protection_status, bl); encode(flags, bl); encode(snapshot_namespace, bl); encode(timestamp, bl); encode(child_count, bl); encode(parent_overlap, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(8, p); decode(id, p); decode(name, p); decode(image_size, p); if (struct_compat < 8) { uint64_t features; decode(features, p); // unused -- preserve ABI } if (struct_v >= 2 && struct_compat < 8) { decode(parent, p); } if (struct_v >= 3) { decode(protection_status, p); } if (struct_v >= 4) { decode(flags, p); } if (struct_v >= 5) { decode(snapshot_namespace, p); } if (struct_v >= 6) { decode(timestamp, p); } if (struct_v >= 7) { decode(child_count, p); } if (struct_v >= 8) { decode(parent_overlap, p); } DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_unsigned("id", id); f->dump_string("name", name); f->dump_unsigned("image_size", image_size); if (parent.exists()) { f->open_object_section("parent"); parent.dump(f); f->close_section(); } switch (protection_status) { case RBD_PROTECTION_STATUS_UNPROTECTED: f->dump_string("protection_status", "unprotected"); break; case RBD_PROTECTION_STATUS_UNPROTECTING: f->dump_string("protection_status", "unprotecting"); break; case RBD_PROTECTION_STATUS_PROTECTED: f->dump_string("protection_status", "protected"); break; default: ceph_abort(); } f->open_object_section("namespace"); snapshot_namespace.dump(f); f->close_section(); f->dump_stream("timestamp") << timestamp; f->dump_unsigned("child_count", child_count); if (parent_overlap) { f->dump_unsigned("parent_overlap", *parent_overlap); } } static void generate_test_instances(std::list<cls_rbd_snap*>& o) { o.push_back(new cls_rbd_snap{}); o.push_back(new cls_rbd_snap{1, "snap", 123456, RBD_PROTECTION_STATUS_PROTECTED, {{1, "", "image", 123}, 234}, 31, {}, cls::rbd::UserSnapshotNamespace{}, 543, {}}); o.push_back(new cls_rbd_snap{1, "snap", 123456, RBD_PROTECTION_STATUS_PROTECTED, {{1, "", "image", 123}, 234}, 31, {}, cls::rbd::UserSnapshotNamespace{}, 543, {0}}); o.push_back(new cls_rbd_snap{1, "snap", 123456, RBD_PROTECTION_STATUS_PROTECTED, {{1, "ns", "image", 123}, 234}, 31, {}, cls::rbd::UserSnapshotNamespace{}, 543, {123}}); } }; WRITE_CLASS_ENCODER_FEATURES(cls_rbd_snap) #endif // __CEPH_CLS_RBD_H
7,846
30.641129
79
h
null
ceph-main/src/cls/refcount/cls_refcount_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_CLS_REFCOUNT_CLIENT_H #define CEPH_CLS_REFCOUNT_CLIENT_H #include "include/rados/librados_fwd.hpp" #include "include/types.h" /* * refcount objclass * * The refcount objclass implements a refcounting scheme that allows having multiple references * to a single rados object. The canonical way to use it is to add a reference and to remove a * reference using a specific tag. This way we ensure that refcounting operations are idempotent, * that is, a single client can only increase/decrease the refcount once using a single tag, so * any replay of operations (implicit or explicit) is possible. * * So, the regular usage would be to create an object, to increase the refcount. Then, when * wanting to have another reference to it, increase the refcount using a different tag. When * removing a reference it is required to drop the refcount (using the same tag that was used * for that reference). When the refcount drops to zero, the object is removed automaticfally. * * In order to maintain backwards compatibility with objects that were created without having * their refcount increased, the implicit_ref was added. Any object that was created without * having it's refcount increased (explicitly) is having an implicit refcount of 1. Since * we don't have a tag for this refcount, we consider this tag as a wildcard. So if the refcount * is being decreased by an unknown tag and we still have one wildcard tag, we'll accept it * as the relevant tag, and the refcount will be decreased. */ void cls_refcount_get(librados::ObjectWriteOperation& op, const std::string& tag, bool implicit_ref = false); void cls_refcount_put(librados::ObjectWriteOperation& op, const std::string& tag, bool implicit_ref = false); void cls_refcount_set(librados::ObjectWriteOperation& op, std::list<std::string>& refs); // these overloads which call io_ctx.operate() or io_ctx.exec() should not be called in the rgw. // rgw_rados_operate() should be called after the overloads w/o calls to io_ctx.operate()/exec() #ifndef CLS_CLIENT_HIDE_IOCTX int cls_refcount_read(librados::IoCtx& io_ctx, std::string& oid, std::list<std::string> *refs, bool implicit_ref = false); #endif #endif
2,299
53.761905
122
h