MongoDB核心类之service_context.h: mongo::ServiceContext

MongoDB核心类之service_context.h: mongo::ServiceContext

目录

MongoDB核心类之service_context.h: mongo::ServiceContext

ServiceContext的内部类:客户端观察者:ClientObserver

ServiceContext内部类:LockedClientsCursor,用来枚举ServiceContext中的所有Client。

ServiceContext内部类:删除ServiceContext的接口ServiceContextDeleter

ServiceContext内部类:删除客户端Client对象的接口:ClientDeleter

ServiceContext内部类:删除OperationContext类的接口:OperationContextDeleter

ServiceContext内部接口:ServiceContext的构造和释放

ServiceContext内部类:构建时动作注册:ConstructorActionRegisterer

ServiceContext内部类:用来持有ClientObserver的ClientObserverHolder

ServiceContext内部字段

ServiceContext的字段:与上边操作分开了,实际上是一个类里的

ServiceEntryPoint和ServiceStateMachine以及ServiceExecutor之间的关系如下


ServiceContext代表了一个mongodb服务器。 比如一个mongod服务器, 或者一个mongos路由(分片模式下)。ServiceContext是Context继承关系中的根结点。ServiceContext拥有0个或者多个客户端(client), 每个客户端拥有各自的OperationContexts.

源码版本:

mongo$ git log
commit 85707dafe1d2894505fdcf74336f93ed7a5f6636
Author: dalyd <[email protected]>
Date:   Fri Jun 19 11:22:47 2020 -0400

    SERVER-49807 Use modules for Linkbench2

ServiceContext的内部类:客户端观察者:ClientObserver

创建方法:在service->makeClient()创建后会创建ClientObserver对象。作为观察者,预定义了以下几个事件。

class ClientObserver {
    public:
        virtual ~ClientObserver() = default;
        virtual void onCreateClient(Client* client) = 0;
        virtual void onDestroyClient(Client* client) = 0;
        virtual void onCreateOperationContext(OperationContext* opCtx) = 0;
        virtual void onDestroyOperationContext(OperationContext* opCtx) = 0;
};

ServiceContext内部类:LockedClientsCursor,用来枚举ServiceContext中的所有Client。

class LockedClientsCursor {
public:
    explicit LockedClientsCursor(ServiceContext* service);
    Client* next();
private:
    stdx::unique_lock<Latch> _lock;
    ClientSet::const_iterator _curr;
    ClientSet::const_iterator _end;
};
Client* ServiceContext::LockedClientsCursor::next() {
    if (_curr == _end)
        return nullptr;
    Client* result = *_curr;
    ++_curr;
    return result;
}

ServiceContext内部类:删除ServiceContext的接口ServiceContextDeleter

class ServiceContextDeleter {
public:
    void operator()(ServiceContext* service) const;
};
//为unique_ptr的对象指定析构器
using UniqueServiceContext = std::unique_ptr<ServiceContext, ServiceContextDeleter>;

ServiceContext内部类:删除客户端Client对象的接口:ClientDeleter

class ClientDeleter {
public:
    void operator()(Client* client) const;
};
//定义Unique类型,提供客户端释放函数
using UniqueClient = std::unique_ptr<Client, ClientDeleter>;

ServiceContext内部类:删除OperationContext类的接口:OperationContextDeleter

class OperationContextDeleter {
public:
    void operator()(OperationContext* opCtx) const;
};
using UniqueOperationContext = std::unique_ptr<OperationContext, OperationContextDeleter>;

ServiceContext内部接口:ServiceContext的构造和释放

using ConstructorAction = std::function<void(ServiceContext*)>;
using DestructorAction = std::function<void(ServiceContext*)>;
class ConstructorDestructorActions {
public:
    ConstructorDestructorActions(ConstructorAction constructor, DestructorAction destructor)
        : _constructor(std::move(constructor)), _destructor(std::move(destructor)) {}

