init.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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(int, const char**)
  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. exit(1);
  137. }
  138. auto logPath = TConfig::Get()->LogPath;
  139. ILoggerPtr logger;
  140. if (logPath.empty()) {
  141. logger = CreateStdErrLogger(logLevel);
  142. } else {
  143. logger = CreateFileLogger(logLevel, logPath, /*append*/ true);
  144. auto coreLoggingConfig = NLogging::TLogManagerConfig::CreateLogFile(logPath, ToCoreLogLevel(logLevel));
  145. NLogging::TLogManager::Get()->Configure(coreLoggingConfig);
  146. }
  147. SetLogger(logger);
  148. }
  149. void NonJobInitialize(const TInitializeOptions& options)
  150. {
  151. if (FromString<bool>(GetEnv("YT_CLEANUP_ON_TERMINATION", "0")) || options.CleanupOnTermination_) {
  152. TAbnormalTerminator::SetErrorTerminationHandler();
  153. }
  154. if (options.WaitProxy_) {
  155. NDetail::TWaitProxy::Get()->SetProxy(options.WaitProxy_);
  156. }
  157. WriteVersionToLog();
  158. }
  159. void ExecJob(int argc, const char** argv, const TInitializeOptions& options)
  160. {
  161. // Now we are definitely in job.
  162. // We take this setting from environment variable to be consistent with client code.
  163. TConfig::Get()->UseClientProtobuf = IsTrue(GetEnv("YT_USE_CLIENT_PROTOBUF", ""));
  164. auto execJobImpl = [&options](TString jobName, i64 outputTableCount, bool hasState) {
  165. auto jobProfiler = CreateJobProfiler();
  166. jobProfiler->Start();
  167. InitializeSecureVault();
  168. NDetail::OutputTableCount = static_cast<i64>(outputTableCount);
  169. THolder<IInputStream> jobStateStream;
  170. if (hasState) {
  171. jobStateStream = MakeHolder<TIFStream>("jobstate");
  172. } else {
  173. jobStateStream = MakeHolder<TBufferStream>(0);
  174. }
  175. int ret = 1;
  176. try {
  177. ret = TJobFactory::Get()->GetJobFunction(jobName.data())(outputTableCount, *jobStateStream);
  178. } catch (const TSystemError& ex) {
  179. if (ex.Status() == EPIPE) {
  180. // 32 == EPIPE, write number here so it's easier to grep this exit code in source files
  181. exit(32);
  182. }
  183. throw;
  184. }
  185. jobProfiler->Stop();
  186. if (options.JobOnExitFunction_) {
  187. (*options.JobOnExitFunction_)();
  188. }
  189. exit(ret);
  190. };
  191. auto jobArguments = NodeFromYsonString(GetEnv("YT_JOB_ARGUMENTS", "#"));
  192. if (jobArguments.HasValue()) {
  193. execJobImpl(
  194. jobArguments["job_name"].AsString(),
  195. jobArguments["output_table_count"].AsInt64(),
  196. jobArguments["has_state"].AsBool());
  197. Y_UNREACHABLE();
  198. }
  199. TString jobType = argc >= 2 ? argv[1] : TString();
  200. if (argc != 5 || jobType != "--yt-map" && jobType != "--yt-reduce") {
  201. // We are inside job but probably using old API
  202. // (i.e. both NYT::Initialize and NMR::Initialize are called).
  203. WriteVersionToLog();
  204. return;
  205. }
  206. TString jobName(argv[2]);
  207. i64 outputTableCount = FromString<i64>(argv[3]);
  208. int hasState = FromString<int>(argv[4]);
  209. execJobImpl(jobName, outputTableCount, hasState);
  210. Y_UNREACHABLE();
  211. }
  212. void EnsureInitialized()
  213. {
  214. if (GetInitStatus() == EInitStatus::NotInitialized) {
  215. JoblessInitialize();
  216. }
  217. }
  218. } // namespace NDetail
  219. ////////////////////////////////////////////////////////////////////////////////
  220. static TMutex InitializeLock;
  221. void JoblessInitialize(const TInitializeOptions& options)
  222. {
  223. auto g = Guard(InitializeLock);
  224. static const char* fakeArgv[] = {"unknown..."};
  225. NDetail::CommonInitialize(1, fakeArgv);
  226. NDetail::NonJobInitialize(options);
  227. NDetail::ElevateInitStatus(NDetail::EInitStatus::JoblessInitialization);
  228. }
  229. void Initialize(int argc, const char* argv[], const TInitializeOptions& options)
  230. {
  231. auto g = Guard(InitializeLock);
  232. NDetail::CommonInitialize(argc, argv);
  233. NDetail::ElevateInitStatus(NDetail::EInitStatus::FullInitialization);
  234. const bool isInsideJob = !GetEnv("YT_JOB_ID").empty();
  235. if (isInsideJob) {
  236. g.Release();
  237. NDetail::ExecJob(argc, argv, options);
  238. } else {
  239. NDetail::NonJobInitialize(options);
  240. }
  241. }
  242. void Initialize(int argc, char* argv[], const TInitializeOptions& options)
  243. {
  244. return Initialize(argc, const_cast<const char**>(argv), options);
  245. }
  246. void Initialize(const TInitializeOptions& options)
  247. {
  248. static const char* fakeArgv[] = {"unknown..."};
  249. Initialize(1, fakeArgv, options);
  250. }
  251. ////////////////////////////////////////////////////////////////////////////////
  252. } // namespace NYT