jthread.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jthread.hpp"
  14. #include "jlib.hpp"
  15. #include "jfile.hpp"
  16. #include "jmutex.hpp"
  17. #include "jexcept.hpp"
  18. #include "jmisc.hpp"
  19. #include "jqueue.tpp"
  20. #include "jregexp.hpp"
  21. #include <assert.h>
  22. #ifdef _WIN32
  23. #include <process.h>
  24. #else
  25. #include <unistd.h>
  26. #include <sys/wait.h>
  27. #include <sys/syscall.h>
  28. #include <sys/types.h>
  29. #include <sys/resource.h>
  30. #endif
  31. #define LINUX_STACKSIZE_CAP (0x200000)
  32. //#define NO_CATCHALL
  33. //static __thread ThreadTermFunc threadTerminationHook;
  34. static thread_local std::vector<ThreadTermFunc> threadTermHooks;
  35. void addThreadTermFunc(ThreadTermFunc onTerm)
  36. {
  37. for (auto hook: threadTermHooks)
  38. {
  39. if (hook==onTerm)
  40. return;
  41. }
  42. threadTermHooks.push_back(onTerm);
  43. }
  44. void callThreadTerminationHooks(bool isPooled)
  45. {
  46. std::vector<ThreadTermFunc> keepHooks;
  47. for (auto hook: threadTermHooks)
  48. {
  49. if ((*hook)(isPooled) && isPooled)
  50. keepHooks.push_back(hook);
  51. }
  52. threadTermHooks.swap(keepHooks);
  53. }
  54. PointerArray *exceptionHandlers = NULL;
  55. MODULE_INIT(INIT_PRIORITY_JTHREAD)
  56. {
  57. exceptionHandlers = new PointerArray();
  58. return true;
  59. }
  60. MODULE_EXIT()
  61. {
  62. for (auto hook: threadTermHooks)
  63. {
  64. (*hook)(false); // May be too late :(
  65. }
  66. delete exceptionHandlers;
  67. }
  68. void addThreadExceptionHandler(IExceptionHandler *handler)
  69. {
  70. assertex(exceptionHandlers); // have to ensure MODULE_INIT has appropriate priority.
  71. exceptionHandlers->append(handler);
  72. }
  73. void removeThreadExceptionHandler(IExceptionHandler *handler)
  74. {
  75. exceptionHandlers->zap(handler);
  76. }
  77. static bool SEHHandling = false;
  78. void enableThreadSEH() { SEHHandling=true; }
  79. void disableThreadSEH() { SEHHandling=false; } // only prevents new threads from having SEH handler, no mech. for turning off existing threads SEH handling.
  80. static ICopyArrayOf<Thread> ThreadList;
  81. static CriticalSection ThreadListSem;
  82. static size32_t defaultThreadStackSize=0;
  83. static ICopyArrayOf<Thread> ThreadDestroyList;
  84. static SpinLock ThreadDestroyListLock;
  85. #ifdef _WIN32
  86. extern void *EnableSEHtranslation();
  87. unsigned WINAPI Thread::_threadmain(LPVOID v)
  88. #else
  89. void *Thread::_threadmain(void *v)
  90. #endif
  91. {
  92. Thread * t = (Thread *)v;
  93. #ifdef _WIN32
  94. if (SEHHandling)
  95. EnableSEHtranslation();
  96. #else
  97. t->tidlog = threadLogID();
  98. #endif
  99. int ret = t->begin();
  100. char *&threadname = t->cthreadname.threadname;
  101. if (threadname) {
  102. memsize_t l=strlen(threadname);
  103. char *newname = (char *)malloc(l+8+1);
  104. memcpy(newname,"Stopped ",8);
  105. memcpy(newname+8,threadname,l+1);
  106. char *oldname = threadname;
  107. threadname = newname;
  108. free(oldname);
  109. }
  110. {
  111. // need to ensure joining thread does not race with us to release
  112. t->Link(); // extra safety link
  113. {
  114. SpinBlock block(ThreadDestroyListLock);
  115. ThreadDestroyList.append(*t);
  116. }
  117. try {
  118. t->stopped.signal();
  119. if (t->Release()) {
  120. PROGLOG("extra unlinked thread");
  121. PrintStackReport();
  122. }
  123. else
  124. t->Release();
  125. }
  126. catch (...) {
  127. PROGLOG("thread release exception");
  128. throw;
  129. }
  130. {
  131. SpinBlock block(ThreadDestroyListLock);
  132. ThreadDestroyList.zap(*t); // hopefully won't get too big (i.e. one entry!)
  133. }
  134. }
  135. #if defined(_WIN32)
  136. return ret;
  137. #else
  138. return (void *) (memsize_t)ret;
  139. #endif
  140. }
  141. // JCSMORE - should have a setPriority(), unsupported under _WIN32
  142. void Thread::adjustPriority(int delta)
  143. {
  144. if (delta < -2)
  145. prioritydelta = -2;
  146. else if (delta > 2)
  147. prioritydelta = 2;
  148. else
  149. prioritydelta = delta;
  150. if (alive)
  151. {
  152. #if defined(_WIN32)
  153. int priority;
  154. switch (delta)
  155. {
  156. case -2: priority = THREAD_PRIORITY_LOWEST; break;
  157. case -1: priority = THREAD_PRIORITY_BELOW_NORMAL; break;
  158. case 0: priority = THREAD_PRIORITY_NORMAL; break;
  159. case +1: priority = THREAD_PRIORITY_ABOVE_NORMAL; break;
  160. case +2: priority = THREAD_PRIORITY_HIGHEST; break;
  161. }
  162. SetThreadPriority(hThread, priority);
  163. #else
  164. //MORE - What control is there?
  165. int policy;
  166. sched_param param;
  167. int rc;
  168. if (( rc = pthread_getschedparam(threadid, &policy, &param)) != 0)
  169. DBGLOG("pthread_getschedparam error: %d", rc);
  170. switch (delta)
  171. {
  172. // JCS - doubtful whether these good values...
  173. case -2: param.sched_priority = 0; policy =SCHED_OTHER; break;
  174. case -1: param.sched_priority = 0; policy =SCHED_OTHER; break;
  175. case 0: param.sched_priority = 0; policy =SCHED_OTHER; break;
  176. case +1: param.sched_priority = (sched_get_priority_max(SCHED_RR)-sched_get_priority_min(SCHED_RR))/2; policy =SCHED_RR; break;
  177. case +2: param.sched_priority = sched_get_priority_max(SCHED_RR); policy =SCHED_RR; break;
  178. }
  179. if(( rc = pthread_setschedparam(threadid, policy, &param)) != 0)
  180. DBGLOG("pthread_setschedparam error: %d policy=%i pr=%i id=%" I64F "u PID=%i", rc,policy,param.sched_priority,(unsigned __int64) threadid,getpid());
  181. else
  182. DBGLOG("priority set id=%" I64F "u policy=%i pri=%i PID=%i",(unsigned __int64) threadid,policy,param.sched_priority,getpid());
  183. #endif
  184. }
  185. }
  186. void Thread::adjustNiceLevel()
  187. {
  188. #if defined(_WIN32)
  189. int priority;
  190. if(nicelevel < -15)
  191. priority = THREAD_PRIORITY_TIME_CRITICAL;
  192. else if(nicelevel >= -15 && nicelevel < -10)
  193. priority = THREAD_PRIORITY_HIGHEST;
  194. else if(nicelevel >= -10 && nicelevel < 0)
  195. priority = THREAD_PRIORITY_ABOVE_NORMAL;
  196. else if(nicelevel == 0)
  197. priority = THREAD_PRIORITY_NORMAL;
  198. else if(nicelevel > 0 && nicelevel <= 10)
  199. priority = THREAD_PRIORITY_BELOW_NORMAL;
  200. else if(nicelevel > 10 && nicelevel <= 15)
  201. priority = THREAD_PRIORITY_LOWEST;
  202. else if(nicelevel >15)
  203. priority = THREAD_PRIORITY_IDLE;
  204. SetThreadPriority(hThread, priority);
  205. #elif defined(__linux__)
  206. setpriority(PRIO_PROCESS, 0, nicelevel);
  207. #else
  208. UNIMPLEMENTED;
  209. #endif
  210. }
  211. bool Thread::isCurrentThread() const
  212. {
  213. return GetCurrentThreadId() == threadid;
  214. }
  215. // _nicelevel ranges from -20 to 19, the higher the nice level, the less cpu time the thread will get.
  216. void Thread::setNice(int _nicelevel)
  217. {
  218. if (_nicelevel < -20 || _nicelevel > 19)
  219. throw MakeStringException(0, "nice level should be between -20 and 19");
  220. if(alive)
  221. throw MakeStringException(0, "nice can only be set before the thread is started.");
  222. nicelevel = _nicelevel;
  223. }
  224. void Thread::setStackSize(size32_t size)
  225. {
  226. stacksize = (unsigned short)(size/0x1000);
  227. }
  228. void Thread::setDefaultStackSize(size32_t size)
  229. {
  230. defaultThreadStackSize = size; // has no effect under windows (though may be used for calculations later)
  231. }
  232. int Thread::begin()
  233. {
  234. if(nicelevel)
  235. adjustNiceLevel();
  236. #ifndef _WIN32
  237. starting.signal();
  238. suspend.wait();
  239. #endif
  240. int ret=-1;
  241. try {
  242. ret = run();
  243. }
  244. catch (IException *e)
  245. {
  246. handleException(e);
  247. }
  248. #ifndef NO_CATCHALL
  249. catch (...)
  250. {
  251. handleException(MakeStringException(0, "Unknown exception in Thread %s", getName()));
  252. }
  253. #endif
  254. callThreadTerminationHooks(false);
  255. #ifdef _WIN32
  256. #ifndef _DEBUG
  257. CloseHandle(hThread); // leak handle when debugging,
  258. // fixes some lockups/crashes in the debugger when lots of threads being created
  259. #endif
  260. hThread = NULL;
  261. #endif
  262. //alive = false; // not safe here
  263. return ret;
  264. }
  265. void Thread::handleException(IException *e)
  266. {
  267. assertex(exceptionHandlers);
  268. if (exceptionHandlers->ordinality() == 0)
  269. {
  270. PrintExceptionLog(e,getName());
  271. //throw; // don't rethrow unhandled, preferable over alternative of causing process death
  272. e->Release();
  273. }
  274. else
  275. {
  276. PrintExceptionLog(e,getName());
  277. bool handled = false;
  278. ForEachItemIn(ie, *exceptionHandlers)
  279. {
  280. IExceptionHandler *handler = (IExceptionHandler *) exceptionHandlers->item(ie);
  281. handled = handler->fireException(e) || handled;
  282. }
  283. if (!handled)
  284. {
  285. // if nothing choose to handle it.
  286. EXCLOG(e, NULL);
  287. //throw e; // don't rethrow unhandled, preferable over alternative of causing process death
  288. }
  289. e->Release();
  290. }
  291. }
  292. void Thread::init(const char *_name)
  293. {
  294. #ifdef _WIN32
  295. hThread = NULL;
  296. #endif
  297. threadid = 0;
  298. tidlog = 0;
  299. alive = false;
  300. cthreadname.threadname = (NULL == _name) ? NULL : strdup(_name);
  301. ithreadname = &cthreadname;
  302. prioritydelta = 0;
  303. nicelevel = 0;
  304. stacksize = 0; // default is EXE default stack size (set by /STACK)
  305. }
  306. void Thread::start()
  307. {
  308. if (alive) {
  309. IWARNLOG("Thread::start(%s) - Thread already started!",getName());
  310. PrintStackReport();
  311. #ifdef _DEBUG
  312. throw MakeStringException(-1,"Thread::start(%s) - Thread already started!",getName());
  313. #endif
  314. return;
  315. }
  316. Link();
  317. startRelease();
  318. }
  319. void Thread::startRelease()
  320. {
  321. assertex(!alive);
  322. stopped.reinit(0); // just in case restarting
  323. #ifdef _WIN32
  324. hThread = (HANDLE)_beginthreadex(NULL, 0x1000*(unsigned)stacksize, Thread::_threadmain, this, CREATE_SUSPENDED, (unsigned *)&threadid);
  325. if (!hThread || !threadid)
  326. {
  327. Release();
  328. throw makeOsException(GetLastError());
  329. }
  330. #else
  331. int status;
  332. unsigned numretrys = 8;
  333. unsigned delay = 1000;
  334. for (;;) {
  335. pthread_attr_t attr;
  336. pthread_attr_init(&attr);
  337. pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
  338. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  339. if (stacksize)
  340. pthread_attr_setstacksize(&attr, (unsigned)stacksize*0x1000);
  341. else if (defaultThreadStackSize)
  342. pthread_attr_setstacksize(&attr, defaultThreadStackSize);
  343. else {
  344. #ifndef __64BIT__ // no need to cap 64bit
  345. size_t defss=0;
  346. pthread_attr_getstacksize(&attr, &defss);
  347. if (defss>LINUX_STACKSIZE_CAP)
  348. pthread_attr_setstacksize(&attr, LINUX_STACKSIZE_CAP);
  349. #endif
  350. }
  351. status = pthread_create(&threadid, &attr, Thread::_threadmain, this);
  352. if ((status==EAGAIN)||(status==EINTR)) {
  353. if (numretrys--==0)
  354. break;
  355. IWARNLOG("pthread_create(%d): Out of threads, retrying...",status);
  356. Sleep(delay);
  357. delay *= 2;
  358. }
  359. else
  360. break;
  361. }
  362. if (status) {
  363. threadid = 0;
  364. Release();
  365. IERRLOG("pthread_create returns %d",status);
  366. PrintStackReport();
  367. PrintMemoryReport();
  368. StringBuffer s;
  369. getThreadList(s);
  370. IERRLOG("Running threads:\n %s",s.str());
  371. throw makeOsException(status);
  372. }
  373. unsigned retryCount = 10;
  374. for (;;)
  375. {
  376. if (starting.wait(1000*10))
  377. break;
  378. else if (0 == --retryCount)
  379. throw MakeStringException(-1, "Thread::start(%s) failed", getName());
  380. IWARNLOG("Thread::start(%s) stalled, waiting to start, retrying", getName());
  381. }
  382. #endif
  383. alive = true;
  384. if (prioritydelta)
  385. adjustPriority(prioritydelta);
  386. {
  387. CriticalBlock block(ThreadListSem);
  388. ThreadList.zap(*this); // just in case restarting
  389. ThreadList.append(*this);
  390. }
  391. #ifdef _WIN32
  392. DWORD count = ResumeThread(hThread);
  393. assertex(count == 1);
  394. #else
  395. suspend.signal();
  396. #endif
  397. }
  398. bool Thread::join(unsigned timeout)
  399. {
  400. if (!alive&&!threadid) {
  401. #ifdef _DEBUG
  402. PROGLOG("join on unstarted thread!");
  403. PrintStackReport();
  404. #endif
  405. return true;
  406. }
  407. if (!stopped.wait(timeout))
  408. return false;
  409. if (!alive) // already joined
  410. {
  411. stopped.signal();
  412. return true;
  413. }
  414. unsigned st = 0;
  415. for (;;) { // this is to prevent race with destroy
  416. // (because Thread objects are not always link counted!)
  417. {
  418. SpinBlock block(ThreadDestroyListLock);
  419. if (ThreadDestroyList.find(*this)==NotFound)
  420. break;
  421. }
  422. #ifdef _DEBUG
  423. if (st==10)
  424. PROGLOG("Thread::join race");
  425. #endif
  426. Sleep(st); // switch back to exiting thread (not very elegant!)
  427. st++;
  428. if (st>10)
  429. st = 10; // note must be non-zero for high priority threads
  430. }
  431. #ifdef _DEBUG
  432. int c = getLinkCount();
  433. if (c>=DEAD_PSEUDO_COUNT) {
  434. PROGLOG("Dead/Dying thread joined! %d",c);
  435. PrintStackReport();
  436. }
  437. #endif
  438. alive = false; // should be safe here
  439. stopped.signal(); // signal stopped again, to prevent any parallel call from blocking.
  440. return true;
  441. }
  442. Thread::~Thread()
  443. {
  444. ithreadname = &cthreadname; // safer (as derived classes destroyed)
  445. #ifdef _DEBUG
  446. if (alive) {
  447. if (!stopped.wait(0)) { // see if fell out of threadmain and signal stopped
  448. PROGLOG("Live thread killed! %s",getName());
  449. PrintStackReport();
  450. }
  451. // don't need to resignal as we are on way out
  452. }
  453. #endif
  454. Link();
  455. // DBGLOG("Thread %x (%s) destroyed\n", threadid, threadname);
  456. {
  457. CriticalBlock block(ThreadListSem);
  458. ThreadList.zap(*this);
  459. }
  460. free(cthreadname.threadname);
  461. cthreadname.threadname = NULL;
  462. }
  463. unsigned getThreadCount()
  464. {
  465. CriticalBlock block(ThreadListSem);
  466. return ThreadList.ordinality();
  467. }
  468. StringBuffer & getThreadList(StringBuffer &str)
  469. {
  470. CriticalBlock block(ThreadListSem);
  471. ForEachItemIn(i,ThreadList) {
  472. Thread &item=ThreadList.item(i);
  473. item.getInfo(str).append("\n");
  474. }
  475. return str;
  476. }
  477. StringBuffer &getThreadName(int thandle,unsigned tid,StringBuffer &name)
  478. {
  479. CriticalBlock block(ThreadListSem);
  480. bool found=false;
  481. ForEachItemIn(i,ThreadList) {
  482. Thread &item=ThreadList.item(i);
  483. int h;
  484. unsigned t;
  485. const char *s = item.getLogInfo(h,t);
  486. if (s&&*s&&((thandle==0)||(h==thandle))&&((tid==0)||(t==tid))) {
  487. if (found) {
  488. name.clear();
  489. break; // only return if unambiguous
  490. }
  491. name.append(s);
  492. found = true;
  493. }
  494. }
  495. return name;
  496. }
  497. // CThreadedPersistent
  498. CThreadedPersistent::CThreadedPersistent(const char *name, IThreaded *_owner) : athread(*this, name), owner(_owner), state(s_ready)
  499. {
  500. halt = false;
  501. athread.start();
  502. }
  503. CThreadedPersistent::~CThreadedPersistent()
  504. {
  505. join(INFINITE, false);
  506. halt = true;
  507. sem.signal();
  508. athread.join();
  509. }
  510. void CThreadedPersistent::threadmain()
  511. {
  512. for (;;)
  513. {
  514. sem.wait();
  515. if (halt)
  516. break;
  517. try
  518. {
  519. owner->threadmain();
  520. // Note we do NOT call the thread reset hook here - these threads are expected to be able to preserve state, I think
  521. }
  522. catch (IException *e)
  523. {
  524. VStringBuffer errMsg("CThreadedPersistent (%s)", athread.getName());
  525. EXCLOG(e, errMsg.str());
  526. exception.setown(e);
  527. joinSem.signal(); // leave in running state, signal to join to handle
  528. continue;
  529. }
  530. unsigned expected = s_running;
  531. if (!state.compare_exchange_strong(expected, s_ready))
  532. {
  533. expected = s_joining;
  534. if (state.compare_exchange_strong(expected, s_ready))
  535. joinSem.signal();
  536. }
  537. }
  538. }
  539. void CThreadedPersistent::start()
  540. {
  541. unsigned expected = s_ready;
  542. if (!state.compare_exchange_strong(expected, s_running))
  543. {
  544. VStringBuffer msg("CThreadedPersistent::start(%s) - not ready", athread.getName());
  545. IWARNLOG("%s", msg.str());
  546. PrintStackReport();
  547. throw MakeStringExceptionDirect(-1, msg.str());
  548. }
  549. sem.signal();
  550. }
  551. bool CThreadedPersistent::join(unsigned timeout, bool throwException)
  552. {
  553. unsigned expected = s_running;
  554. if (state.compare_exchange_strong(expected, s_joining))
  555. {
  556. if (!joinSem.wait(timeout))
  557. {
  558. unsigned expected = s_joining;
  559. if (state.compare_exchange_strong(expected, s_running)) // if still joining, restore running state
  560. return false;
  561. // if here, threadmain() set s_ready after timeout and has or will signal
  562. if (!joinSem.wait(60000) && throwException) // should be instant
  563. throwUnexpected();
  564. return true;
  565. }
  566. if (throwException && exception.get())
  567. {
  568. // switch back to ready state and throw
  569. Owned<IException> e = exception.getClear();
  570. unsigned expected = s_joining;
  571. if (!state.compare_exchange_strong(expected, s_ready))
  572. throwUnexpected();
  573. throw e.getClear();
  574. }
  575. }
  576. return true;
  577. }
  578. //class CAsyncFor
  579. void CAsyncFor::For(unsigned num,unsigned maxatonce,bool abortFollowingException, bool shuffled)
  580. {
  581. if (num <= 1)
  582. {
  583. if (num == 1)
  584. Do(0);
  585. return;
  586. }
  587. Mutex errmutex;
  588. IException *e=NULL;
  589. Owned<IShuffledIterator> shuffler;
  590. if (shuffled) {
  591. shuffler.setown(createShuffledIterator(num));
  592. shuffler->first(); // prime (needed to make thread safe)
  593. }
  594. unsigned i;
  595. if (maxatonce==1) { // no need for threads
  596. for (i=0;i<num;i++) {
  597. unsigned idx = shuffled?shuffler->lookup(i):i;
  598. try {
  599. Do(idx);
  600. }
  601. catch (IException * _e)
  602. {
  603. if (e)
  604. _e->Release(); // only return first
  605. else
  606. e = _e;
  607. if (abortFollowingException)
  608. break;
  609. }
  610. }
  611. }
  612. else {
  613. if (maxatonce==0 || maxatonce > num)
  614. maxatonce = num;
  615. if (maxatonce < num)
  616. {
  617. class cdothread: public Thread
  618. {
  619. public:
  620. Mutex *errmutex;
  621. Semaphore &ready;
  622. IException *&erre;
  623. unsigned idx;
  624. CAsyncFor *self;
  625. cdothread(CAsyncFor *_self,unsigned _idx,Semaphore &_ready,Mutex *_errmutex,IException *&_e)
  626. : Thread("CAsyncFor"),ready(_ready),erre(_e)
  627. {
  628. errmutex =_errmutex;
  629. idx = _idx;
  630. self = _self;
  631. }
  632. int run()
  633. {
  634. try {
  635. self->Do(idx);
  636. }
  637. catch (IException * _e)
  638. {
  639. synchronized block(*errmutex);
  640. if (erre)
  641. _e->Release(); // only return first
  642. else
  643. erre = _e;
  644. }
  645. #ifndef NO_CATCHALL
  646. catch (...)
  647. {
  648. synchronized block(*errmutex);
  649. if (!erre)
  650. erre = MakeStringException(0, "Unknown exception in Thread %s", getName());
  651. }
  652. #endif
  653. ready.signal();
  654. return 0;
  655. }
  656. };
  657. Semaphore ready;
  658. for (i=0;(i<num)&&(i<maxatonce);i++)
  659. ready.signal();
  660. IArrayOf<Thread> started;
  661. started.ensure(num);
  662. for (i=0;i<num;i++) {
  663. ready.wait();
  664. if (abortFollowingException && e) break;
  665. Owned<Thread> thread = new cdothread(this,shuffled?shuffler->lookup(i):i,ready,&errmutex,e);
  666. thread->start();
  667. started.append(*thread.getClear());
  668. }
  669. ForEachItemIn(idx, started)
  670. {
  671. started.item(idx).join();
  672. }
  673. }
  674. else
  675. {
  676. // Common case of execute all at once can be optimized a little
  677. // Note that shuffle and abortFollowingException are meaningless when executing all at once
  678. class cdothread: public Thread
  679. {
  680. public:
  681. Mutex *errmutex;
  682. IException *&erre;
  683. unsigned idx;
  684. CAsyncFor *self;
  685. cdothread(CAsyncFor *_self,unsigned _idx,Mutex *_errmutex,IException *&_e)
  686. : Thread("CAsyncFor"),erre(_e)
  687. {
  688. errmutex =_errmutex;
  689. idx = _idx;
  690. self = _self;
  691. }
  692. int run()
  693. {
  694. try {
  695. self->Do(idx);
  696. }
  697. catch (IException * _e)
  698. {
  699. synchronized block(*errmutex);
  700. if (erre)
  701. _e->Release(); // only return first
  702. else
  703. erre = _e;
  704. }
  705. #ifndef NO_CATCHALL
  706. catch (...)
  707. {
  708. synchronized block(*errmutex);
  709. if (!erre)
  710. erre = MakeStringException(0, "Unknown exception in Thread %s", getName());
  711. }
  712. #endif
  713. return 0;
  714. }
  715. };
  716. IArrayOf<Thread> started;
  717. started.ensure(num);
  718. for (i=0;i<num-1;i++)
  719. {
  720. Owned<Thread> thread = new cdothread(this,i,&errmutex,e);
  721. thread->start();
  722. started.append(*thread.getClear());
  723. }
  724. Do(num-1);
  725. ForEachItemIn(idx, started)
  726. {
  727. started.item(idx).join();
  728. }
  729. }
  730. }
  731. if (e)
  732. throw e;
  733. }
  734. //---------------------------------------------------------------------------------------------------------------------
  735. class CSimpleFunctionThread : public Thread
  736. {
  737. std::function<void()> func;
  738. public:
  739. inline CSimpleFunctionThread(std::function<void()> _func) : Thread("TaskProcessor"), func(_func) { }
  740. virtual int run()
  741. {
  742. func();
  743. return 1;
  744. }
  745. };
  746. void asyncStart(IThreaded & threaded)
  747. {
  748. CThreaded * thread = new CThreaded("AsyncStart", &threaded);
  749. thread->startRelease();
  750. }
  751. void asyncStart(const char * name, IThreaded & threaded)
  752. {
  753. CThreaded * thread = new CThreaded(name, &threaded);
  754. thread->startRelease();
  755. }
  756. //Experimental - is this a useful function to replace some uses of IThreaded?
  757. void asyncStart(std::function<void()> func)
  758. {
  759. (new CSimpleFunctionThread(func))->startRelease();
  760. }
  761. // ---------------------------------------------------------------------------
  762. // Thread Pools
  763. // ---------------------------------------------------------------------------
  764. class CPooledThreadWrapper;
  765. class CThreadPoolBase
  766. {
  767. public:
  768. virtual ~CThreadPoolBase() {}
  769. protected: friend class CPooledThreadWrapper;
  770. IExceptionHandler *exceptionHandler;
  771. CriticalSection crit;
  772. StringAttr poolname;
  773. int donewaiting;
  774. Semaphore donesem;
  775. PointerArray waitingsems;
  776. UnsignedArray waitingids;
  777. bool stopall;
  778. unsigned defaultmax;
  779. unsigned targetpoolsize;
  780. unsigned delay;
  781. Semaphore availsem;
  782. std::atomic_uint numrunning{0};
  783. virtual void notifyStarted(CPooledThreadWrapper *item)=0;
  784. virtual bool notifyStopped(CPooledThreadWrapper *item)=0;
  785. };
  786. class CPooledThreadWrapper: public Thread
  787. {
  788. PooledThreadHandle handle;
  789. IPooledThread *thread;
  790. Semaphore sem;
  791. CThreadPoolBase &parent;
  792. char *runningname;
  793. public:
  794. CPooledThreadWrapper(CThreadPoolBase &_parent,
  795. PooledThreadHandle _handle,
  796. IPooledThread *_thread) // takes ownership of thread
  797. : Thread(StringBuffer("Member of thread pool: ").append(_parent.poolname).str()), parent(_parent)
  798. {
  799. thread = _thread;
  800. handle = _handle;
  801. runningname = strdup(_parent.poolname);
  802. }
  803. ~CPooledThreadWrapper()
  804. {
  805. thread->Release();
  806. free(runningname);
  807. }
  808. void setName(const char *name) { free(runningname); runningname=strdup(name); }
  809. void setHandle(PooledThreadHandle _handle) { handle = _handle; }
  810. PooledThreadHandle queryHandle() { return handle; }
  811. IPooledThread &queryThread() { return *thread; }
  812. void setThread(IPooledThread *_thread) { thread = _thread; } // takes ownership
  813. bool isStopped() { return (handle==0); }
  814. PooledThreadHandle markStopped()
  815. {
  816. PooledThreadHandle ret=handle;
  817. handle = 0;
  818. if (ret) // JCSMORE - I can't see how handle can not be set if here..
  819. parent.numrunning--;
  820. return ret;
  821. }
  822. void markStarted()
  823. {
  824. parent.numrunning++;
  825. }
  826. int run()
  827. {
  828. do
  829. {
  830. sem.wait();
  831. {
  832. CriticalBlock block(parent.crit); // to synchronize
  833. if (parent.stopall)
  834. break;
  835. }
  836. parent.notifyStarted(this);
  837. try
  838. {
  839. char *&threadname = cthreadname.threadname;
  840. char *temp = threadname; // swap running name and threadname
  841. threadname = runningname;
  842. runningname = temp;
  843. thread->threadmain();
  844. temp = threadname; // and back
  845. threadname = runningname;
  846. runningname = temp;
  847. }
  848. catch (IException *e)
  849. {
  850. char *&threadname = cthreadname.threadname;
  851. char *temp = threadname; // swap back
  852. threadname = runningname;
  853. runningname = temp;
  854. handleException(e);
  855. }
  856. #ifndef NO_CATCHALL
  857. catch (...)
  858. {
  859. char *&threadname = cthreadname.threadname;
  860. char *temp = threadname; // swap back
  861. threadname = runningname;
  862. runningname = temp;
  863. handleException(MakeStringException(0, "Unknown exception in Thread from pool %s", parent.poolname.get()));
  864. }
  865. #endif
  866. callThreadTerminationHooks(true); // Reset any per-thread state.
  867. } while (parent.notifyStopped(this));
  868. return 0;
  869. }
  870. void cycle()
  871. {
  872. sem.signal();
  873. }
  874. void go(void *param)
  875. {
  876. thread->init(param);
  877. cycle();
  878. }
  879. bool stop()
  880. {
  881. if (handle)
  882. return thread->stop();
  883. return true;
  884. }
  885. void handleException(IException *e)
  886. {
  887. CriticalBlock block(parent.crit);
  888. PrintExceptionLog(e,parent.poolname.get());
  889. if (!parent.exceptionHandler||!parent.exceptionHandler->fireException(e)) {
  890. }
  891. e->Release();
  892. }
  893. };
  894. class CPooledThreadIterator: implements IPooledThreadIterator, public CInterface
  895. {
  896. unsigned current;
  897. public:
  898. IArrayOf<IPooledThread> threads;
  899. IMPLEMENT_IINTERFACE;
  900. CPooledThreadIterator()
  901. {
  902. current = 0;
  903. }
  904. bool first()
  905. {
  906. current = 0;
  907. return threads.isItem(current);
  908. }
  909. bool next()
  910. {
  911. current++;
  912. return threads.isItem(current);
  913. }
  914. bool isValid()
  915. {
  916. return threads.isItem(current);
  917. }
  918. IPooledThread & query()
  919. {
  920. return threads.item(current);
  921. }
  922. };
  923. class CThreadPool: public CThreadPoolBase, implements IThreadPool, public CInterface
  924. {
  925. CIArrayOf<CPooledThreadWrapper> threadwrappers;
  926. PooledThreadHandle nextid;
  927. IThreadFactory *factory;
  928. unsigned stacksize;
  929. unsigned timeoutOnRelease;
  930. unsigned traceStartDelayPeriod;
  931. unsigned startsInPeriod;
  932. cycle_t startDelayInPeriod;
  933. CCycleTimer overAllTimer;
  934. PooledThreadHandle _start(void *param,const char *name, bool noBlock, unsigned timeout=0)
  935. {
  936. CCycleTimer startTimer;
  937. bool timedout = defaultmax && !availsem.wait(noBlock ? 0 : (timeout>0?timeout:delay));
  938. PooledThreadHandle ret;
  939. {
  940. CriticalBlock block(crit);
  941. if (timedout)
  942. {
  943. if (!availsem.wait(0)) { // make sure take allocated sem if has become available
  944. if (noBlock || timeout > 0)
  945. throw MakeStringException(0, "No threads available in pool %s", poolname.get());
  946. IWARNLOG("Pool limit exceeded for %s", poolname.get());
  947. }
  948. else
  949. timedout = false;
  950. }
  951. if (traceStartDelayPeriod)
  952. {
  953. ++startsInPeriod;
  954. if (timedout)
  955. {
  956. startDelayInPeriod += startTimer.elapsedCycles();
  957. if (overAllTimer.elapsedCycles() >= queryOneSecCycles()*traceStartDelayPeriod) // check avg. delay per minute
  958. {
  959. double totalDelayMs = (static_cast<double>(cycle_to_nanosec(startDelayInPeriod)))/1000000;
  960. double avgDelayMs = (static_cast<double>(cycle_to_nanosec(startDelayInPeriod/startsInPeriod)))/1000000;
  961. unsigned totalElapsedSecs = overAllTimer.elapsedMs()/1000;
  962. PROGLOG("%s: %u threads started in last %u seconds, total delay = %0.2f milliseconds, average delay = %0.2f milliseconds, currently running = %u", poolname.get(), startsInPeriod, totalElapsedSecs, totalDelayMs, avgDelayMs, runningCount());
  963. startsInPeriod = 0;
  964. startDelayInPeriod = 0;
  965. overAllTimer.reset();
  966. }
  967. }
  968. }
  969. CPooledThreadWrapper &t = allocThread();
  970. if (name)
  971. t.setName(name);
  972. t.go(param);
  973. ret = t.queryHandle();
  974. }
  975. Sleep(0);
  976. return ret;
  977. }
  978. public:
  979. IMPLEMENT_IINTERFACE;
  980. CThreadPool(IThreadFactory *_factory,IExceptionHandler *_exceptionHandler,const char *_poolname,unsigned _defaultmax, unsigned _delay, unsigned _stacksize, unsigned _timeoutOnRelease, unsigned _targetpoolsize)
  981. {
  982. poolname.set(_poolname);
  983. factory = LINK(_factory);
  984. exceptionHandler = _exceptionHandler;
  985. nextid = 1;
  986. stopall = false;
  987. defaultmax = _defaultmax;
  988. delay = _delay;
  989. if (defaultmax)
  990. availsem.signal(defaultmax);
  991. stacksize = _stacksize;
  992. timeoutOnRelease = _timeoutOnRelease;
  993. targetpoolsize = _targetpoolsize?_targetpoolsize:defaultmax;
  994. traceStartDelayPeriod = 0;
  995. startsInPeriod = 0;
  996. startDelayInPeriod = 0;
  997. }
  998. ~CThreadPool()
  999. {
  1000. stopAll(true);
  1001. if (!joinAll(true, timeoutOnRelease))
  1002. IWARNLOG("%s; timedout[%d] waiting for threads in pool", poolname.get(), timeoutOnRelease);
  1003. CriticalBlock block(crit);
  1004. bool first=true;
  1005. ForEachItemIn(i,threadwrappers)
  1006. {
  1007. CPooledThreadWrapper &t = threadwrappers.item(i);
  1008. if (!t.isStopped())
  1009. {
  1010. if (first)
  1011. {
  1012. IWARNLOG("Threads still active: ");
  1013. first = false;
  1014. }
  1015. StringBuffer threadInfo;
  1016. PROGLOG("Active thread: %s, info: %s", t.getName(), t.getInfo(threadInfo).str());
  1017. }
  1018. }
  1019. factory->Release();
  1020. }
  1021. CPooledThreadWrapper &allocThread()
  1022. { // called in critical section
  1023. PooledThreadHandle newid=nextid++;
  1024. if (newid==0)
  1025. newid=nextid++;
  1026. ForEachItemIn(i,threadwrappers) {
  1027. CPooledThreadWrapper &it = threadwrappers.item(i);
  1028. if (it.isStopped()) {
  1029. it.setHandle(newid);
  1030. if (!it.queryThread().canReuse()) {
  1031. it.queryThread().Release();
  1032. it.setThread(factory->createNew());
  1033. }
  1034. return it;
  1035. }
  1036. }
  1037. CPooledThreadWrapper &ret = *new CPooledThreadWrapper(*this,newid,factory->createNew());
  1038. if (stacksize)
  1039. ret.setStackSize(stacksize);
  1040. ret.start();
  1041. threadwrappers.append(ret);
  1042. return ret;
  1043. }
  1044. CPooledThreadWrapper *findThread(PooledThreadHandle handle)
  1045. { // called in critical section
  1046. ForEachItemIn(i,threadwrappers) {
  1047. CPooledThreadWrapper &it = threadwrappers.item(i);
  1048. if (it.queryHandle()==handle)
  1049. return &it;
  1050. }
  1051. return NULL;
  1052. }
  1053. PooledThreadHandle startNoBlock(void *param)
  1054. {
  1055. return _start(param, NULL, true);
  1056. }
  1057. PooledThreadHandle startNoBlock(void *param,const char *name)
  1058. {
  1059. return _start(param, name, true);
  1060. }
  1061. PooledThreadHandle start(void *param)
  1062. {
  1063. return _start(param, NULL, false);
  1064. }
  1065. PooledThreadHandle start(void *param,const char *name)
  1066. {
  1067. return _start(param, name, false);
  1068. }
  1069. PooledThreadHandle start(void *param,const char *name, unsigned timeout)
  1070. {
  1071. return _start(param, name, false, timeout);
  1072. }
  1073. bool stop(PooledThreadHandle handle)
  1074. {
  1075. CriticalBlock block(crit);
  1076. CPooledThreadWrapper *t = findThread(handle);
  1077. if (t)
  1078. return t->stop();
  1079. return true; // already stopped
  1080. }
  1081. bool stopAll(bool tryall=false)
  1082. {
  1083. availsem.signal(1000);
  1084. availsem.wait();
  1085. CriticalBlock block(crit);
  1086. bool ret=true;
  1087. ForEachItemIn(i,threadwrappers) {
  1088. CPooledThreadWrapper &it = threadwrappers.item(i);
  1089. if (!it.stop()) {
  1090. ret = false;
  1091. if (!tryall)
  1092. break;
  1093. }
  1094. }
  1095. return ret;
  1096. }
  1097. bool joinWait(CPooledThreadWrapper &t,unsigned timeout)
  1098. {
  1099. // called in critical section
  1100. if (t.isStopped())
  1101. return true;
  1102. Semaphore sem;
  1103. waitingsems.append(&sem);
  1104. waitingids.append(t.queryHandle());
  1105. crit.leave();
  1106. bool ret = sem.wait(timeout);
  1107. crit.enter();
  1108. unsigned i = waitingsems.find(&sem);
  1109. if (i!=NotFound) {
  1110. waitingids.remove(i);
  1111. waitingsems.remove(i);
  1112. }
  1113. return ret;
  1114. }
  1115. bool join(PooledThreadHandle handle,unsigned timeout=INFINITE)
  1116. {
  1117. CriticalBlock block(crit);
  1118. CPooledThreadWrapper *t = findThread(handle);
  1119. if (!t)
  1120. return true; // already stopped
  1121. return joinWait(*t,timeout);
  1122. }
  1123. virtual bool joinAll(bool del,unsigned timeout=INFINITE)
  1124. { // note timeout is for each join
  1125. CriticalBlock block(crit);
  1126. CIArrayOf<CPooledThreadWrapper> tojoin;
  1127. ForEachItemIn(i1,threadwrappers) {
  1128. CPooledThreadWrapper &it = threadwrappers.item(i1);
  1129. it.Link();
  1130. tojoin.append(it);
  1131. }
  1132. ForEachItemIn(i2,tojoin)
  1133. if (!joinWait(tojoin.item(i2),timeout))
  1134. return false;
  1135. if (del) {
  1136. stopall = true;
  1137. ForEachItemIn(i3,tojoin)
  1138. tojoin.item(i3).cycle();
  1139. {
  1140. CriticalUnblock unblock(crit);
  1141. ForEachItemIn(i4,tojoin)
  1142. tojoin.item(i4).join();
  1143. }
  1144. threadwrappers.kill();
  1145. stopall = false;
  1146. }
  1147. return true;
  1148. }
  1149. IPooledThreadIterator *running()
  1150. {
  1151. CriticalBlock block(crit);
  1152. CPooledThreadIterator *ret = new CPooledThreadIterator;
  1153. ForEachItemIn(i,threadwrappers) {
  1154. CPooledThreadWrapper &it = threadwrappers.item(i);
  1155. if (!it.isStopped()) {
  1156. IPooledThread &t = it.queryThread();
  1157. t.Link();
  1158. ret->threads.append(t);
  1159. }
  1160. }
  1161. return ret;
  1162. }
  1163. unsigned runningCount()
  1164. {
  1165. return numrunning;
  1166. }
  1167. void notifyStarted(CPooledThreadWrapper *item)
  1168. {
  1169. item->markStarted();
  1170. }
  1171. bool notifyStopped(CPooledThreadWrapper *item)
  1172. {
  1173. CriticalBlock block(crit);
  1174. PooledThreadHandle myid = item->markStopped();
  1175. ForEachItemIn(i1,waitingids) { // tell anyone waiting
  1176. if (waitingids.item(i1)==myid)
  1177. ((Semaphore *)waitingsems.item(i1))->signal();
  1178. }
  1179. bool ret = true;
  1180. if (defaultmax) {
  1181. unsigned n=threadwrappers.ordinality();
  1182. for (unsigned i2=targetpoolsize;i2<n;i2++) { // only check excess for efficiency
  1183. if (item==&threadwrappers.item(i2)) {
  1184. threadwrappers.remove(i2);
  1185. ret = false;
  1186. break;
  1187. }
  1188. }
  1189. availsem.signal();
  1190. }
  1191. return ret;
  1192. }
  1193. void setStartDelayTracing(unsigned secs)
  1194. {
  1195. traceStartDelayPeriod = secs;
  1196. }
  1197. };
  1198. IThreadPool *createThreadPool(const char *poolname,IThreadFactory *factory,IExceptionHandler *exceptionHandler,unsigned defaultmax, unsigned delay, unsigned stacksize, unsigned timeoutOnRelease, unsigned targetpoolsize)
  1199. {
  1200. return new CThreadPool(factory,exceptionHandler,poolname,defaultmax,delay,stacksize,timeoutOnRelease,targetpoolsize);
  1201. }
  1202. //=======================================================================================================
  1203. static void CheckAllowedProgram(const char *prog,const char *allowed)
  1204. {
  1205. if (!prog||!allowed||(strcmp(allowed,"*")==0))
  1206. return;
  1207. StringBuffer head;
  1208. bool inq = false;
  1209. // note don't have to be too worried about odd quoting as matching fixed list
  1210. while (*prog&&((*prog!=' ')||inq)) {
  1211. if (*prog=='"')
  1212. inq = !inq;
  1213. head.append(*(prog++));
  1214. }
  1215. StringArray list;
  1216. list.appendList(allowed, ",");
  1217. ForEachItemIn(i,list) {
  1218. if (WildMatch(head.str(),list.item(i)))
  1219. return;
  1220. }
  1221. AERRLOG("Unauthorized pipe program(%s)",head.str());
  1222. throw MakeStringException(-1,"Unauthorized pipe program(%s)",head.str());
  1223. }
  1224. class CPipeProcessException : public CSimpleInterfaceOf<IPipeProcessException>
  1225. {
  1226. int errCode;
  1227. StringAttr msg;
  1228. MessageAudience audience;
  1229. public:
  1230. CPipeProcessException(int _errCode, const char *_msg, MessageAudience _audience = MSGAUD_user) : errCode(_errCode), msg(_msg), audience(_audience)
  1231. {
  1232. }
  1233. virtual int errorCode() const override { return errCode; }
  1234. virtual StringBuffer & errorMessage(StringBuffer &str) const override
  1235. {
  1236. if (msg)
  1237. str.append(msg).append(", ");
  1238. return str.append(strerror(errCode));
  1239. }
  1240. MessageAudience errorAudience() const { return audience; }
  1241. };
  1242. IPipeProcessException *createPipeErrnoException(int code, const char *msg)
  1243. {
  1244. return new CPipeProcessException(code, msg);
  1245. }
  1246. IPipeProcessException *createPipeErrnoExceptionV(int code, const char *msg, ...)
  1247. {
  1248. StringBuffer eStr;
  1249. va_list args;
  1250. va_start(args, msg);
  1251. eStr.limited_valist_appendf(1024, msg, args);
  1252. va_end(args);
  1253. return new CPipeProcessException(code, eStr.str());
  1254. }
  1255. class CSimplePipeStream: implements ISimpleReadStream, public CInterface
  1256. {
  1257. public:
  1258. IMPLEMENT_IINTERFACE;
  1259. CSimplePipeStream(IPipeProcess *_pipe, bool _isStderr) : pipe(_pipe), isStderr(_isStderr) {}
  1260. virtual size32_t read(size32_t sz, void * data)
  1261. {
  1262. if (isStderr)
  1263. return pipe->readError(sz, data);
  1264. else
  1265. return pipe->read(sz, data);
  1266. }
  1267. private:
  1268. Owned<IPipeProcess> pipe;
  1269. bool isStderr;
  1270. };
  1271. #ifdef _WIN32
  1272. class CWindowsPipeProcess: implements IPipeProcess, public CInterface
  1273. {
  1274. HANDLE pipeProcess;
  1275. HANDLE hInput;
  1276. HANDLE hOutput;
  1277. HANDLE hError;
  1278. StringAttr title;
  1279. unsigned retcode;
  1280. CriticalSection sect;
  1281. bool aborted;
  1282. StringAttr allowedprogs;
  1283. StringArray envVars;
  1284. StringArray envValues;
  1285. public:
  1286. IMPLEMENT_IINTERFACE;
  1287. CWindowsPipeProcess(const char *_allowedprogs)
  1288. : allowedprogs(_allowedprogs)
  1289. {
  1290. pipeProcess = (HANDLE)-1;
  1291. hInput=(HANDLE)-1;
  1292. hOutput=(HANDLE)-1;
  1293. hError=(HANDLE)-1;
  1294. retcode = (unsigned)-1;
  1295. aborted = false;
  1296. }
  1297. ~CWindowsPipeProcess()
  1298. {
  1299. kill();
  1300. }
  1301. void kill()
  1302. {
  1303. doCloseInput();
  1304. doCloseOutput();
  1305. doCloseError();
  1306. if (pipeProcess != (HANDLE)-1) {
  1307. CloseHandle(pipeProcess);
  1308. pipeProcess = (HANDLE)-1;
  1309. }
  1310. }
  1311. bool run(const char *_title,const char *prog,const char *dir,bool hasinput,bool hasoutput,bool haserror, size32_t stderrbufsize,bool newProcessGroup)
  1312. {
  1313. // size32_t stderrbufsize ignored as not required (I think)
  1314. CriticalBlock block(sect);
  1315. kill();
  1316. title.clear();
  1317. if (_title) {
  1318. title.set(_title);
  1319. PROGLOG("%s: Creating PIPE process : %s", title.get(), prog);
  1320. }
  1321. CheckAllowedProgram(prog,allowedprogs);
  1322. SECURITY_ATTRIBUTES sa;
  1323. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  1324. sa.bInheritHandle = TRUE;
  1325. sa.lpSecurityDescriptor = NULL;
  1326. HANDLE hProgOutput=(HANDLE)-1;
  1327. HANDLE hProgInput=(HANDLE)-1;
  1328. HANDLE hProgError=(HANDLE)-1;
  1329. HANDLE h;
  1330. //NB: Create a pipe handles that are not inherited our end
  1331. if (hasinput) {
  1332. CreatePipe(&hProgInput,&h,&sa,0);
  1333. DuplicateHandle(GetCurrentProcess(),h, GetCurrentProcess(), &hInput, 0, FALSE, DUPLICATE_SAME_ACCESS);
  1334. CloseHandle(h);
  1335. }
  1336. if (hasoutput) {
  1337. CreatePipe(&h,&hProgOutput,&sa,0);
  1338. DuplicateHandle(GetCurrentProcess(),h, GetCurrentProcess(), &hOutput, 0, FALSE, DUPLICATE_SAME_ACCESS);
  1339. CloseHandle(h);
  1340. }
  1341. if (haserror) {
  1342. CreatePipe(&h,&hProgError,&sa,0);
  1343. DuplicateHandle(GetCurrentProcess(),h, GetCurrentProcess(), &hError, 0, FALSE, DUPLICATE_SAME_ACCESS);
  1344. CloseHandle(h);
  1345. }
  1346. STARTUPINFO StartupInfo;
  1347. _clear(StartupInfo);
  1348. StartupInfo.cb = sizeof(StartupInfo);
  1349. StartupInfo.wShowWindow = SW_HIDE;
  1350. StartupInfo.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW ;
  1351. StartupInfo.hStdOutput = hasoutput?hProgOutput:GetStdHandle(STD_OUTPUT_HANDLE);
  1352. StartupInfo.hStdError = haserror?hProgError:GetStdHandle(STD_ERROR_HANDLE);
  1353. StartupInfo.hStdInput = hasinput?hProgInput:GetStdHandle(STD_INPUT_HANDLE);
  1354. PROCESS_INFORMATION ProcessInformation;
  1355. // MORE - should create a new environment block that is copy of parent's, then set all the values in envVars/envValues, and pass it
  1356. if (!CreateProcess(NULL, (char *)prog, NULL,NULL,TRUE,0,NULL, dir&&*dir?dir:NULL, &StartupInfo,&ProcessInformation)) {
  1357. if (_title) {
  1358. StringBuffer errstr;
  1359. formatSystemError(errstr, GetLastError());
  1360. OERRLOG("%s: PIPE process '%s' failed: %s", title.get(), prog, errstr.str());
  1361. }
  1362. return false;
  1363. }
  1364. pipeProcess = ProcessInformation.hProcess;
  1365. CloseHandle(ProcessInformation.hThread);
  1366. if (hasoutput)
  1367. CloseHandle(hProgOutput);
  1368. if (hasinput)
  1369. CloseHandle(hProgInput);
  1370. if (haserror)
  1371. CloseHandle(hProgError);
  1372. return true;
  1373. }
  1374. virtual void setenv(const char *var, const char *value)
  1375. {
  1376. assertex(var);
  1377. if (!value)
  1378. value = "";
  1379. envVars.append(var);
  1380. envValues.append(value);
  1381. }
  1382. size32_t read(size32_t sz, void *buf)
  1383. {
  1384. DWORD sizeRead;
  1385. if (!ReadFile(hOutput, buf, sz, &sizeRead, NULL)) {
  1386. //raise error here
  1387. if(aborted)
  1388. return 0;
  1389. int err=GetLastError();
  1390. switch(err)
  1391. {
  1392. case ERROR_HANDLE_EOF:
  1393. case ERROR_BROKEN_PIPE:
  1394. case ERROR_NO_DATA:
  1395. return 0;
  1396. default:
  1397. aborted = true;
  1398. IException *e = makeOsExceptionV(err, "Pipe: ReadFile failed (size %d)", sz);
  1399. PrintExceptionLog(e, NULL);
  1400. throw e;
  1401. }
  1402. }
  1403. return aborted?((size32_t)-1):((size32_t)sizeRead);
  1404. }
  1405. ISimpleReadStream *getOutputStream()
  1406. {
  1407. return new CSimplePipeStream(LINK(this), false);
  1408. }
  1409. size32_t readError(size32_t sz, void *buf)
  1410. {
  1411. DWORD sizeRead;
  1412. if (!ReadFile(hError, buf, sz, &sizeRead, NULL)) {
  1413. //raise error here
  1414. if(aborted)
  1415. return 0;
  1416. int err=GetLastError();
  1417. switch(err)
  1418. {
  1419. case ERROR_HANDLE_EOF:
  1420. case ERROR_BROKEN_PIPE:
  1421. case ERROR_NO_DATA:
  1422. return 0;
  1423. default:
  1424. aborted = true;
  1425. IException *e = makeOsExceptionV(err, "Pipe: ReadError failed (size %d)", sz);
  1426. PrintExceptionLog(e, NULL);
  1427. throw e;
  1428. }
  1429. }
  1430. return aborted?((size32_t)-1):((size32_t)sizeRead);
  1431. }
  1432. ISimpleReadStream *getErrorStream()
  1433. {
  1434. return new CSimplePipeStream(LINK(this), true);
  1435. }
  1436. size32_t write(size32_t sz, const void *buf)
  1437. {
  1438. DWORD sizeWritten;
  1439. if (!WriteFile(hInput, buf, sz, &sizeWritten, NULL)) {
  1440. int err=GetLastError();
  1441. if ((err==ERROR_HANDLE_EOF)||aborted)
  1442. sizeWritten = 0;
  1443. else {
  1444. IException *e = makeOsExceptionV(err, "Pipe: WriteFile failed (size %d)", sz);
  1445. PrintExceptionLog(e, NULL);
  1446. throw e;
  1447. }
  1448. }
  1449. return aborted?((size32_t)-1):((size32_t)sizeWritten);
  1450. }
  1451. unsigned wait()
  1452. {
  1453. CriticalBlock block(sect);
  1454. if (pipeProcess != (HANDLE)-1) {
  1455. if (title.length())
  1456. PROGLOG("%s: Pipe: Waiting for process to complete %d",title.get(),(unsigned)pipeProcess);
  1457. {
  1458. CriticalUnblock unblock(sect);
  1459. WaitForSingleObject(pipeProcess, INFINITE);
  1460. }
  1461. if (pipeProcess != (HANDLE)-1) {
  1462. GetExitCodeProcess(pipeProcess,(LPDWORD)&retcode); // already got if notified
  1463. CloseHandle(pipeProcess);
  1464. pipeProcess = (HANDLE)-1;
  1465. }
  1466. if (title.length())
  1467. PROGLOG("%s: Pipe: process complete",title.get());
  1468. }
  1469. return retcode;
  1470. }
  1471. unsigned wait(unsigned timeoutms, bool &timedout)
  1472. {
  1473. CriticalBlock block(sect);
  1474. timedout = false;
  1475. if (pipeProcess != (HANDLE)-1) {
  1476. if (title.length())
  1477. PROGLOG("%s: Pipe: Waiting for process to complete %d",title.get(),(unsigned)pipeProcess);
  1478. {
  1479. CriticalUnblock unblock(sect);
  1480. if (WaitForSingleObject(pipeProcess, timeoutms)!=WAIT_OBJECT_0) {
  1481. timedout = true;
  1482. return retcode;
  1483. }
  1484. }
  1485. if (pipeProcess != (HANDLE)-1) {
  1486. GetExitCodeProcess(pipeProcess,(LPDWORD)&retcode); // already got if notified
  1487. CloseHandle(pipeProcess);
  1488. pipeProcess = (HANDLE)-1;
  1489. }
  1490. if (title.length())
  1491. PROGLOG("%s: Pipe: process complete",title.get());
  1492. }
  1493. return retcode;
  1494. }
  1495. void notifyTerminated(HANDLE pid,unsigned _retcode)
  1496. {
  1497. CriticalBlock block(sect);
  1498. if ((pid!=(HANDLE)-1)&&(pid==pipeProcess)) {
  1499. retcode = _retcode;
  1500. pipeProcess = (HANDLE)-1;
  1501. }
  1502. }
  1503. void doCloseInput()
  1504. {
  1505. CriticalBlock block(sect);
  1506. if (hInput != (HANDLE)-1) {
  1507. CloseHandle(hInput);
  1508. hInput = (HANDLE)-1;
  1509. }
  1510. }
  1511. void doCloseOutput()
  1512. {
  1513. CriticalBlock block(sect);
  1514. if (hOutput != (HANDLE)-1) {
  1515. CloseHandle(hOutput);
  1516. hOutput = (HANDLE)-1;
  1517. }
  1518. }
  1519. void doCloseError()
  1520. {
  1521. CriticalBlock block(sect);
  1522. if (hError != (HANDLE)-1) {
  1523. CloseHandle(hError);
  1524. hError = (HANDLE)-1;
  1525. }
  1526. }
  1527. void closeInput()
  1528. {
  1529. doCloseInput();
  1530. }
  1531. void closeOutput()
  1532. {
  1533. doCloseOutput();
  1534. }
  1535. void closeError()
  1536. {
  1537. doCloseError();
  1538. }
  1539. void abort()
  1540. {
  1541. CriticalBlock block(sect);
  1542. if (pipeProcess != (HANDLE)-1) {
  1543. if (title.length())
  1544. PROGLOG("%s: Pipe Aborting",title.get());
  1545. aborted = true;
  1546. //doCloseOutput(); // seems to work better without this
  1547. doCloseInput();
  1548. {
  1549. CriticalUnblock unblock(sect);
  1550. Sleep(100);
  1551. }
  1552. try { // this code is problematic for some reason
  1553. if (pipeProcess != (HANDLE)-1) {
  1554. TerminateProcess(pipeProcess, 255);
  1555. CloseHandle(pipeProcess);
  1556. pipeProcess = (HANDLE)-1;
  1557. }
  1558. }
  1559. catch (...) {
  1560. // ignore errors
  1561. }
  1562. if (title.length())
  1563. PROGLOG("%s: Pipe Aborted",title.get());
  1564. }
  1565. }
  1566. bool hasInput()
  1567. {
  1568. return hInput!=(HANDLE)-1;
  1569. }
  1570. bool hasOutput()
  1571. {
  1572. return hOutput!=(HANDLE)-1;
  1573. }
  1574. bool hasError()
  1575. {
  1576. return hError!=(HANDLE)-1;
  1577. }
  1578. HANDLE getProcessHandle()
  1579. {
  1580. return pipeProcess;
  1581. }
  1582. };
  1583. IPipeProcess *createPipeProcess(const char *allowedprogs)
  1584. {
  1585. return new CWindowsPipeProcess(allowedprogs);
  1586. }
  1587. #else
  1588. class CIgnoreSIGPIPE
  1589. {
  1590. public:
  1591. CIgnoreSIGPIPE()
  1592. {
  1593. oact.sa_handler = SIG_IGN;
  1594. struct sigaction act;
  1595. sigset_t blockset;
  1596. sigemptyset(&blockset);
  1597. act.sa_mask = blockset;
  1598. act.sa_handler = SIG_IGN;
  1599. act.sa_flags = 0;
  1600. sigaction(SIGPIPE, &act, &oact);
  1601. }
  1602. ~CIgnoreSIGPIPE()
  1603. {
  1604. if (oact.sa_handler != SIG_IGN)
  1605. sigaction(SIGPIPE, &oact, NULL);
  1606. }
  1607. private:
  1608. struct sigaction oact;
  1609. };
  1610. #define WHITESPACE " \t\n\r"
  1611. static unsigned dowaitpid(HANDLE pid, int mode)
  1612. {
  1613. while (pid != (HANDLE)-1) {
  1614. int stat=-1;
  1615. int ret = waitpid(pid, &stat, mode);
  1616. if (ret>0)
  1617. {
  1618. if (WIFEXITED(stat))
  1619. return WEXITSTATUS(stat);
  1620. else if (WIFSIGNALED(stat))
  1621. {
  1622. OERRLOG("Program was terminated by signal %u", (unsigned) WTERMSIG(stat));
  1623. if (WTERMSIG(stat)==SIGPIPE)
  1624. return 0;
  1625. return 254;
  1626. }
  1627. else
  1628. {
  1629. return 254;
  1630. }
  1631. }
  1632. if (ret==0)
  1633. break;
  1634. int err = errno;
  1635. if (err == ECHILD)
  1636. break;
  1637. if (err!=EINTR) {
  1638. OERRLOG("dowait failed with errcode %d",err);
  1639. return (unsigned)-1;
  1640. }
  1641. }
  1642. return 0;
  1643. }
  1644. static CriticalSection runsect; // single thread process start to avoid forked handle open/closes interleaving
  1645. class CLinuxPipeProcess: implements IPipeProcess, public CInterface
  1646. {
  1647. class cForkThread: public Thread
  1648. {
  1649. CLinuxPipeProcess *parent;
  1650. public:
  1651. cForkThread(CLinuxPipeProcess *_parent)
  1652. {
  1653. parent = _parent;
  1654. }
  1655. int run()
  1656. {
  1657. parent->run();
  1658. return 0;
  1659. }
  1660. };
  1661. Owned<cForkThread> forkthread;
  1662. class cStdErrorBufferThread: public Thread
  1663. {
  1664. MemoryAttr buf;
  1665. size32_t bufsize;
  1666. Semaphore stopsem;
  1667. CriticalSection &sect;
  1668. int &hError;
  1669. public:
  1670. cStdErrorBufferThread(size32_t maxbufsize,int &_hError,CriticalSection &_sect)
  1671. : sect(_sect), hError(_hError)
  1672. {
  1673. buf.allocate(maxbufsize);
  1674. bufsize = 0;
  1675. }
  1676. int run()
  1677. {
  1678. while (!stopsem.wait(1000)) {
  1679. CriticalBlock block(sect);
  1680. if (hError!=(HANDLE)-1) { // hmm who did that
  1681. fcntl(hError,F_SETFL,O_NONBLOCK); // make sure non-blocking
  1682. if (bufsize<buf.length()) {
  1683. size32_t sizeRead = (size32_t)::read(hError, (byte *)buf.bufferBase()+bufsize, buf.length()-bufsize);
  1684. if ((int)sizeRead>0) {
  1685. bufsize += sizeRead;
  1686. }
  1687. }
  1688. else { // flush (to avoid process blocking)
  1689. byte tmp[1024];
  1690. size32_t totsz = 0;
  1691. for (unsigned i=0;i<1024;i++) {
  1692. size32_t sz = (size32_t)::read(hError, tmp, sizeof(tmp));
  1693. if ((int)sz<=0)
  1694. break;
  1695. totsz+=sz;
  1696. }
  1697. if (totsz)
  1698. IWARNLOG("Lost %d bytes of stderr output",totsz);
  1699. }
  1700. }
  1701. }
  1702. if (hError!=(HANDLE)-1) { // hmm who did that
  1703. fcntl(hError,F_SETFL,0); // read any remaining data in blocking mode
  1704. while (bufsize<buf.length()) {
  1705. size32_t sizeRead = (size32_t)::read(hError, (byte *)buf.bufferBase()+bufsize, buf.length()-bufsize);
  1706. if ((int)sizeRead>0)
  1707. bufsize += sizeRead;
  1708. else
  1709. break;
  1710. }
  1711. }
  1712. return 0;
  1713. }
  1714. void stop()
  1715. {
  1716. stopsem.signal();
  1717. Thread::join();
  1718. }
  1719. size32_t read(size32_t sz,void *out)
  1720. {
  1721. CriticalBlock block(sect);
  1722. if (bufsize<sz)
  1723. sz = bufsize;
  1724. if (sz>0) {
  1725. memcpy(out,buf.bufferBase(),sz);
  1726. if (sz!=bufsize) {
  1727. bufsize -= sz;
  1728. memmove(buf.bufferBase(),(byte *)buf.bufferBase()+sz,bufsize); // not ideal but hopefully not large
  1729. }
  1730. else
  1731. bufsize = 0;
  1732. }
  1733. return sz;
  1734. }
  1735. } *stderrbufferthread;
  1736. protected: friend class PipeWriterThread;
  1737. HANDLE pipeProcess;
  1738. HANDLE hInput;
  1739. HANDLE hOutput;
  1740. HANDLE hError;
  1741. bool hasinput;
  1742. bool hasoutput;
  1743. bool haserror;
  1744. bool newProcessGroup;
  1745. StringAttr title;
  1746. StringAttr cmd;
  1747. StringAttr prog;
  1748. StringAttr dir;
  1749. int retcode;
  1750. CriticalSection sect;
  1751. Semaphore started;
  1752. bool aborted;
  1753. MemoryBuffer stderrbuf;
  1754. size32_t stderrbufsize;
  1755. StringAttr allowedprogs;
  1756. StringArray envVars;
  1757. StringArray envValues;
  1758. void clearUtilityThreads(bool clearStderr)
  1759. {
  1760. Owned<cForkThread> ft;
  1761. cStdErrorBufferThread *et;
  1762. {
  1763. CriticalBlock block(sect); // clear forkthread and optionally stderrbufferthread
  1764. ft.setown(forkthread.getClear());
  1765. et = stderrbufferthread;
  1766. if (clearStderr)
  1767. stderrbufferthread = nullptr;
  1768. }
  1769. if (ft)
  1770. {
  1771. ft->join();
  1772. ft.clear();
  1773. }
  1774. if (et)
  1775. {
  1776. et->stop();
  1777. if (clearStderr)
  1778. delete et;
  1779. }
  1780. }
  1781. public:
  1782. IMPLEMENT_IINTERFACE;
  1783. CLinuxPipeProcess(const char *_allowedprogs)
  1784. : allowedprogs(_allowedprogs)
  1785. {
  1786. pipeProcess = (HANDLE)-1;
  1787. hInput=(HANDLE)-1;
  1788. hOutput=(HANDLE)-1;
  1789. hError=(HANDLE)-1;
  1790. retcode = -1;
  1791. aborted = false;
  1792. stderrbufferthread = NULL;
  1793. newProcessGroup = false;
  1794. }
  1795. ~CLinuxPipeProcess()
  1796. {
  1797. kill();
  1798. }
  1799. void kill()
  1800. {
  1801. closeInput();
  1802. closeOutput();
  1803. closeError();
  1804. clearUtilityThreads(true);
  1805. }
  1806. char **splitargs(const char *line,unsigned &argc)
  1807. {
  1808. char *buf = strdup(line);
  1809. // first count params (this probably could be improved)
  1810. char *s = buf;
  1811. argc = 0;
  1812. while (readarg(s))
  1813. argc++;
  1814. free(buf);
  1815. size32_t l = strlen(line)+1;
  1816. size32_t al = (argc+1)*sizeof(char *);
  1817. char **argv = (char **)malloc(al+l);
  1818. argv[argc] = NULL;
  1819. s = ((char *)argv)+al;
  1820. memcpy(s,line,l);
  1821. for (unsigned i=0;i<argc;i++)
  1822. argv[i] = readarg(s);
  1823. return argv;
  1824. }
  1825. void run()
  1826. {
  1827. int inpipe[2];
  1828. int outpipe[2];
  1829. int errpipe[2];
  1830. if ((hasinput && (::pipe(inpipe)==-1)) ||
  1831. (hasoutput && (::pipe(outpipe)==-1)) ||
  1832. (haserror && (::pipe(errpipe)==-1)))
  1833. {
  1834. retcode = START_FAILURE;
  1835. started.signal();
  1836. throw makeOsException(errno);
  1837. }
  1838. /* NB: Important to call splitargs (which calls malloc) before the fork()
  1839. * and not in the child process. Because performing malloc in the child
  1840. * process, which then calls exec() can cause problems for TBB malloc proxy.
  1841. */
  1842. unsigned argc;
  1843. char **argv=splitargs(prog,argc);
  1844. for (;;)
  1845. {
  1846. pipeProcess = (HANDLE)fork();
  1847. if (pipeProcess!=(HANDLE)-1)
  1848. break;
  1849. if (errno!=EAGAIN) {
  1850. if (hasinput) {
  1851. close(inpipe[0]);
  1852. close(inpipe[1]);
  1853. }
  1854. if (hasoutput) {
  1855. close(outpipe[0]);
  1856. close(outpipe[1]);
  1857. }
  1858. if (haserror) {
  1859. close(errpipe[0]);
  1860. close(errpipe[1]);
  1861. }
  1862. retcode = START_FAILURE;
  1863. started.signal();
  1864. free(argv);
  1865. return;
  1866. }
  1867. }
  1868. if (pipeProcess==0) { // child
  1869. if (newProcessGroup)//Force the child process into its own process group, so we can terminate it and its children.
  1870. setpgid(0,0);
  1871. if (hasinput) {
  1872. dup2(inpipe[0],0);
  1873. close(inpipe[0]);
  1874. close(inpipe[1]);
  1875. }
  1876. if (hasoutput) {
  1877. dup2(outpipe[1],1);
  1878. close(outpipe[0]);
  1879. close(outpipe[1]);
  1880. }
  1881. if (haserror) {
  1882. dup2(errpipe[1],2);
  1883. close(errpipe[0]);
  1884. close(errpipe[1]);
  1885. }
  1886. if (dir.get()) {
  1887. if (chdir(dir) == -1)
  1888. throw MakeStringException(-1, "CLinuxPipeProcess::run: could not change dir to %s", dir.get());
  1889. }
  1890. ForEachItemIn(idx, envVars)
  1891. {
  1892. ::setenv(envVars.item(idx), envValues.item(idx), 1);
  1893. }
  1894. execvp(argv[0],argv);
  1895. if (haserror)
  1896. {
  1897. Owned<IException> e = createPipeErrnoExceptionV(errno, "exec failed: %s", prog.get());
  1898. StringBuffer eStr;
  1899. fprintf(stderr, "ERROR: %d: %s", e->errorCode(), e->errorMessage(eStr).str());
  1900. fflush(stderr);
  1901. }
  1902. _exit(START_FAILURE); // must be _exit!!
  1903. }
  1904. free(argv);
  1905. if (hasinput)
  1906. close(inpipe[0]);
  1907. if (hasoutput)
  1908. close(outpipe[1]);
  1909. if (haserror)
  1910. close(errpipe[1]);
  1911. hInput = hasinput?inpipe[1]:((HANDLE)-1);
  1912. hOutput = hasoutput?outpipe[0]:((HANDLE)-1);
  1913. hError = haserror?errpipe[0]:((HANDLE)-1);
  1914. started.signal();
  1915. retcode = dowaitpid(pipeProcess, 0);
  1916. if (retcode==START_FAILURE)
  1917. closeOutput();
  1918. }
  1919. bool run(const char *_title,const char *_prog,const char *_dir,bool _hasinput,bool _hasoutput, bool _haserror, size32_t stderrbufsize, bool _newProcessGroup)
  1920. {
  1921. CriticalBlock runblock(runsect);
  1922. kill();
  1923. CriticalBlock block(sect);
  1924. hasinput = _hasinput;
  1925. hasoutput = _hasoutput;
  1926. haserror = _haserror;
  1927. newProcessGroup = _newProcessGroup;
  1928. title.clear();
  1929. prog.set(_prog);
  1930. dir.set(_dir);
  1931. if (_title)
  1932. {
  1933. title.set(_title);
  1934. PROGLOG("%s: Creating PIPE program process : '%s' - hasinput=%d, hasoutput=%d stderrbufsize=%d", title.get(), prog.get(),(int)hasinput, (int)hasoutput, stderrbufsize);
  1935. }
  1936. CheckAllowedProgram(prog,allowedprogs);
  1937. retcode = 0;
  1938. if (forkthread)
  1939. {
  1940. {
  1941. CriticalUnblock unblock(sect);
  1942. forkthread->join();
  1943. }
  1944. forkthread.clear();
  1945. }
  1946. forkthread.setown(new cForkThread(this));
  1947. forkthread->start();
  1948. bool joined = false;
  1949. {
  1950. CriticalUnblock unblock(sect);
  1951. started.wait();
  1952. joined = forkthread->join(50); // give a chance to fail
  1953. }
  1954. // only check retcode if we were able to join
  1955. if ( (joined) && (retcode==START_FAILURE) )
  1956. {
  1957. DBGLOG("%s: PIPE process '%s' failed to start", title.get()?title.get():"CLinuxPipeProcess", prog.get());
  1958. forkthread.clear();
  1959. return false;
  1960. }
  1961. if (stderrbufsize)
  1962. {
  1963. if (stderrbufferthread)
  1964. {
  1965. stderrbufferthread->stop();
  1966. delete stderrbufferthread;
  1967. }
  1968. stderrbufferthread = new cStdErrorBufferThread(stderrbufsize,hError,sect);
  1969. stderrbufferthread->start();
  1970. }
  1971. return true;
  1972. }
  1973. virtual void setenv(const char *var, const char *value)
  1974. {
  1975. assertex(var);
  1976. if (!value)
  1977. value = "";
  1978. envVars.append(var);
  1979. envValues.append(value);
  1980. }
  1981. size32_t read(size32_t sz, void *buf)
  1982. {
  1983. CriticalBlock block(sect);
  1984. if (aborted)
  1985. return (size32_t)-1;
  1986. if (hOutput==(HANDLE)-1)
  1987. return 0;
  1988. size32_t sizeRead;
  1989. for (;;) {
  1990. {
  1991. CriticalUnblock unblock(sect);
  1992. sizeRead = (size32_t)::read(hOutput, buf, sz);
  1993. }
  1994. if (sizeRead!=(size32_t)-1)
  1995. break;
  1996. if (aborted)
  1997. break;
  1998. if (errno!=EINTR) {
  1999. aborted = true;
  2000. throw createPipeErrnoExceptionV(errno,"Pipe: read failed (size %d)", sz);
  2001. }
  2002. }
  2003. return aborted?((size32_t)-1):((size32_t)sizeRead);
  2004. }
  2005. ISimpleReadStream *getOutputStream()
  2006. {
  2007. return new CSimplePipeStream(LINK(this), false);
  2008. }
  2009. size32_t write(size32_t sz, const void *buf)
  2010. {
  2011. CriticalBlock block(sect);
  2012. CIgnoreSIGPIPE ignoresigpipe;
  2013. if (aborted)
  2014. return (size32_t)-1;
  2015. if (hInput==(HANDLE)-1)
  2016. return 0;
  2017. size32_t sizeWritten;
  2018. for (;;) {
  2019. {
  2020. CriticalUnblock unblock(sect);
  2021. sizeWritten = (size32_t)::write(hInput, buf, sz);
  2022. }
  2023. if (sizeWritten!=(size32_t)-1)
  2024. break;
  2025. if (aborted)
  2026. break;
  2027. if (errno!=EINTR) {
  2028. throw createPipeErrnoExceptionV(errno, "Pipe: write failed (size %d)", sz);
  2029. }
  2030. }
  2031. return aborted?((size32_t)-1):((size32_t)sizeWritten);
  2032. }
  2033. size32_t readError(size32_t sz, void *buf)
  2034. {
  2035. CriticalBlock block(sect);
  2036. if (stderrbufferthread)
  2037. return stderrbufferthread->read(sz,buf);
  2038. if (aborted)
  2039. return (size32_t)-1;
  2040. if (hError==(HANDLE)-1)
  2041. return 0;
  2042. size32_t sizeRead;
  2043. for (;;) {
  2044. {
  2045. CriticalUnblock unblock(sect);
  2046. sizeRead = (size32_t)::read(hError, buf, sz);
  2047. }
  2048. if (sizeRead!=(size32_t)-1)
  2049. break;
  2050. if (aborted)
  2051. break;
  2052. if (errno!=EINTR) {
  2053. aborted = true;
  2054. throw createPipeErrnoExceptionV(errno, "Pipe: readError failed (size %d)", sz);
  2055. }
  2056. }
  2057. return aborted?((size32_t)-1):((size32_t)sizeRead);
  2058. }
  2059. ISimpleReadStream *getErrorStream()
  2060. {
  2061. return new CSimplePipeStream(LINK(this), true);
  2062. }
  2063. void notifyTerminated(HANDLE pid,unsigned _retcode)
  2064. {
  2065. CriticalBlock block(sect);
  2066. if (((int)pid>0)&&(pid==pipeProcess)) {
  2067. retcode = _retcode;
  2068. pipeProcess = (HANDLE)-1;
  2069. }
  2070. }
  2071. unsigned wait()
  2072. {
  2073. bool timedout;
  2074. return wait(INFINITE, timedout);
  2075. }
  2076. unsigned wait(unsigned timeoutms, bool &timedout)
  2077. {
  2078. timedout = false;
  2079. if (INFINITE != timeoutms)
  2080. {
  2081. CriticalBlock block(sect);
  2082. if (forkthread)
  2083. {
  2084. {
  2085. CriticalUnblock unblock(sect);
  2086. if (!forkthread->join(timeoutms))
  2087. {
  2088. timedout = true;
  2089. return retcode;
  2090. }
  2091. }
  2092. }
  2093. }
  2094. // NOTE - we don't clear stderrbufferthread here, since we want to be able to still read the buffered data
  2095. clearUtilityThreads(false); // NB: will recall forkthread->join(), but doesn't matter
  2096. if (pipeProcess != (HANDLE)-1)
  2097. {
  2098. if (title.length())
  2099. PROGLOG("%s: Pipe: process %d complete %d", title.get(), pipeProcess, retcode);
  2100. pipeProcess = (HANDLE)-1;
  2101. }
  2102. return retcode;
  2103. }
  2104. void closeOutput()
  2105. {
  2106. CriticalBlock block(sect);
  2107. if (hOutput != (HANDLE)-1) {
  2108. ::close(hOutput);
  2109. hOutput = (HANDLE)-1;
  2110. }
  2111. }
  2112. void closeInput()
  2113. {
  2114. CriticalBlock block(sect);
  2115. if (hInput != (HANDLE)-1) {
  2116. ::close(hInput);
  2117. hInput = (HANDLE)-1;
  2118. }
  2119. }
  2120. void closeError()
  2121. {
  2122. CriticalBlock block(sect);
  2123. if (hError != (HANDLE)-1) {
  2124. ::close(hError);
  2125. hError = (HANDLE)-1;
  2126. }
  2127. }
  2128. void abort()
  2129. {
  2130. CriticalBlock block(sect);
  2131. if (pipeProcess != (HANDLE)-1) {
  2132. if (title.length())
  2133. PROGLOG("%s: Pipe Aborting",title.get());
  2134. aborted = true;
  2135. closeInput();
  2136. {
  2137. CriticalUnblock unblock(sect);
  2138. forkthread->join(1000);
  2139. }
  2140. if (pipeProcess != (HANDLE)-1) {
  2141. if (title.length())
  2142. PROGLOG("%s: Forcibly killing pipe process %d",title.get(),pipeProcess);
  2143. if (newProcessGroup)
  2144. ::kill(-pipeProcess,SIGKILL);
  2145. else
  2146. ::kill(pipeProcess,SIGKILL); // if this doesn't kill it we are in trouble
  2147. CriticalUnblock unblock(sect);
  2148. wait();
  2149. }
  2150. if (title.length())
  2151. PROGLOG("%s: Pipe Aborted",title.get());
  2152. retcode = -1;
  2153. forkthread.clear();
  2154. }
  2155. }
  2156. bool hasInput()
  2157. {
  2158. CriticalBlock block(sect);
  2159. return hInput!=(HANDLE)-1;
  2160. }
  2161. bool hasOutput()
  2162. {
  2163. CriticalBlock block(sect);
  2164. return hOutput!=(HANDLE)-1;
  2165. }
  2166. bool hasError()
  2167. {
  2168. CriticalBlock block(sect);
  2169. return hError!=(HANDLE)-1;
  2170. }
  2171. HANDLE getProcessHandle()
  2172. {
  2173. CriticalBlock block(sect);
  2174. return pipeProcess;
  2175. }
  2176. };
  2177. IPipeProcess *createPipeProcess(const char *allowedprogs)
  2178. {
  2179. return new CLinuxPipeProcess(allowedprogs);
  2180. }
  2181. #endif
  2182. // Worker thread
  2183. class CWorkQueueThread: implements IWorkQueueThread, public CInterface
  2184. {
  2185. public:
  2186. IMPLEMENT_IINTERFACE;
  2187. CriticalSection crit;
  2188. unsigned persisttime;
  2189. class cWorkerThread: public Thread
  2190. {
  2191. unsigned persisttime;
  2192. CWorkQueueThread *parent;
  2193. CriticalSection &crit;
  2194. public:
  2195. cWorkerThread(CWorkQueueThread *_parent,CriticalSection &_crit,unsigned _persisttime)
  2196. : crit(_crit)
  2197. {
  2198. parent = _parent;
  2199. persisttime = _persisttime;
  2200. }
  2201. QueueOf<IWorkQueueItem,false> queue;
  2202. Semaphore sem;
  2203. int run()
  2204. {
  2205. for (;;) {
  2206. IWorkQueueItem * work;
  2207. bool wr = sem.wait(persisttime);
  2208. {
  2209. CriticalBlock block(crit);
  2210. if (!wr) {
  2211. wr = sem.wait(0); // catch race
  2212. if (!wr)
  2213. break; // timed out
  2214. }
  2215. work = queue.dequeue();
  2216. }
  2217. if (!work)
  2218. break;
  2219. try {
  2220. work->execute();
  2221. work->Release();
  2222. }
  2223. catch (IException *e)
  2224. {
  2225. EXCLOG(e,"CWorkQueueThread item execute");
  2226. e->Release();
  2227. }
  2228. }
  2229. CriticalBlock block(crit);
  2230. parent->worker=NULL; // this should be safe
  2231. return 0;
  2232. }
  2233. } *worker;
  2234. CWorkQueueThread(unsigned _persisttime)
  2235. {
  2236. persisttime = _persisttime;
  2237. worker = NULL;
  2238. }
  2239. ~CWorkQueueThread()
  2240. {
  2241. wait();
  2242. }
  2243. void post(IWorkQueueItem *packet)
  2244. {
  2245. CriticalBlock block(crit);
  2246. if (!worker) {
  2247. worker = new cWorkerThread(this,crit,persisttime);
  2248. worker->startRelease();
  2249. }
  2250. worker->queue.enqueue(packet);
  2251. worker->sem.signal();
  2252. }
  2253. void wait()
  2254. {
  2255. CriticalBlock block(crit);
  2256. if (worker) {
  2257. worker->queue.enqueue(NULL);
  2258. worker->sem.signal();
  2259. Linked<cWorkerThread> wt;
  2260. wt.set(worker);
  2261. CriticalUnblock unblock(crit);
  2262. wt->join();
  2263. }
  2264. }
  2265. unsigned pending()
  2266. {
  2267. CriticalBlock block(crit);
  2268. unsigned ret = 0;
  2269. if (worker)
  2270. ret = worker->queue.ordinality();
  2271. return ret;
  2272. }
  2273. };
  2274. IWorkQueueThread *createWorkQueueThread(unsigned persisttime)
  2275. {
  2276. return new CWorkQueueThread(persisttime);
  2277. }
  2278. unsigned threadLogID() // for use in logging
  2279. {
  2280. #if defined(__APPLE__)
  2281. return pthread_mach_thread_np(pthread_self());
  2282. #elif !defined(_WIN32)
  2283. #ifdef SYS_gettid
  2284. return (unsigned) (memsize_t) syscall(SYS_gettid);
  2285. #endif
  2286. #endif
  2287. return (unsigned)(memsize_t) GetCurrentThreadId(); // truncated in 64bit
  2288. }