    void onCreate(ServiceContext* service) const {
        _constructor(service);
    }
    void onDestroy(ServiceContext* service) const {
        _destructor(service);
    }

private:
    ConstructorAction _constructor;
    DestructorAction _destructor;
};

ServiceContext内部类:构建时动作注册:ConstructorActionRegisterer

class ConstructorActionRegisterer { //构造时的动作注册
    public:
        ConstructorActionRegisterer(std::string name,
                                    ConstructorAction constructor,
                                    DestructorAction destructor = {});

        //构造动作会关联一个名字
        //constructor在所有prereqs执行成功后。然后执行对应的destructor(如果有提供,可以不提供)
        ConstructorActionRegisterer(std::string name,
                                    std::vector<std::string> prereqs,
                                    ConstructorAction constructor,
                                    DestructorAction destructor = {});


        //先执行preqs,再执行constructor,再执行最后执行depends,再执行destructor.
        ConstructorActionRegisterer(std::string name,
                                    std::vector<std::string> prereqs,
                                    std::vector<std::string> dependents,
                                    ConstructorAction constructor,
                                    DestructorAction destructor = {});

    private:
        using ConstructorActionListIterator = std::list<ConstructorDestructorActions>::iterator;
        ConstructorActionListIterator _iter;
        //全局注册器
        boost::optional<GlobalInitializerRegisterer> _registerer;
};

ServiceContext内部类:用来持有ClientObserver的ClientObserverHolder

class ClientObserverHolder {
public:

    void onCreate(Client* client) const {
        _observer->onCreateClient(client);
    }
    void onDestroy(Client* client) const {
        _observer->onDestroyClient(client);
    }
    void onCreate(OperationContext* opCtx) const {
        _observer->onCreateOperationContext(opCtx);
    }
    void onDestroy(OperationContext* opCtx) const {
         _observer->onDestroyOperationContext(opCtx);
    }
    /*explicit*/ ClientObserverHolder(std::unique_ptr<ClientObserver> observer)
            : _observer(std::move(observer)) {}
private:
    std::unique_ptr<ClientObserver> _observer;
};

ServiceContext内部字段

class ServiceContext final : public Decorable<ServiceContext> {
    //可见不能直接构造ServiceContext对象。此对象也不能拷贝。构造函数和赋值操作都被删除了。
    ServiceContext(const ServiceContext&) = delete;
    ServiceContext& operator=(const ServiceContext&) = delete;
public:
    using ClientSet = stdx::unordered_set<Client*>;
    //构建ServiceContext的工厂函数
    static UniqueServiceContext make();

    ServiceContext();
    ~ServiceContext();
    //注册客户端观察者:只能在makeClient中调用,或者在启动多线程前
    void registerClientObserver(std::unique_ptr<ClientObserver> observer);
    //创建一个客户端Client对象,session是transport里的SessionHandle对象,此对象用来与客户端交互
    UniqueClient makeClient(std::string desc, transport::SessionHandle session = nullptr);
    //创建一个操作上下文,此时client不能有OperationContext
    UniqueOperationContext makeOperationContext(Client* client);
    //设置存储引擎 In-Memory  WireTiger?
    void setStorageEngine(std::unique_ptr<StorageEngine> engine);
    StorageEngine* getStorageEngine() {
        return _storageEngine.get();
    }
    //信号处理,通知所有的OperationContext已经被Kill了
    void setKillAllOperations();
    void unsetKillAllOperations();
    bool getKillAllOperations() {
        return _globalKill.loadRelaxed();
    }
    //处理信号,默认值是ctrl+C. 操作前要先获取 opCtx->getClient, and opCtx->getServiceContext() 的锁。遍历_killOpListeners,调用其interrupt方法。
    void killOperation(WithLock,
                       OperationContext* opCtx,
                       ErrorCodes::Error killCode = ErrorCodes::Interrupted);
    void killAndDelistOperation(
        OperationContext* opCtx,
        ErrorCodes::Error killError = ErrorCodes::OperationIsKilledAndDelisted) noexcept;
    //注册信号处理器
    void registerKillOpListener(KillOpListenerInterface* listener);  
    //设置周期化运行的函数,在设置前必须已经在运行了。ServiceContext不负责启动runner
    void setPeriodicRunner(std::unique_ptr<PeriodicRunner> runner);
    PeriodicRunner* getPeriodicRunner() const;  

