jthread.cpp 62 KB

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