jthread.cpp 66 KB

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