jthread.cpp 65 KB

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