actorsystem.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #pragma once
  2. #include "defs.h"
  3. #include "balancer.h"
  4. #include "config.h"
  5. #include "event.h"
  6. #include "executor_pool.h"
  7. #include "log_settings.h"
  8. #include "scheduler_cookie.h"
  9. #include "mon_stats.h"
  10. #include "cpu_manager.h"
  11. #include "executor_thread.h"
  12. #include <library/cpp/threading/future/future.h>
  13. #include <library/cpp/actors/util/ticket_lock.h>
  14. #include <util/generic/vector.h>
  15. #include <util/datetime/base.h>
  16. #include <util/system/mutex.h>
  17. namespace NActors {
  18. class IActor;
  19. class TActorSystem;
  20. class TCpuManager;
  21. struct TWorkerContext;
  22. inline TActorId MakeInterconnectProxyId(ui32 destNodeId) {
  23. char data[12];
  24. memcpy(data, "ICProxy@", 8);
  25. memcpy(data + 8, &destNodeId, sizeof(ui32));
  26. return TActorId(0, TStringBuf(data, 12));
  27. }
  28. inline bool IsInterconnectProxyId(const TActorId& actorId) {
  29. return actorId.IsService() && !memcmp(actorId.ServiceId().data(), "ICProxy@", 8);
  30. }
  31. inline ui32 GetInterconnectProxyNode(const TActorId& actorId) {
  32. ui32 nodeId;
  33. memcpy(&nodeId, actorId.ServiceId().data() + 8, sizeof(ui32));
  34. return nodeId;
  35. }
  36. namespace NSchedulerQueue {
  37. class TReader;
  38. struct TQueueType;
  39. }
  40. // could be proxy to in-pool schedulers (for NUMA-aware executors)
  41. class ISchedulerThread : TNonCopyable {
  42. public:
  43. virtual ~ISchedulerThread() {
  44. }
  45. virtual void Prepare(TActorSystem* actorSystem, volatile ui64* currentTimestamp, volatile ui64* currentMonotonic) = 0;
  46. virtual void PrepareSchedules(NSchedulerQueue::TReader** readers, ui32 scheduleReadersCount) = 0;
  47. virtual void PrepareStart() { /* empty */ }
  48. virtual void Start() = 0;
  49. virtual void PrepareStop() = 0;
  50. virtual void Stop() = 0;
  51. };
  52. struct TActorSetupCmd {
  53. TMailboxType::EType MailboxType;
  54. ui32 PoolId;
  55. std::unique_ptr<IActor> Actor;
  56. TActorSetupCmd();
  57. TActorSetupCmd(const TActorSetupCmd&) = delete;
  58. TActorSetupCmd(TActorSetupCmd&&);
  59. TActorSetupCmd& operator=(const TActorSetupCmd&) = delete;
  60. TActorSetupCmd& operator=(TActorSetupCmd&&);
  61. TActorSetupCmd(std::unique_ptr<IActor> actor, TMailboxType::EType mailboxType, ui32 poolId);
  62. ~TActorSetupCmd();
  63. // For legacy code, please do not use
  64. TActorSetupCmd(IActor* actor, TMailboxType::EType mailboxType, ui32 poolId);
  65. void Set(std::unique_ptr<IActor> actor, TMailboxType::EType mailboxType, ui32 poolId);
  66. };
  67. using TProxyWrapperFactory = std::function<TActorId(TActorSystem*, ui32)>;
  68. struct TInterconnectSetup {
  69. TVector<TActorSetupCmd> ProxyActors;
  70. TProxyWrapperFactory ProxyWrapperFactory;
  71. };
  72. struct TActorSystemSetup {
  73. ui32 NodeId = 0;
  74. // Either Executors or CpuManager must be initialized
  75. ui32 ExecutorsCount = 0;
  76. TArrayHolder<TAutoPtr<IExecutorPool>> Executors;
  77. TAutoPtr<IBalancer> Balancer; // main implementation will be implicitly created if not set
  78. TCpuManagerConfig CpuManager;
  79. TAutoPtr<ISchedulerThread> Scheduler;
  80. TInterconnectSetup Interconnect;
  81. bool MonitorStuckActors = false;
  82. using TLocalServices = TVector<std::pair<TActorId, TActorSetupCmd>>;
  83. TLocalServices LocalServices;
  84. ui32 GetExecutorsCount() const {
  85. return Executors ? ExecutorsCount : CpuManager.GetExecutorsCount();
  86. }
  87. TString GetPoolName(ui32 poolId) const {
  88. return Executors ? Executors[poolId]->GetName() : CpuManager.GetPoolName(poolId);
  89. }
  90. ui32 GetThreads(ui32 poolId) const {
  91. auto result = GetThreadsOptional(poolId);
  92. Y_ABORT_UNLESS(result, "undefined pool id: %" PRIu32, (ui32)poolId);
  93. return *result;
  94. }
  95. std::optional<ui32> GetThreadsOptional(const ui32 poolId) const {
  96. if (Y_LIKELY(Executors)) {
  97. if (Y_LIKELY(poolId < ExecutorsCount)) {
  98. return Executors[poolId]->GetDefaultThreadCount();
  99. } else {
  100. return {};
  101. }
  102. } else {
  103. return CpuManager.GetThreadsOptional(poolId);
  104. }
  105. }
  106. };
  107. class TActorSystem : TNonCopyable {
  108. struct TServiceMap;
  109. public:
  110. const ui32 NodeId;
  111. private:
  112. THolder<TCpuManager> CpuManager;
  113. const ui32 ExecutorPoolCount;
  114. TAutoPtr<ISchedulerThread> Scheduler;
  115. THolder<TServiceMap> ServiceMap;
  116. const ui32 InterconnectCount;
  117. TArrayHolder<TActorId> Interconnect;
  118. volatile ui64 CurrentTimestamp;
  119. volatile ui64 CurrentMonotonic;
  120. volatile ui64 CurrentIDCounter;
  121. THolder<NSchedulerQueue::TQueueType> ScheduleQueue;
  122. mutable TTicketLock ScheduleLock;
  123. friend class TExecutorThread;
  124. THolder<TActorSystemSetup> SystemSetup;
  125. TActorId DefSelfID;
  126. void* AppData0;
  127. TIntrusivePtr<NLog::TSettings> LoggerSettings0;
  128. TProxyWrapperFactory ProxyWrapperFactory;
  129. TMutex ProxyCreationLock;
  130. bool StartExecuted;
  131. bool StopExecuted;
  132. bool CleanupExecuted;
  133. std::deque<std::function<void()>> DeferredPreStop;
  134. public:
  135. TActorSystem(THolder<TActorSystemSetup>& setup, void* appData = nullptr,
  136. TIntrusivePtr<NLog::TSettings> loggerSettings = TIntrusivePtr<NLog::TSettings>(nullptr));
  137. ~TActorSystem();
  138. void Start();
  139. void Stop();
  140. void Cleanup();
  141. template <ESendingType SendingType = ESendingType::Common>
  142. TActorId Register(IActor* actor, TMailboxType::EType mailboxType = TMailboxType::HTSwap, ui32 executorPool = 0,
  143. ui64 revolvingCounter = 0, const TActorId& parentId = TActorId());
  144. bool MonitorStuckActors() const { return SystemSetup->MonitorStuckActors; }
  145. private:
  146. typedef bool (IExecutorPool::*TEPSendFunction)(TAutoPtr<IEventHandle>& ev);
  147. template <TEPSendFunction EPSpecificSend>
  148. bool GenericSend(TAutoPtr<IEventHandle> ev) const;
  149. public:
  150. template <ESendingType SendingType = ESendingType::Common>
  151. bool Send(TAutoPtr<IEventHandle> ev) const;
  152. bool SpecificSend(TAutoPtr<IEventHandle> ev, ESendingType sendingType) const;
  153. bool SpecificSend(TAutoPtr<IEventHandle> ev) const;
  154. bool Send(const TActorId& recipient, IEventBase* ev, ui32 flags = 0, ui64 cookie = 0) const;
  155. /**
  156. * Schedule one-shot event that will be send at given time point in the future.
  157. *
  158. * @param deadline the wallclock time point in future when event must be send
  159. * @param ev the event to send
  160. * @param cookie cookie that will be piggybacked with event
  161. */
  162. void Schedule(TInstant deadline, TAutoPtr<IEventHandle> ev, ISchedulerCookie* cookie = nullptr) const;
  163. /**
  164. * Schedule one-shot event that will be send at given time point in the future.
  165. *
  166. * @param deadline the monotonic time point in future when event must be send
  167. * @param ev the event to send
  168. * @param cookie cookie that will be piggybacked with event
  169. */
  170. void Schedule(TMonotonic deadline, TAutoPtr<IEventHandle> ev, ISchedulerCookie* cookie = nullptr) const;
  171. /**
  172. * Schedule one-shot event that will be send after given delay.
  173. *
  174. * @param delta the time from now to delay event sending
  175. * @param ev the event to send
  176. * @param cookie cookie that will be piggybacked with event
  177. */
  178. void Schedule(TDuration delta, TAutoPtr<IEventHandle> ev, ISchedulerCookie* cookie = nullptr) const;
  179. /**
  180. * A way to interact with actors from non-actor context.
  181. *
  182. * This method will send the `event` to the `recipient` and then will wait for a response. When response arrives,
  183. * it will be passed to the future. If response is not of type `T`, the future will resolve into an exception.
  184. *
  185. * @tparam T expected response type. Must be derived from `TEventBase`,
  186. * or use `IEventBase` to catch any response.
  187. * @param actorSystem actor system that will be used to register an actor that'll wait for response.
  188. * @param recipient who will get a request.
  189. * @param event a request message.
  190. * @return future that will be resolved when a message from `recipient` arrives.
  191. */
  192. template <typename T>
  193. [[nodiscard]]
  194. NThreading::TFuture<THolder<T>> Ask(TActorId recipient, THolder<IEventBase> event, TDuration timeout = TDuration::Max()) {
  195. if constexpr (std::is_same_v<T, IEventBase>) {
  196. return AskGeneric(Nothing(), recipient, std::move(event), timeout);
  197. } else {
  198. return AskGeneric(T::EventType, recipient, std::move(event), timeout)
  199. .Apply([](const NThreading::TFuture<THolder<IEventBase>>& ev) {
  200. return THolder<T>(static_cast<T*>(const_cast<THolder<IEventBase>&>(ev.GetValueSync()).Release())); // =(
  201. });
  202. }
  203. }
  204. [[nodiscard]]
  205. NThreading::TFuture<THolder<IEventBase>> AskGeneric(
  206. TMaybe<ui32> expectedEventType,
  207. TActorId recipient,
  208. THolder<IEventBase> event,
  209. TDuration timeout);
  210. ui64 AllocateIDSpace(ui64 count);
  211. TActorId InterconnectProxy(ui32 destinationNode) const;
  212. ui32 BroadcastToProxies(const std::function<IEventHandle*(const TActorId&)>&);
  213. void UpdateLinkStatus(ui8 status, ui32 destinationNode);
  214. ui8 LinkStatus(ui32 destinationNode);
  215. TActorId LookupLocalService(const TActorId& x) const;
  216. TActorId RegisterLocalService(const TActorId& serviceId, const TActorId& actorId);
  217. TInstant Timestamp() const {
  218. return TInstant::MicroSeconds(RelaxedLoad(&CurrentTimestamp));
  219. }
  220. TMonotonic Monotonic() const {
  221. return TMonotonic::MicroSeconds(RelaxedLoad(&CurrentMonotonic));
  222. }
  223. template <typename T>
  224. T* AppData() const {
  225. return (T*)AppData0;
  226. }
  227. NLog::TSettings* LoggerSettings() const {
  228. return LoggerSettings0.Get();
  229. }
  230. void GetPoolStats(ui32 poolId, TExecutorPoolStats& poolStats, TVector<TExecutorThreadStats>& statsCopy) const;
  231. THarmonizerStats GetHarmonizerStats() const;
  232. std::optional<ui32> GetPoolThreadsCount(const ui32 poolId) const {
  233. if (!SystemSetup) {
  234. return {};
  235. }
  236. return SystemSetup->GetThreadsOptional(poolId);
  237. }
  238. void DeferPreStop(std::function<void()> fn) {
  239. DeferredPreStop.push_back(std::move(fn));
  240. }
  241. TVector<IExecutorPool*> GetBasicExecutorPools() const {
  242. return CpuManager->GetBasicExecutorPools();
  243. }
  244. };
  245. }