jthread.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  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. void callThreadTerminationHooks()
  45. {
  46. if (threadTerminationHook)
  47. {
  48. (*threadTerminationHook)();
  49. threadTerminationHook = NULL;
  50. }
  51. }
  52. PointerArray *exceptionHandlers = NULL;
  53. MODULE_INIT(INIT_PRIORITY_JTHREAD)
  54. {
  55. if (threadTerminationHook)
  56. (*threadTerminationHook)(); // May be too late :(
  57. exceptionHandlers = new PointerArray();
  58. return true;
  59. }
  60. MODULE_EXIT()
  61. {
  62. delete exceptionHandlers;
  63. }
  64. void addThreadExceptionHandler(IExceptionHandler *handler)
  65. {
  66. assertex(exceptionHandlers); // have to ensure MODULE_INIT has appropriate priority.
  67. exceptionHandlers->append(handler);
  68. }
  69. void removeThreadExceptionHandler(IExceptionHandler *handler)
  70. {
  71. exceptionHandlers->zap(handler);
  72. }
  73. static bool SEHHandling = false;
  74. void enableThreadSEH() { SEHHandling=true; }
  75. void disableThreadSEH() { SEHHandling=false; } // only prevents new threads from having SEH handler, no mech. for turning off existing threads SEH handling.
  76. static ICopyArrayOf<Thread> ThreadList;
  77. static CriticalSection ThreadListSem;
  78. static size32_t defaultThreadStackSize=0;
  79. static ICopyArrayOf<Thread> ThreadDestroyList;
  80. static SpinLock ThreadDestroyListLock;
  81. #ifdef _WIN32
  82. extern void *EnableSEHtranslation();
  83. unsigned WINAPI Thread::_threadmain(LPVOID v)
  84. #else
  85. void *Thread::_threadmain(void *v)
  86. #endif
  87. {
  88. Thread * t = (Thread *)v;
  89. #ifdef _WIN32
  90. if (SEHHandling)
  91. EnableSEHtranslation();
  92. #else
  93. t->tidlog = threadLogID();
  94. #endif
  95. int ret = t->begin();
  96. char *&threadname = t->cthreadname.threadname;
  97. if (threadname) {
  98. memsize_t l=strlen(threadname);
  99. char *newname = (char *)malloc(l+8+1);
  100. memcpy(newname,"Stopped ",8);
  101. memcpy(newname+8,threadname,l+1);
  102. char *oldname = threadname;
  103. threadname = newname;
  104. free(oldname);
  105. }
  106. {
  107. // need to ensure joining thread does not race with us to release
  108. t->Link(); // extra safety link
  109. {
  110. SpinBlock block(ThreadDestroyListLock);
  111. ThreadDestroyList.append(*t);
  112. }
  113. try {
  114. t->stopped.signal();
  115. if (t->Release()) {
  116. PROGLOG("extra unlinked thread");
  117. PrintStackReport();
  118. }
  119. else
  120. t->Release();
  121. }
  122. catch (...) {
  123. PROGLOG("thread release exception");
  124. throw;
  125. }
  126. {
  127. SpinBlock block(ThreadDestroyListLock);
  128. ThreadDestroyList.zap(*t); // hopefully won't get too big (i.e. one entry!)
  129. }
  130. }
  131. #if defined(_WIN32)
  132. return ret;
  133. #else
  134. return (void *) (memsize_t)ret;
  135. #endif
  136. }
  137. // JCSMORE - should have a setPriority(), unsupported under _WIN32
  138. void Thread::adjustPriority(int delta)
  139. {
  140. if (delta < -2)
  141. prioritydelta = -2;
  142. else if (delta > 2)
  143. prioritydelta = 2;
  144. else
  145. prioritydelta = delta;
  146. if (alive)
  147. {
  148. #if defined(_WIN32)
  149. int priority;
  150. switch (delta)
  151. {
  152. case -2: priority = THREAD_PRIORITY_LOWEST; break;
  153. case -1: priority = THREAD_PRIORITY_BELOW_NORMAL; break;
  154. case 0: priority = THREAD_PRIORITY_NORMAL; break;
  155. case +1: priority = THREAD_PRIORITY_ABOVE_NORMAL; break;
  156. case +2: priority = THREAD_PRIORITY_HIGHEST; break;
  157. }
  158. SetThreadPriority(hThread, priority);
  159. #else
  160. //MORE - What control is there?
  161. int policy;
  162. sched_param param;
  163. int rc;
  164. if (( rc = pthread_getschedparam(threadid, &policy, &param)) != 0)
  165. DBGLOG("pthread_getschedparam error: %d", rc);
  166. switch (delta)
  167. {
  168. // JCS - doubtful whether these good values...
  169. case -2: param.sched_priority = 0; policy =SCHED_OTHER; break;
  170. case -1: param.sched_priority = 0; policy =SCHED_OTHER; break;
  171. case 0: param.sched_priority = 0; policy =SCHED_OTHER; break;
  172. case +1: param.sched_priority = (sched_get_priority_max(SCHED_RR)-sched_get_priority_min(SCHED_RR))/2; policy =SCHED_RR; break;
  173. case +2: param.sched_priority = sched_get_priority_max(SCHED_RR); policy =SCHED_RR; break;
  174. }
  175. if(( rc = pthread_setschedparam(threadid, policy, &param)) != 0)
  176. DBGLOG("pthread_setschedparam error: %d policy=%i pr=%i id=%" I64F "u PID=%i", rc,policy,param.sched_priority,(unsigned __int64) threadid,getpid());
  177. else
  178. DBGLOG("priority set id=%" I64F "u policy=%i pri=%i PID=%i",(unsigned __int64) threadid,policy,param.sched_priority,getpid());
  179. #endif
  180. }
  181. }
  182. void Thread::adjustNiceLevel()
  183. {
  184. #if defined(_WIN32)
  185. int priority;
  186. if(nicelevel < -15)
  187. priority = THREAD_PRIORITY_TIME_CRITICAL;
  188. else if(nicelevel >= -15 && nicelevel < -10)
  189. priority = THREAD_PRIORITY_HIGHEST;
  190. else if(nicelevel >= -10 && nicelevel < 0)
  191. priority = THREAD_PRIORITY_ABOVE_NORMAL;
  192. else if(nicelevel == 0)
  193. priority = THREAD_PRIORITY_NORMAL;
  194. else if(nicelevel > 0 && nicelevel <= 10)
  195. priority = THREAD_PRIORITY_BELOW_NORMAL;
  196. else if(nicelevel > 10 && nicelevel <= 15)
  197. priority = THREAD_PRIORITY_LOWEST;
  198. else if(nicelevel >15)
  199. priority = THREAD_PRIORITY_IDLE;
  200. SetThreadPriority(hThread, priority);
  201. #elif defined(__linux__)
  202. setpriority(PRIO_PROCESS, 0, nicelevel);
  203. #else
  204. UNIMPLEMENTED;
  205. #endif
  206. }
  207. bool Thread::isCurrentThread() const
  208. {
  209. return GetCurrentThreadId() == threadid;
  210. }
  211. // _nicelevel ranges from -20 to 19, the higher the nice level, the less cpu time the thread will get.
  212. void Thread::setNice(int _nicelevel)
  213. {
  214. if (_nicelevel < -20 || _nicelevel > 19)
  215. throw MakeStringException(0, "nice level should be between -20 and 19");
  216. if(alive)
  217. throw MakeStringException(0, "nice can only be set before the thread is started.");
  218. nicelevel = _nicelevel;
  219. }
  220. void Thread::setStackSize(size32_t size)
  221. {
  222. stacksize = (unsigned short)(size/0x1000);
  223. }
  224. void Thread::setDefaultStackSize(size32_t size)
  225. {
  226. defaultThreadStackSize = size; // has no effect under windows (though may be used for calculations later)
  227. }
  228. int Thread::begin()
  229. {
  230. if(nicelevel)
  231. adjustNiceLevel();
  232. #ifndef _WIN32
  233. starting.signal();
  234. suspend.wait();
  235. #endif
  236. int ret=-1;
  237. try {
  238. ret = run();
  239. }
  240. catch (IException *e)
  241. {
  242. handleException(e);
  243. }
  244. #ifndef NO_CATCHALL
  245. catch (...)
  246. {
  247. handleException(MakeStringException(0, "Unknown exception in Thread %s", getName()));
  248. }
  249. #endif
  250. callThreadTerminationHooks();
  251. #ifdef _WIN32
  252. #ifndef _DEBUG
  253. CloseHandle(hThread); // leak handle when debugging,
  254. // fixes some lockups/crashes in the debugger when lots of threads being created
  255. #endif
  256. hThread = NULL;
  257. #endif
  258. //alive = false; // not safe here
  259. return ret;
  260. }
  261. void Thread::handleException(IException *e)
  262. {
  263. assertex(exceptionHandlers);
  264. if (exceptionHandlers->ordinality() == 0)
  265. {
  266. PrintExceptionLog(e,getName());
  267. //throw; // don't rethrow unhandled, preferable over alternative of causing process death
  268. e->Release();
  269. }
  270. else
  271. {
  272. PrintExceptionLog(e,getName());
  273. bool handled = false;
  274. ForEachItemIn(ie, *exceptionHandlers)
  275. {
  276. IExceptionHandler *handler = (IExceptionHandler *) exceptionHandlers->item(ie);
  277. handled = handler->fireException(e) || handled;
  278. }
  279. if (!handled)
  280. {
  281. // if nothing choose to handle it.
  282. EXCLOG(e, NULL);
  283. //throw e; // don't rethrow unhandled, preferable over alternative of causing process death
  284. }
  285. e->Release();
  286. }
  287. }
  288. void Thread::init(const char *_name)
  289. {
  290. #ifdef _WIN32
  291. hThread = NULL;
  292. #endif
  293. threadid = 0;
  294. tidlog = 0;
  295. alive = false;
  296. cthreadname.threadname = (NULL == _name) ? NULL : strdup(_name);
  297. ithreadname = &cthreadname;
  298. prioritydelta = 0;
  299. nicelevel = 0;
  300. stacksize = 0; // default is EXE default stack size (set by /STACK)
  301. }
  302. void Thread::start()
  303. {
  304. if (alive) {
  305. WARNLOG("Thread::start(%s) - Thread already started!",getName());
  306. PrintStackReport();
  307. #ifdef _DEBUG
  308. throw MakeStringException(-1,"Thread::start(%s) - Thread already started!",getName());
  309. #endif
  310. return;
  311. }
  312. Link();
  313. startRelease();
  314. }
  315. void Thread::startRelease()
  316. {
  317. assertex(!alive);
  318. stopped.reinit(0); // just in case restarting
  319. #ifdef _WIN32
  320. hThread = (HANDLE)_beginthreadex(NULL, 0x1000*(unsigned)stacksize, Thread::_threadmain, this, CREATE_SUSPENDED, (unsigned *)&threadid);
  321. if (!hThread || !threadid)
  322. {
  323. Release();
  324. throw makeOsException(GetLastError());
  325. }
  326. #else
  327. int status;
  328. unsigned numretrys = 8;
  329. unsigned delay = 1000;
  330. loop {
  331. pthread_attr_t attr;
  332. pthread_attr_init(&attr);
  333. pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
  334. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  335. if (stacksize)
  336. pthread_attr_setstacksize(&attr, (unsigned)stacksize*0x1000);
  337. else if (defaultThreadStackSize)
  338. pthread_attr_setstacksize(&attr, defaultThreadStackSize);
  339. else {
  340. #ifndef __64BIT__ // no need to cap 64bit
  341. size_t defss=0;
  342. pthread_attr_getstacksize(&attr, &defss);
  343. if (defss>LINUX_STACKSIZE_CAP)
  344. pthread_attr_setstacksize(&attr, LINUX_STACKSIZE_CAP);
  345. #endif
  346. }
  347. status = pthread_create(&threadid, &attr, Thread::_threadmain, this);
  348. if ((status==EAGAIN)||(status==EINTR)) {
  349. if (numretrys--==0)
  350. break;
  351. WARNLOG("pthread_create(%d): Out of threads, retrying...",status);
  352. Sleep(delay);
  353. delay *= 2;
  354. }
  355. else
  356. break;
  357. }
  358. if (status) {
  359. threadid = 0;
  360. Release();
  361. ERRLOG("pthread_create returns %d",status);
  362. PrintStackReport();
  363. PrintMemoryReport();
  364. StringBuffer s;
  365. getThreadList(s);
  366. ERRLOG("Running threads:\n %s",s.str());
  367. throw makeOsException(status);
  368. }
  369. unsigned retryCount = 10;
  370. loop
  371. {
  372. if (starting.wait(1000*10))
  373. break;
  374. else if (0 == --retryCount)
  375. throw MakeStringException(-1, "Thread::start(%s) failed", getName());
  376. WARNLOG("Thread::start(%s) stalled, waiting to start, retrying", getName());
  377. }
  378. #endif
  379. alive = true;
  380. if (prioritydelta)
  381. adjustPriority(prioritydelta);
  382. {
  383. CriticalBlock block(ThreadListSem);
  384. ThreadList.zap(*this); // just in case restarting
  385. ThreadList.append(*this);
  386. }
  387. #ifdef _WIN32
  388. DWORD count = ResumeThread(hThread);
  389. assertex(count == 1);
  390. #else
  391. suspend.signal();
  392. #endif
  393. }
  394. bool Thread::join(unsigned timeout)
  395. {
  396. if (!alive&&!threadid) {
  397. #ifdef _DEBUG
  398. PROGLOG("join on unstarted thread!");
  399. PrintStackReport();
  400. #endif
  401. return true;
  402. }
  403. if (!stopped.wait(timeout))
  404. return false;
  405. if (!alive) // already joined
  406. {
  407. stopped.signal();
  408. return true;
  409. }
  410. unsigned st = 0;
  411. loop { // this is to prevent race with destroy
  412. // (because Thread objects are not always link counted!)
  413. {
  414. SpinBlock block(ThreadDestroyListLock);
  415. if (ThreadDestroyList.find(*this)==NotFound)
  416. break;
  417. }
  418. #ifdef _DEBUG
  419. if (st==10)
  420. PROGLOG("Thread::join race");
  421. #endif
  422. Sleep(st); // switch back to exiting thread (not very elegant!)
  423. st++;
  424. if (st>10)
  425. st = 10; // note must be non-zero for high priority threads
  426. }
  427. #ifdef _DEBUG
  428. int c = getLinkCount();
  429. if (c>=DEAD_PSEUDO_COUNT) {
  430. PROGLOG("Dead/Dying thread joined! %d",c);
  431. PrintStackReport();
  432. }
  433. #endif
  434. alive = false; // should be safe here
  435. stopped.signal(); // signal stopped again, to prevent any parallel call from blocking.
  436. return true;
  437. }
  438. Thread::~Thread()
  439. {
  440. ithreadname = &cthreadname; // safer (as derived classes destroyed)
  441. #ifdef _DEBUG
  442. if (alive) {
  443. if (!stopped.wait(0)) { // see if fell out of threadmain and signal stopped
  444. PROGLOG("Live thread killed! %s",getName());
  445. PrintStackReport();
  446. }
  447. // don't need to resignal as we are on way out
  448. }
  449. #endif
  450. Link();
  451. // DBGLOG("Thread %x (%s) destroyed\n", threadid, threadname);
  452. {
  453. CriticalBlock block(ThreadListSem);
  454. ThreadList.zap(*this);
  455. }
  456. free(cthreadname.threadname);
  457. cthreadname.threadname = NULL;
  458. }
  459. unsigned getThreadCount()
  460. {
  461. CriticalBlock block(ThreadListSem);
  462. return ThreadList.ordinality();
  463. }
  464. StringBuffer & getThreadList(StringBuffer &str)
  465. {
  466. CriticalBlock block(ThreadListSem);
  467. ForEachItemIn(i,ThreadList) {
  468. Thread &item=ThreadList.item(i);
  469. item.getInfo(str).append("\n");
  470. }
  471. return str;
  472. }
  473. StringBuffer &getThreadName(int thandle,unsigned tid,StringBuffer &name)
  474. {
  475. CriticalBlock block(ThreadListSem);
  476. bool found=false;
  477. ForEachItemIn(i,ThreadList) {
  478. Thread &item=ThreadList.item(i);
  479. int h;
  480. unsigned t;
  481. const char *s = item.getLogInfo(h,t);
  482. if (s&&*s&&((thandle==0)||(h==thandle))&&((tid==0)||(t==tid))) {
  483. if (found) {
  484. name.clear();
  485. break; // only return if unambiguous
  486. }
  487. name.append(s);
  488. found = true;
  489. }
  490. }
  491. return name;
  492. }
  493. // CThreadedPersistent
  494. CThreadedPersistent::CThreadedPersistent(const char *name, IThreaded *_owner) : athread(*this, name), owner(_owner)
  495. {
  496. halt = false;
  497. atomic_set(&state, s_ready);
  498. athread.start();
  499. }
  500. CThreadedPersistent::~CThreadedPersistent()
  501. {
  502. join(INFINITE);
  503. halt = true;
  504. sem.signal();
  505. athread.join();
  506. }
  507. void CThreadedPersistent::main()
  508. {
  509. loop
  510. {
  511. sem.wait();
  512. if (halt)
  513. break;
  514. try
  515. {
  516. owner->main();
  517. // Note we do NOT call the thread reset hook here - these threads are expected to be able to preserve state, I think
  518. }
  519. catch (IException *e)
  520. {
  521. VStringBuffer errMsg("CThreadedPersistent (%s)", athread.getName());
  522. EXCLOG(e, errMsg.str());
  523. exception.setown(e);
  524. joinSem.signal(); // leave in running state, signal to join to handle
  525. continue;
  526. }
  527. if (!atomic_cas(&state, s_ready, s_running))
  528. if (atomic_cas(&state, s_ready, s_joining))
  529. joinSem.signal();
  530. }
  531. }
  532. void CThreadedPersistent::start()
  533. {
  534. if (!atomic_cas(&state, s_running, s_ready))
  535. {
  536. VStringBuffer msg("CThreadedPersistent::start(%s) - not ready", athread.getName());
  537. WARNLOG("%s", msg.str());
  538. PrintStackReport();
  539. throw MakeStringExceptionDirect(-1, msg.str());
  540. }
  541. sem.signal();
  542. }
  543. bool CThreadedPersistent::join(unsigned timeout)
  544. {
  545. if (atomic_cas(&state, s_joining, s_running))
  546. {
  547. if (!joinSem.wait(timeout))
  548. {
  549. if (atomic_cas(&state, s_running, s_joining)) // if still joining, restore running state
  550. return false;
  551. // if here, main() set s_ready after timeout and has or will signal
  552. if (!joinSem.wait(60000)) // should be instant
  553. throwUnexpected();
  554. return true;
  555. }
  556. if (exception.get())
  557. {
  558. // switch back to ready state and throw
  559. Owned<IException> e = exception.getClear();
  560. if (!atomic_cas(&state, s_ready, s_joining))
  561. throwUnexpected();
  562. throw e.getClear();
  563. }
  564. }
  565. return true;
  566. }
  567. //class CAsyncFor
  568. void CAsyncFor::For(unsigned num,unsigned maxatonce,bool abortFollowingException, bool shuffled)
  569. {
  570. if (num <= 1)
  571. {
  572. if (num == 1)
  573. Do(0);
  574. return;
  575. }
  576. Mutex errmutex;
  577. Semaphore ready;
  578. Semaphore finished;
  579. IException *e=NULL;
  580. Owned<IShuffledIterator> shuffler;
  581. if (shuffled) {
  582. shuffler.setown(createShuffledIterator(num));
  583. shuffler->first(); // prime (needed to make thread safe)
  584. }
  585. unsigned i;
  586. if (maxatonce==1) { // no need for threads
  587. for (i=0;i<num;i++) {
  588. unsigned idx = shuffled?shuffler->lookup(i):i;
  589. try {
  590. Do(idx);
  591. }
  592. catch (IException * _e)
  593. {
  594. if (e)
  595. _e->Release(); // only return first
  596. else
  597. e = _e;
  598. if (abortFollowingException)
  599. break;
  600. }
  601. }
  602. }
  603. else {
  604. class cdothread: public Thread
  605. {
  606. public:
  607. Mutex *errmutex;
  608. Semaphore &ready;
  609. Semaphore &finished;
  610. int timeout;
  611. IException *&erre;
  612. unsigned idx;
  613. CAsyncFor *self;
  614. cdothread(CAsyncFor *_self,unsigned _idx,Semaphore &_ready,Semaphore &_finished,Mutex *_errmutex,IException *&_e)
  615. : Thread("CAsyncFor"),ready(_ready),finished(_finished),erre(_e)
  616. {
  617. errmutex =_errmutex;
  618. idx = _idx;
  619. self = _self;
  620. }
  621. int run()
  622. {
  623. try {
  624. self->Do(idx);
  625. }
  626. catch (IException * _e)
  627. {
  628. synchronized block(*errmutex);
  629. if (erre)
  630. _e->Release(); // only return first
  631. else
  632. erre = _e;
  633. }
  634. #ifndef NO_CATCHALL
  635. catch (...)
  636. {
  637. synchronized block(*errmutex);
  638. if (!erre)
  639. erre = MakeStringException(0, "Unknown exception in Thread %s", getName());
  640. }
  641. #endif
  642. ready.signal();
  643. finished.signal();
  644. return 0;
  645. }
  646. };
  647. if (maxatonce==0)
  648. maxatonce = num;
  649. for (i=0;(i<num)&&(i<maxatonce);i++)
  650. ready.signal();
  651. for (i=0;i<num;i++) {
  652. ready.wait();
  653. if (abortFollowingException && e) break;
  654. Thread *thread = new cdothread(this,shuffled?shuffler->lookup(i):i,ready,finished,&errmutex,e);
  655. thread->startRelease();
  656. }
  657. while (i--)
  658. finished.wait();
  659. }
  660. if (e)
  661. throw e;
  662. }
  663. //---------------------------------------------------------------------------------------------------------------------
  664. class CSimpleFunctionThread : public Thread
  665. {
  666. std::function<void()> func;
  667. public:
  668. inline CSimpleFunctionThread(std::function<void()> _func) : Thread("TaskProcessor"), func(_func) { }
  669. virtual int run()
  670. {
  671. func();
  672. return 1;
  673. }
  674. };
  675. void asyncStart(IThreaded & threaded)
  676. {
  677. CThreaded * thread = new CThreaded("AsyncStart", &threaded);
  678. thread->startRelease();
  679. }
  680. void asyncStart(const char * name, IThreaded & threaded)
  681. {
  682. CThreaded * thread = new CThreaded(name, &threaded);
  683. thread->startRelease();
  684. }
  685. //Experimental - is this a useful function to replace some uses of IThreaded?
  686. void asyncStart(std::function<void()> func)
  687. {
  688. (new CSimpleFunctionThread(func))->startRelease();
  689. }
  690. // ---------------------------------------------------------------------------
  691. // Thread Pools
  692. // ---------------------------------------------------------------------------
  693. class CPooledThreadWrapper;
  694. class CThreadPoolBase
  695. {
  696. public:
  697. virtual ~CThreadPoolBase() {}
  698. protected: friend class CPooledThreadWrapper;
  699. IExceptionHandler *exceptionHandler;
  700. CriticalSection crit;
  701. StringAttr poolname;
  702. int donewaiting;
  703. Semaphore donesem;
  704. PointerArray waitingsems;
  705. UnsignedArray waitingids;
  706. bool stopall;
  707. unsigned defaultmax;
  708. unsigned targetpoolsize;
  709. unsigned delay;
  710. Semaphore availsem;
  711. atomic_t numrunning;
  712. virtual void notifyStarted(CPooledThreadWrapper *item)=0;
  713. virtual bool notifyStopped(CPooledThreadWrapper *item)=0;
  714. };
  715. class CPooledThreadWrapper: public Thread
  716. {
  717. PooledThreadHandle handle;
  718. IPooledThread *thread;
  719. Semaphore sem;
  720. CThreadPoolBase &parent;
  721. char *runningname;
  722. public:
  723. IMPLEMENT_IINTERFACE;
  724. CPooledThreadWrapper(CThreadPoolBase &_parent,
  725. PooledThreadHandle _handle,
  726. IPooledThread *_thread) // takes ownership of thread
  727. : Thread(StringBuffer("Member of thread pool: ").append(_parent.poolname).str()), parent(_parent)
  728. {
  729. thread = _thread;
  730. handle = _handle;
  731. runningname = strdup(_parent.poolname);
  732. }
  733. ~CPooledThreadWrapper()
  734. {
  735. thread->Release();
  736. free(runningname);
  737. }
  738. void setName(const char *name) { free(runningname); runningname=strdup(name); }
  739. void setHandle(PooledThreadHandle _handle) { handle = _handle; }
  740. PooledThreadHandle queryHandle() { return handle; }
  741. IPooledThread &queryThread() { return *thread; }
  742. void setThread(IPooledThread *_thread) { thread = _thread; } // takes ownership
  743. bool isStopped() { return (handle==0); }
  744. PooledThreadHandle markStopped()
  745. {
  746. PooledThreadHandle ret=handle;
  747. handle = 0;
  748. if (ret) // JCSMORE - I can't see how handle can not be set if here..
  749. atomic_dec(&parent.numrunning);
  750. return ret;
  751. }
  752. void markStarted()
  753. {
  754. atomic_inc(&parent.numrunning);
  755. }
  756. int run()
  757. {
  758. do
  759. {
  760. sem.wait();
  761. {
  762. CriticalBlock block(parent.crit); // to synchronize
  763. if (parent.stopall)
  764. break;
  765. }
  766. parent.notifyStarted(this);
  767. try
  768. {
  769. char *&threadname = cthreadname.threadname;
  770. char *temp = threadname; // swap running name and threadname
  771. threadname = runningname;
  772. runningname = temp;
  773. thread->main();
  774. temp = threadname; // and back
  775. threadname = runningname;
  776. runningname = temp;
  777. }
  778. catch (IException *e)
  779. {
  780. char *&threadname = cthreadname.threadname;
  781. char *temp = threadname; // swap back
  782. threadname = runningname;
  783. runningname = temp;
  784. handleException(e);
  785. }
  786. #ifndef NO_CATCHALL
  787. catch (...)
  788. {
  789. char *&threadname = cthreadname.threadname;
  790. char *temp = threadname; // swap back
  791. threadname = runningname;
  792. runningname = temp;
  793. handleException(MakeStringException(0, "Unknown exception in Thread from pool %s", parent.poolname.get()));
  794. }
  795. #endif
  796. callThreadTerminationHooks(); // Reset any pre-thread state.
  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. }