init.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. #include "init.h"
  2. #include "abortable_registry.h"
  3. #include "job_profiler.h"
  4. #include <yt/cpp/mapreduce/http/requests.h>
  5. #include <yt/cpp/mapreduce/interface/config.h>
  6. #include <yt/cpp/mapreduce/interface/init.h>
  7. #include <yt/cpp/mapreduce/interface/operation.h>
  8. #include <yt/cpp/mapreduce/interface/logging/logger.h>
  9. #include <yt/cpp/mapreduce/interface/logging/yt_log.h>
  10. #include <yt/cpp/mapreduce/io/job_reader.h>
  11. #include <yt/cpp/mapreduce/common/helpers.h>
  12. #include <yt/cpp/mapreduce/common/wait_proxy.h>
  13. #include <yt/yt/core/logging/log_manager.h>
  14. #include <yt/yt/core/logging/config.h>
  15. #include <library/cpp/sighandler/async_signals_handler.h>
  16. #include <util/folder/dirut.h>
  17. #include <util/generic/singleton.h>
  18. #include <util/string/builder.h>
  19. #include <util/string/cast.h>
  20. #include <util/string/type.h>
  21. #include <util/system/env.h>
  22. #include <util/system/thread.h>
  23. namespace NYT {
  24. ////////////////////////////////////////////////////////////////////////////////
  25. namespace {
  26. void WriteVersionToLog()
  27. {
  28. YT_LOG_INFO("Wrapper version: %v",
  29. TProcessState::Get()->ClientVersion);
  30. }
  31. static TNode SecureVaultContents; // safe
  32. void InitializeSecureVault()
  33. {
  34. SecureVaultContents = NodeFromYsonString(
  35. GetEnv("YT_SECURE_VAULT", "{}"));
  36. }
  37. }
  38. ////////////////////////////////////////////////////////////////////////////////
  39. const TNode& GetJobSecureVault()
  40. {
  41. return SecureVaultContents;
  42. }
  43. ////////////////////////////////////////////////////////////////////////////////
  44. class TAbnormalTerminator
  45. {
  46. public:
  47. TAbnormalTerminator() = default;
  48. static void SetErrorTerminationHandler()
  49. {
  50. if (Instance().OldHandler_ != nullptr) {
  51. return;
  52. }
  53. Instance().OldHandler_ = std::set_terminate(&TerminateHandler);
  54. SetAsyncSignalFunction(SIGINT, SignalHandler);
  55. SetAsyncSignalFunction(SIGTERM, SignalHandler);
  56. }
  57. private:
  58. static TAbnormalTerminator& Instance()
  59. {
  60. return *Singleton<TAbnormalTerminator>();
  61. }
  62. static void* Invoke(void* opaque)
  63. {
  64. (*reinterpret_cast<std::function<void()>*>(opaque))();
  65. return nullptr;
  66. }
  67. static void TerminateWithTimeout(
  68. const TDuration& timeout,
  69. const std::function<void(void)>& exitFunction,
  70. const TString& logMessage)
  71. {
  72. std::function<void()> threadFun = [=] {
  73. YT_LOG_INFO("%v",
  74. logMessage);
  75. NDetail::TAbortableRegistry::Get()->AbortAllAndBlockForever();
  76. };
  77. TThread thread(TThread::TParams(Invoke, &threadFun).SetName("aborter"));
  78. thread.Start();
  79. thread.Detach();
  80. Sleep(timeout);
  81. exitFunction();
  82. }
  83. static void SignalHandler(int signalNumber)
  84. {
  85. TerminateWithTimeout(
  86. TDuration::Seconds(5),
  87. std::bind(_exit, -signalNumber),
  88. ::TStringBuilder() << "Signal " << signalNumber << " received, aborting transactions. Waiting 5 seconds...");
  89. }
  90. static void TerminateHandler()
  91. {
  92. TerminateWithTimeout(
  93. TDuration::Seconds(5),
  94. [&] {
  95. if (Instance().OldHandler_) {
  96. Instance().OldHandler_();
  97. } else {
  98. abort();
  99. }
  100. },
  101. ::TStringBuilder() << "Terminate called, aborting transactions. Waiting 5 seconds...");
  102. }
  103. private:
  104. std::terminate_handler OldHandler_ = nullptr;
  105. };
  106. ////////////////////////////////////////////////////////////////////////////////
  107. namespace NDetail {
  108. EInitStatus& GetInitStatus()
  109. {
  110. static EInitStatus initStatus = EInitStatus::NotInitialized;
  111. return initStatus;
  112. }
  113. static void ElevateInitStatus(const EInitStatus newStatus) {
  114. NDetail::GetInitStatus() = Max(NDetail::GetInitStatus(), newStatus);
  115. }
  116. NLogging::ELogLevel ToCoreLogLevel(ILogger::ELevel level)
  117. {
  118. switch (level) {
  119. case ILogger::FATAL:
  120. return NLogging::ELogLevel::Fatal;
  121. case ILogger::ERROR:
  122. return NLogging::ELogLevel::Error;
  123. case ILogger::INFO:
  124. return NLogging::ELogLevel::Info;
  125. case ILogger::DEBUG:
  126. return NLogging::ELogLevel::Debug;
  127. }
  128. Y_ABORT();
  129. }
  130. void CommonInitialize(TGuard<TMutex>& g)
  131. {
  132. auto logLevelStr = to_lower(TConfig::Get()->LogLevel);
  133. ILogger::ELevel logLevel;
  134. if (!TryFromString(logLevelStr, logLevel)) {
  135. Cerr << "Invalid log level: " << TConfig::Get()->LogLevel << Endl;
  136. g.Release();
  137. exit(1);
  138. }
  139. auto logPath = TConfig::Get()->LogPath;
  140. if (logPath.empty()) {
  141. auto coreLoggingConfig = NLogging::TLogManagerConfig::CreateStderrLogger(ToCoreLogLevel(logLevel));
  142. for (const auto& rule : coreLoggingConfig->Rules) {
  143. rule->ExcludeCategories = TConfig::Get()->LogExcludeCategories;
  144. }
  145. NLogging::TLogManager::Get()->Configure(coreLoggingConfig);
  146. if (TConfig::Get()->LogUseCore) {
  147. SetUseCoreLog();
  148. } else {
  149. auto logger = CreateStdErrLogger(logLevel);
  150. SetLogger(logger);
  151. }
  152. } else {
  153. auto coreLoggingConfig = NLogging::TLogManagerConfig::CreateLogFile(logPath, ToCoreLogLevel(logLevel));
  154. for (const auto& rule : coreLoggingConfig->Rules) {
  155. rule->ExcludeCategories = TConfig::Get()->LogExcludeCategories;
  156. }
  157. NLogging::TLogManager::Get()->Configure(coreLoggingConfig);
  158. SetUseCoreLog();
  159. }
  160. }
  161. void NonJobInitialize(const TInitializeOptions& options)
  162. {
  163. if (FromString<bool>(GetEnv("YT_CLEANUP_ON_TERMINATION", "0")) || options.CleanupOnTermination_) {
  164. TAbnormalTerminator::SetErrorTerminationHandler();
  165. }
  166. if (options.WaitProxy_) {
  167. NDetail::TWaitProxy::Get()->SetProxy(options.WaitProxy_);
  168. }
  169. WriteVersionToLog();
  170. }
  171. void ExecJob(int argc, const char** argv, const TInitializeOptions& options)
  172. {
  173. // Now we are definitely in job.
  174. // We take this setting from environment variable to be consistent with client code.
  175. TConfig::Get()->UseClientProtobuf = IsTrue(GetEnv("YT_USE_CLIENT_PROTOBUF", ""));
  176. auto execJobImpl = [&options](TString jobName, i64 outputTableCount, bool hasState) {
  177. auto jobProfiler = CreateJobProfiler();
  178. jobProfiler->Start();
  179. InitializeSecureVault();
  180. NDetail::OutputTableCount = static_cast<i64>(outputTableCount);
  181. std::unique_ptr<IInputStream> jobStateStream;
  182. if (hasState) {
  183. jobStateStream = std::make_unique<TIFStream>("jobstate");
  184. } else {
  185. jobStateStream = std::make_unique<TBufferStream>(0);
  186. }
  187. int ret = 1;
  188. try {
  189. ret = TJobFactory::Get()->GetJobFunction(jobName.data())(outputTableCount, *jobStateStream);
  190. } catch (const TSystemError& ex) {
  191. if (ex.Status() == EPIPE) {
  192. // 32 == EPIPE, write number here so it's easier to grep this exit code in source files
  193. exit(32);
  194. }
  195. throw;
  196. }
  197. jobProfiler->Stop();
  198. if (options.JobOnExitFunction_) {
  199. (*options.JobOnExitFunction_)();
  200. }
  201. exit(ret);
  202. };
  203. auto jobArguments = NodeFromYsonString(GetEnv("YT_JOB_ARGUMENTS", "#"));
  204. if (jobArguments.HasValue()) {
  205. execJobImpl(
  206. jobArguments["job_name"].AsString(),
  207. jobArguments["output_table_count"].AsInt64(),
  208. jobArguments["has_state"].AsBool());
  209. Y_UNREACHABLE();
  210. }
  211. TString jobType = argc >= 2 ? argv[1] : TString();
  212. if (argc != 5 || jobType != "--yt-map" && jobType != "--yt-reduce") {
  213. // We are inside job but probably using old API
  214. // (i.e. both NYT::Initialize and NMR::Initialize are called).
  215. WriteVersionToLog();
  216. return;
  217. }
  218. TString jobName(argv[2]);
  219. i64 outputTableCount = FromString<i64>(argv[3]);
  220. int hasState = FromString<int>(argv[4]);
  221. execJobImpl(jobName, outputTableCount, hasState);
  222. Y_UNREACHABLE();
  223. }
  224. void EnsureInitialized()
  225. {
  226. if (GetInitStatus() == EInitStatus::NotInitialized) {
  227. JoblessInitialize();
  228. }
  229. }
  230. } // namespace NDetail
  231. ////////////////////////////////////////////////////////////////////////////////
  232. static TMutex InitializeLock;
  233. void JoblessInitialize(const TInitializeOptions& options)
  234. {
  235. auto g = Guard(InitializeLock);
  236. NDetail::CommonInitialize(g);
  237. NDetail::NonJobInitialize(options);
  238. NDetail::ElevateInitStatus(NDetail::EInitStatus::JoblessInitialization);
  239. }
  240. void Initialize(int argc, const char* argv[], const TInitializeOptions& options)
  241. {
  242. auto g = Guard(InitializeLock);
  243. NDetail::CommonInitialize(g);
  244. NDetail::ElevateInitStatus(NDetail::EInitStatus::FullInitialization);
  245. const bool isInsideJob = !GetEnv("YT_JOB_ID").empty();
  246. if (isInsideJob) {
  247. g.Release();
  248. NDetail::ExecJob(argc, argv, options);
  249. } else {
  250. NDetail::NonJobInitialize(options);
  251. }
  252. }
  253. void Initialize(int argc, char* argv[], const TInitializeOptions& options)
  254. {
  255. return Initialize(argc, const_cast<const char**>(argv), options);
  256. }
  257. void Initialize(const TInitializeOptions& options)
  258. {
  259. static const char* fakeArgv[] = {"unknown..."};
  260. Initialize(1, fakeArgv, options);
  261. }
  262. ////////////////////////////////////////////////////////////////////////////////
  263. } // namespace NYT