   //transport
   transport::TransportLayer* getTransportLayer() const;
   ServiceEntryPoint* getServiceEntryPoint() const;
   transport::ServiceExecutor* getServiceExecutor() const; //一个调度器,可以把任务调度到线程上运行
    void setServiceEntryPoint(std::unique_ptr<ServiceEntryPoint> sep);
    void setTransportLayer(std::unique_ptr<transport::TransportLayer> tl);
    void setServiceExecutor(std::unique_ptr<transport::ServiceExecutor> exec);
   //阻塞,等所有transportLayer都添加完成
   void waitForStartupComplete();
   //通知所有TransportLayer启动完成
   void notifyStartupComplete();
   int getActiveClientOperations();
   void setOpObserver(std::unique_ptr<OpObserver> opObserver);
    OpObserver* getOpObserver() const {
        return _opObserver.get();
    }
    //GET SET几种时钟源
    TickSource* getTickSource() const {
        return _tickSource.get();
    }
    ClockSource* getFastClockSource() const {
        return _fastClockSource.get();
    }
    ClockSource* getPreciseClockSource() const {
        return _preciseClockSource.get();
    }
    //延时执行器
     BatonHandle makeBaton(OperationContext* opCtx) const;

    uint64_t getCatalogGeneration() const {
        return _catalogGeneration.load();
    }

    void incrementCatalogGeneration() {
        _catalogGeneration.fetchAndAdd(1);
    }

    LockedClient getLockedClient(OperationId id);
    //移除opCtx上的操作,要获得Client的锁
    void _delistOperation(OperationContext* opCtx) noexcept;
};

ServiceContext的字段:与上边操作分开了,实际上是一个类里的

class ServiceContext final : public Decorable<ServiceContext>
{
    //ServiceContext级别的锁    
    Mutex _mutex = MONGO_MAKE_LATCH(/*HierarchicalAcquisitionLevel(2), */             
    "ServiceContext::_mutex");


    std::unique_ptr<PeriodicRunner> _runner;
    //传输层,也就是网络接口,用来接受客户端连接
    std::unique_ptr<transport::TransportLayer> _transportLayer;
    //这里注册各种命令,mongos和mongod显示能处理的命令不同
    std::unique_ptr<ServiceEntryPoint> _serviceEntryPoint;
    std::unique_ptr<transport::ServiceExecutor> _serviceExecutor;
    std::unique_ptr<StorageEngine> _storageEngine;
    std::vector<ClientObserverHolder> _clientObservers;
    ClientSet _clients;    //所有的clients都放在这个set里
    //OperationId到Client的映射
    stdx::unordered_map<OperationId, Client*> _clientByOperationId;
    std::unique_ptr<OpObserver> _opObserver;
    std::unique_ptr<TickSource> _tickSource;
    //不精确,但是调用成本低
    std::unique_ptr<ClockSource> _fastClockSource;
    //高精确度,但是调用成本高
    std::unique_ptr<ClockSource> _preciseClockSource;
    AtomicWord<bool> _globalKill{false};
    std::vector<KillOpListenerInterface*> _killOpListeners;
    //用来分配操作ID
    AtomicWord<OperationId> _nextOpId{1};
    AtomicWord<uint64_t> _catalogGeneration{0};
    bool _startupComplete = false;
    stdx::condition_variable _startupCompleteCondVar;
};

ServiceEntryPoint和ServiceStateMachine以及ServiceExecutor之间的关系如下

更加详细的关系见我的另一篇:mongodb之mongod启动,各核心类之间的关系

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章