mpcomm.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161
  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. #define mp_decl __declspec(dllexport)
  14. /* TBD
  15. lost packet disposal
  16. synchronous send
  17. connection protocol (HRPC);
  18. look at all timeouts
  19. */
  20. #include "platform.h"
  21. #include "portlist.h"
  22. #include "jlib.hpp"
  23. #include <limits.h>
  24. #include "jsocket.hpp"
  25. #include "jmutex.hpp"
  26. #include "jutil.hpp"
  27. #include "jthread.hpp"
  28. #include "jqueue.tpp"
  29. #include "jsuperhash.hpp"
  30. #include "jmisc.hpp"
  31. #include "mpcomm.hpp"
  32. #include "mpbuff.hpp"
  33. #include "mputil.hpp"
  34. #include "mplog.hpp"
  35. #ifdef _MSC_VER
  36. #pragma warning (disable : 4355)
  37. #endif
  38. //#define _TRACE
  39. //#define _FULLTRACE
  40. #if 1 // #ifdef _FULLTRACE
  41. #define _TRACELINKCLOSED
  42. #endif
  43. #define _TRACEMPSERVERNOTIFYCLOSED
  44. #define _TRACEORPHANS
  45. #define REFUSE_STALE_CONNECTION
  46. #define MP_PROTOCOL_VERSION 0x102
  47. #define MP_PROTOCOL_VERSIONV6 0x202 // extended for IPV6
  48. // These should really be configurable
  49. #define CANCELTIMEOUT 1000 // 1 sec
  50. #define CONNECT_TIMEOUT (5*60*1000) // 5 mins
  51. #define CONNECT_READ_TIMEOUT (10*1000) // 10 seconds. NB: used by connect readtms loop (see loopCnt)
  52. #define CONNECT_TIMEOUT_INTERVAL 1000 // 1 sec
  53. #define CONNECT_RETRYCOUNT 180 // Overall max connect time is = CONNECT_RETRYCOUNT * CONNECT_READ_TIMEOUT
  54. #define CONNECT_TIMEOUT_MINSLEEP 2000 // random range: CONNECT_TIMEOUT_MINSLEEP to CONNECT_TIMEOUT_MAXSLEEP milliseconds
  55. #define CONNECT_TIMEOUT_MAXSLEEP 5000
  56. #define CONFIRM_TIMEOUT (90*1000) // 1.5 mins
  57. #define CONFIRM_TIMEOUT_INTERVAL 5000 // 5 secs
  58. #define TRACESLOW_THRESHOLD 1000 // 1 sec
  59. #define VERIFY_DELAY (1*60*1000) // 1 Minute
  60. #define VERIFY_TIMEOUT (1*60*1000) // 1 Minute
  61. #define DIGIT1 U64C(0x10000000000) // (256ULL*256ULL*256ULL*65536ULL)
  62. #define DIGIT2 U64C(0x100000000) // (256ULL*256ULL*65536ULL)
  63. #define DIGIT3 U64C(0x1000000) // (256ULL*65536ULL)
  64. #define DIGIT4 U64C(0x10000) // (65536ULL)
  65. #define _TRACING
  66. static CriticalSection verifysect;
  67. static CriticalSection childprocesssect;
  68. static UnsignedArray childprocesslist;
  69. // IPv6 TBD
  70. struct SocketEndpointV4
  71. {
  72. byte ip[4];
  73. unsigned short port;
  74. SocketEndpointV4() {};
  75. SocketEndpointV4(const SocketEndpoint &val) { set(val); }
  76. void set(const SocketEndpoint &val)
  77. {
  78. port = val.port;
  79. if (val.getNetAddress(sizeof(ip),&ip)!=sizeof(ip))
  80. IPV6_NOT_IMPLEMENTED();
  81. }
  82. void get(SocketEndpoint &val)
  83. {
  84. val.setNetAddress(sizeof(ip),&ip);
  85. val.port = port;
  86. }
  87. };
  88. class PacketHeader // standard packet header - no virtuals
  89. {
  90. public:
  91. static unsigned nextseq;
  92. static unsigned lasttick;
  93. void initseq()
  94. {
  95. sequence = msTick();
  96. lasttick = sequence;
  97. if (sequence-nextseq>USHRT_MAX)
  98. sequence = nextseq++;
  99. else
  100. nextseq = sequence+1;
  101. }
  102. PacketHeader(size32_t _size, SocketEndpoint &_sender, SocketEndpoint &_target, mptag_t _tag, mptag_t _replytag)
  103. {
  104. size = _size;
  105. tag = _tag;
  106. sender.set(_sender);
  107. target.set(_target);
  108. replytag = _replytag;
  109. flags = 0;
  110. version = MP_PROTOCOL_VERSION;
  111. initseq();
  112. }
  113. PacketHeader() {}
  114. size32_t size; // 0 total packet size
  115. mptag_t tag; // 4 packet tag (kind)
  116. unsigned short version; // 8 protocol version
  117. unsigned short flags; // 10 flags
  118. SocketEndpointV4 sender; // 12 who sent
  119. SocketEndpointV4 target; // 18 who destined for
  120. mptag_t replytag; // 24 used for reply
  121. unsigned sequence; // 28 packet type dependant
  122. // Total 32
  123. void setMessageFields(CMessageBuffer &mb)
  124. {
  125. SocketEndpoint ep;
  126. sender.get(ep);
  127. mb.init(ep,tag,replytag);
  128. }
  129. };
  130. class PacketHeaderV6 : public PacketHeader
  131. {
  132. unsigned senderex[4]; // 32
  133. unsigned targetex[4]; // 48
  134. // total 64
  135. void setMessageFields(CMessageBuffer &mb)
  136. {
  137. SocketEndpoint ep;
  138. ep.setNetAddress(sizeof(senderex),&senderex);
  139. ep.port = sender.port;
  140. mb.init(ep,tag,replytag);
  141. }
  142. };
  143. unsigned PacketHeader::nextseq=0;
  144. unsigned PacketHeader::lasttick=0;
  145. #define MINIMUMPACKETSIZE sizeof(PacketHeader)
  146. #define MAXDATAPERPACKET 50000
  147. struct MultiPacketHeader
  148. {
  149. mptag_t tag;
  150. size32_t ofs;
  151. size32_t size;
  152. unsigned idx;
  153. unsigned numparts;
  154. size32_t total;
  155. StringBuffer &getDetails(StringBuffer &out) const
  156. {
  157. out.append("MultiPacketHeader: ");
  158. out.append("tag=").append((unsigned)tag);
  159. out.append(",ofs=").append(ofs);
  160. out.append(",size=").append(size);
  161. out.append(",idx=").append(idx);
  162. out.append(",numparts=").append(numparts);
  163. out.append(",total=").append(total);
  164. return out;
  165. }
  166. };
  167. //
  168. class CMPException: public CInterface, public IMP_Exception
  169. {
  170. public:
  171. IMPLEMENT_IINTERFACE;
  172. CMPException(MessagePassingError err,const SocketEndpoint &ep) : error(err), endpoint(ep)
  173. {
  174. }
  175. StringBuffer & errorMessage(StringBuffer &str) const
  176. {
  177. StringBuffer tmp;
  178. switch (error) {
  179. case MPERR_ok: str.append("OK"); break;
  180. case MPERR_connection_failed: str.appendf("MP connect failed (%s)",endpoint.getUrlStr(tmp).str()); break;
  181. case MPERR_process_not_in_group: str.appendf("Current process not in Communicator group"); break;
  182. case MPERR_protocol_version_mismatch: str.appendf("Protocol version mismatch (%s)",endpoint.getUrlStr(tmp).str()); break;
  183. case MPERR_link_closed: str.appendf("MP link closed (%s)",endpoint.getUrlStr(tmp).str()); break;
  184. }
  185. return str;
  186. }
  187. int errorCode() const { return error; }
  188. MessageAudience errorAudience() const
  189. {
  190. return MSGAUD_user;
  191. }
  192. virtual const SocketEndpoint &queryEndpoint() const { return endpoint; }
  193. private:
  194. MessagePassingError error;
  195. SocketEndpoint endpoint;
  196. };
  197. class CBufferQueueNotify
  198. {
  199. public:
  200. virtual bool notify(CMessageBuffer *)=0;
  201. virtual bool notifyClosed(SocketEndpoint &closedep)=0; // called when connection closed
  202. };
  203. class CBufferQueueWaiting
  204. {
  205. public:
  206. enum QWenum { QWcontinue, QWdequeue, QWprobe };
  207. Semaphore sem;
  208. CBufferQueueNotify &waiting;
  209. bool probe;
  210. CBufferQueueWaiting(CBufferQueueNotify& _waiting,bool _probe) : waiting(_waiting) { probe = _probe; }
  211. QWenum notify(CMessageBuffer *b)
  212. {
  213. // check this for DLL unloaded TBD
  214. if (waiting.notify(b)) {
  215. sem.signal();
  216. return probe?QWprobe:QWdequeue;
  217. }
  218. return QWcontinue;
  219. }
  220. QWenum notifyClosed(SocketEndpoint &ep)
  221. {
  222. // check this for DLL unloaded TBD
  223. if (waiting.notifyClosed(ep)) {
  224. sem.signal();
  225. return QWdequeue;
  226. }
  227. return QWcontinue;
  228. }
  229. };
  230. typedef CopyReferenceArrayOf<CBufferQueueWaiting> CWaitingArray;
  231. class CBufferQueue
  232. {
  233. QueueOf<CMessageBuffer, false> received;
  234. CWaitingArray waiting;
  235. CriticalSection sect;
  236. public:
  237. CBufferQueue()
  238. {
  239. }
  240. void enqueue(CMessageBuffer *b)
  241. {
  242. CriticalBlock block(sect);
  243. unsigned iter=0;
  244. loop {
  245. ForEachItemIn(i,waiting) {
  246. CBufferQueueWaiting::QWenum r = waiting.item(i).notify(b);
  247. if (r!=CBufferQueueWaiting::QWcontinue) {
  248. waiting.remove(i);
  249. if (r==CBufferQueueWaiting::QWdequeue)
  250. return;
  251. //CBufferQueueWaiting::QWprobe
  252. break;
  253. }
  254. }
  255. if (b->getReplyTag() != TAG_CANCEL)
  256. break;
  257. if (iter++==10) {
  258. delete b;
  259. return;
  260. }
  261. CriticalUnblock unblock(sect);
  262. Sleep(CANCELTIMEOUT/10); // to avoid race conditions (cancel eventually times out)
  263. }
  264. received.enqueue(b);
  265. }
  266. bool wait(CBufferQueueNotify &nfy,bool probe,CTimeMon &tm)
  267. {
  268. CriticalBlock block(sect);
  269. bool probegot = false;
  270. ForEachQueueItemIn(i,received) {
  271. if (nfy.notify(received.item(i))) {
  272. if (probe) {
  273. probegot = true;
  274. }
  275. else {
  276. received.dequeue(i);
  277. return true;
  278. }
  279. }
  280. }
  281. if (probegot)
  282. return true;
  283. unsigned remaining;
  284. if (tm.timedout(&remaining))
  285. return false;
  286. CBufferQueueWaiting qwaiting(nfy,probe);
  287. waiting.append(qwaiting);
  288. sect.leave();
  289. bool ok = qwaiting.sem.wait(remaining);
  290. sect.enter();
  291. if (!ok) {
  292. ok = qwaiting.sem.wait(0);
  293. if (!ok)
  294. waiting.zap(qwaiting);
  295. }
  296. return ok;
  297. }
  298. unsigned flush(CBufferQueueNotify &nfy)
  299. {
  300. unsigned count = 0;
  301. CriticalBlock block(sect);
  302. ForEachQueueItemInRev(i,received) {
  303. if (nfy.notify(received.item(i))) {
  304. count++;
  305. delete received.dequeue(i);
  306. }
  307. }
  308. return count;
  309. }
  310. void notifyClosed(SocketEndpoint &ep)
  311. {
  312. CriticalBlock block(sect);
  313. ForEachItemInRev(i,waiting) {
  314. CBufferQueueWaiting::QWenum r = waiting.item(i).notifyClosed(ep);
  315. if (r!=CBufferQueueWaiting::QWcontinue) {
  316. waiting.remove(i);
  317. }
  318. }
  319. }
  320. StringBuffer &getReceiveQueueDetails(StringBuffer &buf)
  321. {
  322. CriticalBlock block(sect);
  323. ForEachQueueItemIn(i,received) {
  324. received.item(i)->getDetails(buf).append('\n');
  325. }
  326. return buf;
  327. }
  328. };
  329. static UnsignedShortArray freetags;
  330. static unsigned nextfreetag=0;
  331. unsigned short generateDynamicTag()
  332. {
  333. if (freetags.ordinality())
  334. return freetags.popGet();
  335. return nextfreetag++;
  336. }
  337. void releaseDynamicTag(unsigned short tag)
  338. {
  339. freetags.append(tag);
  340. }
  341. bool check_kernparam(const char *path, int *value)
  342. {
  343. #ifdef __linux__
  344. FILE *f = fopen(path,"r");
  345. char res[32];
  346. char *r = 0;
  347. if (f) {
  348. r = fgets(res, sizeof(res), f);
  349. fclose(f);
  350. if (r) {
  351. *value = atoi(r);
  352. return true;
  353. }
  354. }
  355. #endif
  356. return false;
  357. }
  358. bool check_somaxconn(int *val)
  359. {
  360. return check_kernparam("/proc/sys/net/core/somaxconn", val);
  361. }
  362. class CMPServer;
  363. class CMPChannel;
  364. class CMPConnectThread: public Thread
  365. {
  366. bool running;
  367. ISocket *listensock;
  368. CMPServer *parent;
  369. int mpSoMaxConn;
  370. unsigned mpTraceLevel;
  371. void checkSelfDestruct(void *p,size32_t sz);
  372. public:
  373. CMPConnectThread(CMPServer *_parent, unsigned port);
  374. ~CMPConnectThread()
  375. {
  376. ::Release(listensock);
  377. }
  378. int run();
  379. void start(unsigned short port);
  380. void stop()
  381. {
  382. if (running) {
  383. running = false;
  384. listensock->cancel_accept();
  385. if (!join(1000*60*5)) // should be pretty instant
  386. printf("CMPConnectThread::stop timed out\n");
  387. }
  388. }
  389. };
  390. class PingPacketHandler;
  391. class PingReplyPacketHandler;
  392. class MultiPacketHandler;
  393. class BroadcastPacketHandler;
  394. class ForwardPacketHandler;
  395. class UserPacketHandler;
  396. class CMPNotifyClosedThread;
  397. typedef SuperHashTableOf<CMPChannel,SocketEndpoint> CMPChannelHT;
  398. class CMPServer: private CMPChannelHT, implements IMPServer
  399. {
  400. byte RTsalt;
  401. ISocketSelectHandler *selecthandler;
  402. CMPConnectThread *connectthread;
  403. CBufferQueue receiveq;
  404. CMPNotifyClosedThread *notifyclosedthread;
  405. CriticalSection sect;
  406. protected:
  407. unsigned short port;
  408. public:
  409. bool checkclosed;
  410. bool tryReopenChannel = false;
  411. // packet handlers
  412. PingPacketHandler *pingpackethandler; // TAG_SYS_PING
  413. PingReplyPacketHandler *pingreplypackethandler; // TAG_SYS_PING_REPLY
  414. ForwardPacketHandler *forwardpackethandler; // TAG_SYS_FORWARD
  415. MultiPacketHandler *multipackethandler; // TAG_SYS_MULTI
  416. BroadcastPacketHandler *broadcastpackethandler; // TAG_SYS_BCAST
  417. UserPacketHandler *userpackethandler; // default
  418. IMPLEMENT_IINTERFACE_USING(CMPChannelHT);
  419. CMPServer(unsigned _port);
  420. ~CMPServer();
  421. void start();
  422. virtual void stop();
  423. unsigned short getPort() { return port; }
  424. void setPort(unsigned short _port) { port = _port; }
  425. CMPChannel *lookup(const SocketEndpoint &remoteep);
  426. ISocketSelectHandler &querySelectHandler() { return *selecthandler; };
  427. CBufferQueue &getReceiveQ() { return receiveq; }
  428. void checkTagOK(mptag_t tag);
  429. bool recv(CMessageBuffer &mbuf, const SocketEndpoint *ep, mptag_t tag, CTimeMon &tm);
  430. void flush(mptag_t tag);
  431. unsigned probe(const SocketEndpoint *ep, mptag_t tag, CTimeMon &tm, SocketEndpoint &sender);
  432. void cancel(const SocketEndpoint *ep, mptag_t tag);
  433. bool nextChannel(CMPChannel *&c);
  434. void addConnectionMonitor(IConnectionMonitor *monitor);
  435. void removeConnectionMonitor(IConnectionMonitor *monitor);
  436. void notifyClosed(SocketEndpoint &ep, bool trace);
  437. StringBuffer &getReceiveQueueDetails(StringBuffer &buf)
  438. {
  439. return receiveq.getReceiveQueueDetails(buf);
  440. }
  441. void removeChannel(CMPChannel *c) { if (c) removeExact(c); }
  442. protected:
  443. void onAdd(void *);
  444. void onRemove(void *e);
  445. unsigned getHashFromElement(const void *e) const;
  446. unsigned getHashFromFindParam(const void *fp) const;
  447. const void * getFindParam(const void *p) const;
  448. bool matchesFindParam(const void * et, const void *fp, unsigned fphash) const;
  449. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CMPChannel,SocketEndpoint);
  450. CriticalSection replyTagSect;
  451. int rettag;
  452. INode *myNode;
  453. public:
  454. virtual mptag_t createReplyTag()
  455. {
  456. // these are short-lived so a simple increment will do (I think this is OK!)
  457. mptag_t ret;
  458. {
  459. CriticalBlock block(replyTagSect);
  460. if (RTsalt==0xff) {
  461. RTsalt = (byte)(getRandom()%16);
  462. rettag = (int)TAG_REPLY_BASE-RTsalt;
  463. }
  464. if (rettag>(int)TAG_REPLY_BASE) { // wrapped
  465. rettag = (int)TAG_REPLY_BASE-RTsalt;
  466. }
  467. ret = (mptag_t)rettag;
  468. rettag -= 16;
  469. }
  470. flush(ret);
  471. return ret;
  472. }
  473. virtual ICommunicator *createCommunicator(IGroup *group, bool outer);
  474. virtual INode *queryMyNode()
  475. {
  476. return myNode;
  477. }
  478. virtual void setOpt(MPServerOpts opt, const char *value)
  479. {
  480. switch (opt)
  481. {
  482. case mpsopt_channelreopen:
  483. {
  484. bool tf = (nullptr != value) ? strToBool(value) : false;
  485. PROGLOG("Setting ChannelReopen = %s", tf ? "true" : "false");
  486. tryReopenChannel = tf;
  487. break;
  488. }
  489. default:
  490. // ignore
  491. break;
  492. }
  493. }
  494. };
  495. //===========================================================================
  496. class CMPNotifyClosedThread: public Thread
  497. {
  498. IArrayOf<IConnectionMonitor> connectionmonitors;
  499. CriticalSection conmonsect;
  500. SimpleInterThreadQueueOf<INode, false> workq;
  501. bool stopping;
  502. CMPServer *parent;
  503. CriticalSection stopsect;
  504. public:
  505. CMPNotifyClosedThread(CMPServer *_parent)
  506. : Thread("CMPNotifyClosedThread")
  507. {
  508. parent = _parent;
  509. stopping = false;
  510. }
  511. ~CMPNotifyClosedThread()
  512. {
  513. IArrayOf<IConnectionMonitor> todelete;
  514. CriticalBlock block(conmonsect);
  515. while (connectionmonitors.ordinality())
  516. todelete.append(connectionmonitors.popGet());
  517. }
  518. void addConnectionMonitor(IConnectionMonitor *monitor)
  519. {
  520. if (monitor)
  521. connectionmonitors.append(*LINK(monitor));
  522. }
  523. void removeConnectionMonitor(IConnectionMonitor *monitor)
  524. {
  525. // called in critical section CMPServer::sect
  526. if (monitor) {
  527. CriticalBlock block(conmonsect);
  528. connectionmonitors.zap(*monitor);
  529. }
  530. }
  531. int run()
  532. {
  533. loop {
  534. try {
  535. Owned<INode> node = workq.dequeue();
  536. if (node->endpoint().isNull())
  537. break;
  538. SocketEndpoint ep = node->endpoint();
  539. parent->getReceiveQ().notifyClosed(ep);
  540. IArrayOf<IConnectionMonitor> toclose;
  541. {
  542. CriticalBlock block(conmonsect);
  543. ForEachItemIn(i1,connectionmonitors) {
  544. toclose.append(*LINK(&connectionmonitors.item(i1)));
  545. }
  546. }
  547. ForEachItemIn(i,toclose) {
  548. toclose.item(i).onClose(ep);
  549. }
  550. }
  551. catch (IException *e) {
  552. FLLOG(MCoperatorWarning, unknownJob, e,"MP writepacket");
  553. e->Release();
  554. }
  555. }
  556. return 0;
  557. }
  558. void stop()
  559. {
  560. {
  561. CriticalBlock block(stopsect);
  562. if (!stopping) {
  563. stopping = true;
  564. SocketEndpoint ep;
  565. workq.enqueue(createINode(ep));
  566. }
  567. }
  568. while (!join(1000*60*3))
  569. PROGLOG("CMPNotifyClosedThread join failed");
  570. }
  571. void notify(SocketEndpoint &ep)
  572. {
  573. CriticalBlock block(stopsect);
  574. if (!stopping&&!ep.isNull()) {
  575. if (workq.ordinality()>100)
  576. PROGLOG("MP: %d waiting to close",workq.ordinality());
  577. workq.enqueue(createINode(ep));
  578. }
  579. }
  580. };
  581. void traceSlowReadTms(const char *msg, ISocket *sock, void *dst, size32_t minSize, size32_t maxSize, size32_t &sizeRead, unsigned timeoutMs, unsigned timeoutChkIntervalMs)
  582. {
  583. dbgassertex(timeoutChkIntervalMs < timeoutMs);
  584. StringBuffer epStr;
  585. CCycleTimer readTmsTimer;
  586. unsigned intervalTimeoutMs = timeoutChkIntervalMs;
  587. loop
  588. {
  589. try
  590. {
  591. sock->readtms(dst, minSize, maxSize, sizeRead, intervalTimeoutMs);
  592. break;
  593. }
  594. catch (IJSOCK_Exception *e)
  595. {
  596. if (JSOCKERR_graceful_close == e->errorCode())
  597. return;
  598. else if (JSOCKERR_timeout_expired != e->errorCode())
  599. throw;
  600. unsigned elapsedMs = readTmsTimer.elapsedMs();
  601. if (elapsedMs >= timeoutMs)
  602. throw;
  603. unsigned remainingMs = timeoutMs-elapsedMs;
  604. if (remainingMs < timeoutChkIntervalMs)
  605. intervalTimeoutMs = remainingMs;
  606. if (0 == epStr.length())
  607. {
  608. SocketEndpoint ep;
  609. sock->getPeerEndpoint(ep);
  610. ep.getUrlStr(epStr);
  611. }
  612. WARNLOG("%s %s, stalled for %d ms so far", msg, epStr.str(), elapsedMs);
  613. }
  614. }
  615. if (readTmsTimer.elapsedMs() >= TRACESLOW_THRESHOLD)
  616. {
  617. if (0 == epStr.length())
  618. {
  619. SocketEndpoint ep;
  620. sock->getPeerEndpoint(ep);
  621. ep.getUrlStr(epStr);
  622. }
  623. WARNLOG("%s %s, took: %d ms", msg, epStr.str(), readTmsTimer.elapsedMs());
  624. }
  625. }
  626. class CMPPacketReader;
  627. class CMPChannel: public CInterface
  628. {
  629. ISocket *channelsock;
  630. CMPServer *parent;
  631. Mutex sendmutex;
  632. Semaphore sendwaitingsig;
  633. unsigned sendwaiting; // number waiting on sendwaitingsem (for multi/single clashes to resolve)
  634. CriticalSection connectsect;
  635. CMPPacketReader *reader;
  636. bool master; // i.e. connected originally
  637. mptag_t multitag; // current multi send in progress
  638. bool closed;
  639. IArrayOf<ISocket> keptsockets;
  640. CriticalSection attachsect;
  641. unsigned __int64 attachaddrval;
  642. SocketEndpoint attachep;
  643. atomic_t attachchk;
  644. protected: friend class CMPServer;
  645. SocketEndpoint remoteep;
  646. SocketEndpoint localep; // who the other end thinks I am
  647. protected: friend class CMPPacketReader;
  648. unsigned lastxfer;
  649. #ifdef _FULLTRACE
  650. unsigned startxfer;
  651. unsigned numiter;
  652. #endif
  653. bool checkReconnect(CTimeMon &tm)
  654. {
  655. if (!parent->tryReopenChannel)
  656. return false;
  657. ::Release(channelsock);
  658. channelsock = nullptr;
  659. if (connect(tm))
  660. return true;
  661. WARNLOG("Failed to reconnect");
  662. return false;
  663. }
  664. bool connect(CTimeMon &tm)
  665. {
  666. // must be called from connectsect
  667. // also in sendmutex
  668. ISocket *newsock=NULL;
  669. unsigned retrycount = CONNECT_RETRYCOUNT;
  670. unsigned remaining;
  671. while (!channelsock) {
  672. try {
  673. StringBuffer str;
  674. #ifdef _TRACE
  675. LOG(MCdebugInfo(100), unknownJob, "MP: connecting to %s",remoteep.getUrlStr(str).str());
  676. #endif
  677. if (((int)tm.timeout)<0)
  678. remaining = CONNECT_TIMEOUT;
  679. else if (tm.timedout(&remaining)) {
  680. #ifdef _FULLTRACE
  681. PROGLOG("MP: connect timed out 1");
  682. #endif
  683. return false;
  684. }
  685. if (remaining<10000)
  686. remaining = 10000; // 10s min granularity for MP
  687. newsock = ISocket::connect_timeout(remoteep,remaining);
  688. newsock->set_keep_alive(true);
  689. #ifdef _FULLTRACE
  690. LOG(MCdebugInfo(100), unknownJob, "MP: connect after socket connect, retrycount = %d", retrycount);
  691. #endif
  692. SocketEndpointV4 id[2];
  693. SocketEndpoint hostep;
  694. hostep.setLocalHost(parent->getPort());
  695. id[0].set(hostep);
  696. id[1].set(remoteep);
  697. unsigned __int64 addrval = DIGIT1*id[0].ip[0] + DIGIT2*id[0].ip[1] + DIGIT3*id[0].ip[2] + DIGIT4*id[0].ip[3] + id[0].port;
  698. #ifdef _TRACE
  699. PROGLOG("MP: connect addrval = %" I64F "u", addrval);
  700. #endif
  701. newsock->write(&id[0],sizeof(id));
  702. #ifdef _FULLTRACE
  703. StringBuffer tmp1;
  704. id[0].getUrlStr(tmp1);
  705. tmp1.append(' ');
  706. id[1].getUrlStr(tmp1);
  707. LOG(MCdebugInfo(100), unknownJob, "MP: connect after socket write %s",tmp1.str());
  708. #endif
  709. size32_t reply = 0;
  710. size32_t rd = 0;
  711. #ifdef _TRACE
  712. LOG(MCdebugInfo(100), unknownJob, "MP: connect after socket write, waiting for read");
  713. #endif
  714. // Wait for connection reply but also check for A<->B deadlock (where both processes are here
  715. // waiting for other side to send confirm) and decide who stops waiting based on address.
  716. // To be compatible with older versions of mplib which will not do this,
  717. // loop with short wait time and release CS to allow other side to proceed
  718. StringBuffer epStr;
  719. unsigned startMs = msTick();
  720. unsigned loopCnt = CONNECT_READ_TIMEOUT / CONNECT_TIMEOUT_INTERVAL + 1;
  721. #ifdef _TRACE
  722. PROGLOG("MP: loopCnt start = %u", loopCnt);
  723. #endif
  724. while (loopCnt-- > 0)
  725. {
  726. {
  727. CriticalBlock block(attachsect);
  728. #ifdef _TRACE
  729. PROGLOG("MP: connect got attachsect, attachchk = %d, loopCnt = %u", atomic_read(&attachchk), loopCnt);
  730. #endif
  731. if (atomic_read(&attachchk) > 0)
  732. {
  733. if (remoteep.equals(attachep))
  734. {
  735. #ifdef _TRACE
  736. PROGLOG("MP: deadlock situation [] attachaddrval = %" I64F "u addrval = %" I64F "u", attachaddrval, addrval);
  737. #endif
  738. if (attachaddrval < addrval)
  739. break;
  740. }
  741. }
  742. }
  743. rd = 0;
  744. try
  745. {
  746. newsock->readtms(&reply,sizeof(reply),sizeof(reply),rd,CONNECT_TIMEOUT_INTERVAL);
  747. }
  748. catch (IException *e)
  749. {
  750. #ifdef _TRACE
  751. PROGLOG("MP: loop exception code = %d, loopCnt = %u", e->errorCode(), loopCnt);
  752. #endif
  753. if ( (e->errorCode() != JSOCKERR_timeout_expired) ||
  754. ((e->errorCode() == JSOCKERR_timeout_expired) && (loopCnt == 0)) )
  755. {
  756. if (tm.timedout(&remaining))
  757. {
  758. #ifdef _FULLTRACE
  759. EXCLOG(e,"MP: connect timed out 3");
  760. #endif
  761. e->Release();
  762. newsock->Release();
  763. return false;
  764. }
  765. #ifdef _TRACE
  766. EXCLOG(e, "MP: Failed to connect");
  767. #endif
  768. if ((retrycount--==0)||(tm.timeout==MP_ASYNC_SEND))
  769. { // don't bother retrying on async send
  770. e->Release();
  771. throw new CMPException(MPERR_connection_failed,remoteep);
  772. }
  773. // if other side closes, connect again
  774. if (e->errorCode() == JSOCKERR_graceful_close)
  775. {
  776. LOG(MCdebugInfo(100), unknownJob, "MP: Retrying (other side closed connection, probably due to clash)");
  777. e->Release();
  778. break;
  779. }
  780. e->Release();
  781. #ifdef _TRACE
  782. LOG(MCdebugInfo(100), unknownJob, "MP: Retrying connection to %s, %d attempts left",remoteep.getUrlStr(str).toCharArray(),retrycount+1);
  783. #endif
  784. }
  785. else
  786. {
  787. if (0 == epStr.length())
  788. {
  789. SocketEndpoint ep;
  790. newsock->getPeerEndpoint(ep);
  791. ep.getUrlStr(epStr);
  792. }
  793. WARNLOG("MP: connect to: %s, stalled for %d ms so far", epStr.str(), msTick()-startMs);
  794. e->Release();
  795. }
  796. }
  797. #ifdef _FULLTRACE
  798. PROGLOG("MP: rd = %d", rd);
  799. #endif
  800. if (rd != 0)
  801. break;
  802. }
  803. #ifdef _TRACE
  804. LOG(MCdebugInfo(100), unknownJob, "MP: connect after socket read rd=%u, reply=%u, sizeof(id)=%lu", rd, reply, sizeof(id));
  805. #endif
  806. if (reply!=0)
  807. {
  808. unsigned elapsedMs = msTick() - startMs;
  809. if (elapsedMs >= TRACESLOW_THRESHOLD)
  810. {
  811. if (0 == epStr.length())
  812. {
  813. SocketEndpoint ep;
  814. newsock->getPeerEndpoint(ep);
  815. ep.getUrlStr(epStr);
  816. }
  817. WARNLOG("MP: connect to: %s, took: %d ms", epStr.str(), elapsedMs);
  818. }
  819. assertex(reply==sizeof(id)); // how can this fail?
  820. if (attachSocket(newsock,remoteep,hostep,true,NULL,addrval))
  821. {
  822. newsock->Release();
  823. newsock = NULL;
  824. #ifdef _TRACE
  825. LOG(MCdebugInfo(100), unknownJob, "MP: connected to %s",str.str());
  826. #endif
  827. lastxfer = msTick();
  828. closed = false;
  829. break;
  830. }
  831. }
  832. }
  833. catch (IException *e)
  834. {
  835. if (tm.timedout(&remaining)) {
  836. #ifdef _FULLTRACE
  837. EXCLOG(e,"MP: connect timed out 2");
  838. #endif
  839. e->Release();
  840. return false;
  841. }
  842. #ifdef _TRACE
  843. EXCLOG(e, "MP: Failed to connect");
  844. #endif
  845. e->Release();
  846. if ((retrycount--==0)||(tm.timeout==MP_ASYNC_SEND)) { // don't bother retrying on async send
  847. IMP_Exception *e=new CMPException(MPERR_connection_failed,remoteep);
  848. throw e;
  849. }
  850. #ifdef _TRACE
  851. StringBuffer str;
  852. str.clear();
  853. LOG(MCdebugInfo(100), unknownJob, "MP: Retrying connection to %s, %d attempts left",remoteep.getUrlStr(str).str(),retrycount+1);
  854. #endif
  855. }
  856. ::Release(newsock);
  857. newsock = NULL;
  858. {
  859. CriticalUnblock unblock(connectsect); // to avoid connecting philosopher problem
  860. #ifdef _FULLTRACE
  861. PROGLOG("MP: before sleep");
  862. #endif
  863. // check often if channelsock was created from accept thread
  864. Sleep(50);
  865. unsigned totalt = CONNECT_TIMEOUT_MINSLEEP + getRandom() % (CONNECT_TIMEOUT_MAXSLEEP-CONNECT_TIMEOUT_MINSLEEP);
  866. unsigned startt = msTick();
  867. unsigned deltat = 0;
  868. while (deltat < totalt)
  869. {
  870. {
  871. CriticalBlock block(connectsect);
  872. if (channelsock)
  873. break;
  874. }
  875. deltat = msTick() - startt;
  876. Sleep(50);
  877. }
  878. #ifdef _FULLTRACE
  879. PROGLOG("MP: after sleep");
  880. #endif
  881. }
  882. }
  883. return true;
  884. }
  885. public:
  886. Semaphore pingsem;
  887. CMPChannel(CMPServer *_parent,SocketEndpoint &_remoteep);
  888. ~CMPChannel();
  889. void reset();
  890. bool attachSocket(ISocket *newsock,const SocketEndpoint &_remoteep,const SocketEndpoint &_localep,bool ismaster,size32_t *confirm, unsigned __int64 addrval=0);
  891. bool writepacket(const void *hdr,size32_t hdrsize,const void *hdr2,size32_t hdr2size,const void *body,size32_t bodysize,CTimeMon &tm)
  892. {
  893. Linked<ISocket> dest;
  894. {
  895. CriticalBlock block(connectsect);
  896. if (closed) {
  897. #ifdef _TRACELINKCLOSED
  898. LOG(MCdebugInfo(100), unknownJob, "WritePacket closed on entry");
  899. PrintStackReport();
  900. #endif
  901. if (!checkReconnect(tm))
  902. throw new CMPException(MPERR_link_closed,remoteep);
  903. }
  904. if (!channelsock) {
  905. if (!connect(tm)) {
  906. #ifdef _FULLTRACE
  907. LOG(MCdebugInfo(100), unknownJob, "WritePacket connect failed");
  908. #endif
  909. return false;
  910. }
  911. }
  912. dest.set(channelsock);
  913. }
  914. try {
  915. #ifdef _FULLTRACE
  916. unsigned t1 = msTick();
  917. #endif
  918. if ((tm.timeout!=MP_ASYNC_SEND)&&(tm.timeout!=MP_WAIT_FOREVER)) {
  919. // if (tm.timeout!=MP_ASYNC_SEND) {
  920. unsigned remaining;
  921. if (tm.timedout(&remaining))
  922. return false;
  923. if (channelsock->wait_write(remaining)==0) {
  924. return false;
  925. }
  926. if (tm.timedout())
  927. return false;
  928. }
  929. // exception checking TBD
  930. #ifdef _FULLTRACE
  931. StringBuffer ep1;
  932. StringBuffer ep2;
  933. LOG(MCdebugInfo(100), unknownJob, "WritePacket(target=%s,(%d,%d,%d))",remoteep.getUrlStr(ep1).str(),hdrsize,hdr2size,bodysize);
  934. unsigned t2 = msTick();
  935. #endif
  936. unsigned n = 0;
  937. const void *bufs[3];
  938. size32_t sizes[3];
  939. if (hdrsize) {
  940. bufs[n] = hdr;
  941. sizes[n++] = hdrsize;
  942. }
  943. if (hdr2size) {
  944. bufs[n] = hdr2;
  945. sizes[n++] = hdr2size;
  946. }
  947. if (bodysize) {
  948. bufs[n] = body;
  949. sizes[n++] = bodysize;
  950. }
  951. if (!dest) {
  952. LOG(MCdebugInfo(100), unknownJob, "MP Warning: WritePacket unexpected NULL socket");
  953. return false;
  954. }
  955. dest->write_multiple(n,bufs,sizes);
  956. lastxfer = msTick();
  957. #ifdef _FULLTRACE
  958. LOG(MCdebugInfo(100), unknownJob, "WritePacket(timewaiting=%d,timesending=%d)",t2-t1,lastxfer-t2);
  959. #endif
  960. }
  961. catch (IException *e) {
  962. FLLOG(MCoperatorWarning, unknownJob, e,"MP writepacket");
  963. closeSocket(false, true);
  964. throw;
  965. }
  966. return true;
  967. }
  968. bool writepacket(const void *hdr,size32_t hdrsize,const void *body,size32_t bodysize,CTimeMon &tm)
  969. {
  970. return writepacket(hdr,hdrsize,NULL,0,body,bodysize,tm);
  971. }
  972. bool writepacket(const void *hdr,size32_t hdrsize,CTimeMon &tm)
  973. {
  974. return writepacket(hdr,hdrsize,NULL,0,NULL,0,tm);
  975. }
  976. bool sendPing(CTimeMon &tm);
  977. bool sendPingReply(unsigned timeout,bool identifyself);
  978. bool verifyConnection(CTimeMon &tm,bool allowconnect)
  979. {
  980. {
  981. CriticalBlock block(connectsect);
  982. if (!channelsock&&allowconnect)
  983. return connect(tm);
  984. if (closed||!channelsock)
  985. return false;
  986. if ((msTick()-lastxfer)<VERIFY_DELAY)
  987. return true;
  988. }
  989. StringBuffer ep;
  990. remoteep.getUrlStr(ep);
  991. loop {
  992. CTimeMon pingtm(1000*60);
  993. if (sendPing(pingtm))
  994. break;
  995. {
  996. CriticalBlock block(connectsect);
  997. if (closed||!channelsock)
  998. return false;
  999. }
  1000. if (tm.timedout()) {
  1001. LOG(MCdebugInfo(100), unknownJob, "MP: verify, ping failed to %s",ep.str());
  1002. closeSocket();
  1003. return false;
  1004. }
  1005. LOG(MCdebugInfo(100), unknownJob, "MP: verify, ping failed to %s, retrying",ep.str());
  1006. unsigned remaining;
  1007. if (!pingtm.timedout(&remaining)&&remaining)
  1008. Sleep(remaining);
  1009. }
  1010. return true;
  1011. }
  1012. bool send(MemoryBuffer &mb, mptag_t tag, mptag_t replytag, CTimeMon &tm, bool reply);
  1013. void closeSocket(bool keepsocket=false, bool trace=false)
  1014. {
  1015. ISocket *s;
  1016. bool socketfailed = false;
  1017. {
  1018. CriticalBlock block(connectsect);
  1019. if (!channelsock)
  1020. return;
  1021. lastxfer = msTick();
  1022. closed = true;
  1023. if (parent)
  1024. parent->checkclosed = true;
  1025. s=channelsock;
  1026. channelsock = NULL;
  1027. {
  1028. CriticalBlock block(attachsect);
  1029. attachaddrval = 0;
  1030. attachep.set(NULL);
  1031. atomic_set(&attachchk, 0);
  1032. }
  1033. if (!keepsocket) {
  1034. try {
  1035. s->shutdown();
  1036. }
  1037. catch (IException *e) {
  1038. socketfailed = true; // ignore if the socket has been closed
  1039. WARNLOG("closeSocket() : Ignoring shutdown error");
  1040. e->Release();
  1041. }
  1042. }
  1043. parent->querySelectHandler().remove(s);
  1044. }
  1045. parent->notifyClosed(remoteep, trace);
  1046. if (socketfailed) {
  1047. try {
  1048. s->Release();
  1049. }
  1050. catch (IException *) {
  1051. // ignore
  1052. }
  1053. }
  1054. else if (keepsocket) {
  1055. // hopefully shouldn't get too many of these! (this is a kludge to prevent closing off wrong socket)
  1056. if (keptsockets.ordinality()>10)
  1057. keptsockets.remove(0);
  1058. keptsockets.append(*s);
  1059. }
  1060. else {
  1061. try {
  1062. s->close();
  1063. }
  1064. catch (IException *) {
  1065. socketfailed = true; // ignore if the socket has been closed
  1066. }
  1067. s->Release();
  1068. }
  1069. }
  1070. CMPServer &queryServer() { return *parent; }
  1071. void monitorCheck();
  1072. StringBuffer & queryEpStr(StringBuffer &s)
  1073. {
  1074. return remoteep.getUrlStr(s);
  1075. }
  1076. bool isClosed()
  1077. {
  1078. return closed;
  1079. }
  1080. bool isConnected()
  1081. {
  1082. return !closed&&(channelsock!=NULL);
  1083. }
  1084. };
  1085. // Message Handlers (not done as interfaces for speed reasons
  1086. class UserPacketHandler // default
  1087. {
  1088. CMPServer *server;
  1089. public:
  1090. UserPacketHandler(CMPServer *_server)
  1091. {
  1092. server = _server;
  1093. }
  1094. void handle(CMessageBuffer *msg) // takes ownership of message buffer
  1095. {
  1096. server->getReceiveQ().enqueue(msg);
  1097. }
  1098. bool send(CMPChannel *channel,PacketHeader &hdr,MemoryBuffer &mb, CTimeMon &tm)
  1099. {
  1100. #ifdef _FULLTRACE
  1101. StringBuffer ep1;
  1102. StringBuffer ep2;
  1103. LOG(MCdebugInfo(100), unknownJob, "MP: send(target=%s,sender=%s,tag=%d,replytag=%d,size=%d)",hdr.target.getUrlStr(ep1).str(),hdr.sender.getUrlStr(ep2).str(),hdr.tag,hdr.replytag,hdr.size);
  1104. #endif
  1105. return channel->writepacket(&hdr,sizeof(hdr),mb.toByteArray(),mb.length(),tm);
  1106. }
  1107. };
  1108. class PingPacketHandler // TAG_SYS_PING
  1109. {
  1110. public:
  1111. void handle(CMPChannel *channel,bool identifyself)
  1112. {
  1113. channel->sendPingReply(CONFIRM_TIMEOUT,identifyself);
  1114. }
  1115. bool send(CMPChannel *channel,PacketHeader &hdr,CTimeMon &tm)
  1116. {
  1117. return channel->writepacket(&hdr,sizeof(hdr),tm);
  1118. }
  1119. };
  1120. class PingReplyPacketHandler // TAG_SYS_PING_REPLY
  1121. {
  1122. public:
  1123. void handle(CMPChannel *channel)
  1124. {
  1125. channel->pingsem.signal();
  1126. }
  1127. bool send(CMPChannel *channel,PacketHeader &hdr,MemoryBuffer &mb,CTimeMon &tm)
  1128. {
  1129. return channel->writepacket(&hdr,sizeof(hdr),mb.toByteArray(),mb.length(),tm);
  1130. }
  1131. };
  1132. class CMultiPacketReceiver: public CInterface
  1133. { // assume each sender only sends one multi-message per channel
  1134. public:
  1135. SocketEndpoint sender;
  1136. MultiPacketHeader info;
  1137. CMessageBuffer *msg;
  1138. byte * ptr;
  1139. };
  1140. class MultiPacketHandler // TAG_SYS_MULTI
  1141. {
  1142. CIArrayOf<CMultiPacketReceiver> inprogress; // should be ok as not many in progress hopefully (TBD orphans)
  1143. CriticalSection sect;
  1144. unsigned lastErrMs;
  1145. void logError(unsigned code, MultiPacketHeader &mhdr, CMessageBuffer &msg, MultiPacketHeader *otherMhdr)
  1146. {
  1147. unsigned ms = msTick();
  1148. if ((ms-lastErrMs) > 1000) // avoid logging too much
  1149. {
  1150. StringBuffer errorMsg("sender=");
  1151. msg.getSender().getUrlStr(errorMsg).newline();
  1152. errorMsg.append("This header: ");
  1153. mhdr.getDetails(errorMsg).newline();
  1154. if (otherMhdr)
  1155. {
  1156. errorMsg.append("Other header: ");
  1157. otherMhdr->getDetails(errorMsg).newline();
  1158. }
  1159. msg.getDetails(errorMsg);
  1160. LOG(MCerror, unknownJob, "MultiPacketHandler: protocol error (%d) %s", code, errorMsg.str());
  1161. }
  1162. lastErrMs = ms;
  1163. }
  1164. public:
  1165. MultiPacketHandler() : lastErrMs(0)
  1166. {
  1167. }
  1168. CMessageBuffer *handle(CMessageBuffer * msg)
  1169. {
  1170. if (!msg)
  1171. return NULL;
  1172. CriticalBlock block(sect);
  1173. MultiPacketHeader mhdr;
  1174. msg->read(sizeof(mhdr),&mhdr);
  1175. CMultiPacketReceiver *recv=NULL;
  1176. ForEachItemIn(i,inprogress) {
  1177. CMultiPacketReceiver &mpr = inprogress.item(i);
  1178. if ((mpr.info.tag==mhdr.tag)&&mpr.sender.equals(msg->getSender())) {
  1179. recv = &mpr;
  1180. break;
  1181. }
  1182. }
  1183. if (mhdr.idx==0) {
  1184. if ((mhdr.ofs!=0)||(recv!=NULL)) {
  1185. logError(1, mhdr, *msg, recv?&recv->info:NULL);
  1186. delete msg;
  1187. return NULL;
  1188. }
  1189. recv = new CMultiPacketReceiver;
  1190. recv->msg = new CMessageBuffer();
  1191. recv->msg->init(msg->getSender(),mhdr.tag,msg->getReplyTag());
  1192. recv->ptr = (byte *)recv->msg->reserveTruncate(mhdr.total);
  1193. recv->sender = msg->getSender();
  1194. recv->info = mhdr;
  1195. inprogress.append(*recv);
  1196. }
  1197. else {
  1198. if ((recv==NULL)||(mhdr.ofs==0)||
  1199. (recv->info.ofs+recv->info.size!=mhdr.ofs)||
  1200. (recv->info.idx+1!=mhdr.idx)||
  1201. (recv->info.total!=mhdr.total)||
  1202. (mhdr.ofs+mhdr.size>mhdr.total)) {
  1203. logError(2, mhdr, *msg, recv?&recv->info:NULL);
  1204. delete msg;
  1205. return NULL;
  1206. }
  1207. }
  1208. msg->read(mhdr.size,recv->ptr+mhdr.ofs);
  1209. delete msg;
  1210. msg = NULL;
  1211. recv->info = mhdr;
  1212. if (mhdr.idx+1==mhdr.numparts) {
  1213. if (mhdr.ofs+mhdr.size!=mhdr.total) {
  1214. logError(3, mhdr, *msg, NULL);
  1215. return NULL;
  1216. }
  1217. msg = recv->msg;
  1218. inprogress.remove(i);
  1219. }
  1220. return msg;
  1221. }
  1222. bool send(CMPChannel *channel,PacketHeader &hdr,MemoryBuffer &mb, CTimeMon &tm, Mutex &sendmutex)
  1223. {
  1224. // must not adjust mb
  1225. #ifdef _FULLTRACE
  1226. StringBuffer ep1;
  1227. StringBuffer ep2;
  1228. LOG(MCdebugInfo(100), unknownJob, "MP: multi-send(target=%s,sender=%s,tag=%d,replytag=%d,size=%d)",hdr.target.getUrlStr(ep1).str(),hdr.sender.getUrlStr(ep2).str(),hdr.tag,hdr.replytag,hdr.size);
  1229. #endif
  1230. PacketHeader outhdr;
  1231. outhdr = hdr;
  1232. outhdr.tag = TAG_SYS_MULTI;
  1233. MultiPacketHeader mhdr;
  1234. mhdr.total = hdr.size-sizeof(hdr);
  1235. mhdr.numparts = (mhdr.total+MAXDATAPERPACKET-1)/MAXDATAPERPACKET;
  1236. mhdr.size = mhdr.total/mhdr.numparts;
  1237. mhdr.tag = hdr.tag;
  1238. mhdr.ofs = 0;
  1239. mhdr.idx = 0;
  1240. const byte *p = (const byte *)mb.toByteArray();
  1241. unsigned i=0;
  1242. loop {
  1243. if (i+1==mhdr.numparts)
  1244. mhdr.size = mhdr.total-mhdr.ofs;
  1245. #ifdef _FULLTRACE
  1246. LOG(MCdebugInfo(100), unknownJob, "MP: multi-send block=%d, num blocks=%d, ofs=%d, size=%d",i,mhdr.numparts,mhdr.ofs,mhdr.size);
  1247. #endif
  1248. outhdr.initseq();
  1249. outhdr.size = sizeof(outhdr)+sizeof(mhdr)+mhdr.size;
  1250. if (!channel->writepacket(&outhdr,sizeof(outhdr),&mhdr,sizeof(mhdr),p,mhdr.size,tm)) {
  1251. #ifdef _FULLTRACE
  1252. LOG(MCdebugInfo(100), unknownJob, "MP: multi-send failed");
  1253. #endif
  1254. return false;
  1255. }
  1256. i++;
  1257. if (i==mhdr.numparts)
  1258. break;
  1259. sendmutex.unlock(); // allow other messages to interleave
  1260. sendmutex.lock();
  1261. mhdr.idx++;
  1262. mhdr.ofs += mhdr.size;
  1263. p += mhdr.size;
  1264. }
  1265. return true;
  1266. }
  1267. };
  1268. class BroadcastPacketHandler // TAG_SYS_BCAST
  1269. {
  1270. public:
  1271. CMessageBuffer *handle(CMessageBuffer * msg)
  1272. {
  1273. delete msg;
  1274. return NULL;
  1275. }
  1276. };
  1277. class ForwardPacketHandler // TAG_SYS_FORWARD
  1278. {
  1279. public:
  1280. CMessageBuffer *handle(CMessageBuffer * msg)
  1281. {
  1282. delete msg;
  1283. return NULL;
  1284. }
  1285. };
  1286. // --------------------------------------------------------
  1287. class CMPPacketReader: public CInterface, public ISocketSelectNotify
  1288. {
  1289. CMessageBuffer *activemsg;
  1290. byte * activeptr;
  1291. size32_t remaining;
  1292. byte *dataptr;
  1293. CMPChannel *parent;
  1294. CriticalSection sect;
  1295. public:
  1296. IMPLEMENT_IINTERFACE;
  1297. CMPPacketReader(CMPChannel *_parent)
  1298. {
  1299. init(_parent);
  1300. }
  1301. void init(CMPChannel *_parent)
  1302. {
  1303. parent = _parent;
  1304. activemsg = NULL;
  1305. }
  1306. void shutdown()
  1307. {
  1308. CriticalBlock block(sect);
  1309. parent = NULL;
  1310. }
  1311. bool notifySelected(ISocket *sock,unsigned selected)
  1312. {
  1313. if (!parent)
  1314. return false;
  1315. try {
  1316. // try and mop up all data on socket
  1317. size32_t sizeavail = sock->avail_read();
  1318. if (sizeavail==0) {
  1319. // graceful close
  1320. Linked<CMPChannel> pc;
  1321. {
  1322. CriticalBlock block(sect);
  1323. if (parent) {
  1324. pc.set(parent); // don't want channel to disappear during call
  1325. parent = NULL;
  1326. }
  1327. }
  1328. if (pc)
  1329. pc->closeSocket(false, true);
  1330. return false;
  1331. }
  1332. do {
  1333. parent->lastxfer = msTick();
  1334. #ifdef _FULLTRACE
  1335. parent->numiter++;
  1336. #endif
  1337. if (!activemsg) { // no message in progress
  1338. PacketHeader hdr; // header for active message
  1339. #ifdef _FULLTRACE
  1340. parent->numiter = 1;
  1341. parent->startxfer = msTick();
  1342. #endif
  1343. // assumes packet header will arrive in one go
  1344. if (sizeavail<sizeof(hdr)) {
  1345. #ifdef _FULLTRACE
  1346. LOG(MCdebugInfo(100), unknownJob, "Selected stalled on header %d %d",sizeavail,sizeavail-sizeof(hdr));
  1347. #endif
  1348. size32_t szread;
  1349. sock->read(&hdr,sizeof(hdr),sizeof(hdr),szread,60); // I don't *really* want to block here but not much else can do
  1350. }
  1351. else
  1352. sock->read(&hdr,sizeof(hdr));
  1353. if (hdr.version/0x100 != MP_PROTOCOL_VERSION/0x100) {
  1354. // TBD IPV6 here
  1355. SocketEndpoint ep;
  1356. hdr.sender.get(ep);
  1357. IMP_Exception *e=new CMPException(MPERR_protocol_version_mismatch,ep);
  1358. throw e;
  1359. }
  1360. if (sizeavail<=sizeof(hdr))
  1361. sizeavail = sock->avail_read();
  1362. else
  1363. sizeavail -= sizeof(hdr);
  1364. #ifdef _FULLTRACE
  1365. StringBuffer ep1;
  1366. StringBuffer ep2;
  1367. LOG(MCdebugInfo(100), unknownJob, "MP: ReadPacket(sender=%s,target=%s,tag=%d,replytag=%d,size=%d)",hdr.sender.getUrlStr(ep1).str(),hdr.target.getUrlStr(ep2).str(),hdr.tag,hdr.replytag,hdr.size);
  1368. #endif
  1369. remaining = hdr.size-sizeof(hdr);
  1370. activemsg = new CMessageBuffer(remaining); // will get from low level IO at some stage
  1371. activeptr = (byte *)activemsg->reserveTruncate(remaining);
  1372. hdr.setMessageFields(*activemsg);
  1373. }
  1374. size32_t toread = sizeavail;
  1375. if (toread>remaining)
  1376. toread = remaining;
  1377. if (toread) {
  1378. sock->read(activeptr,toread);
  1379. remaining -= toread;
  1380. sizeavail -= toread;
  1381. activeptr += toread;
  1382. }
  1383. if (remaining==0) { // we have the packet so process
  1384. #ifdef _FULLTRACE
  1385. LOG(MCdebugInfo(100), unknownJob, "MP: ReadPacket(timetaken = %d,select iterations=%d)",msTick()-parent->startxfer,parent->numiter);
  1386. #endif
  1387. do {
  1388. switch (activemsg->getTag()) {
  1389. case TAG_SYS_MULTI:
  1390. activemsg = parent->queryServer().multipackethandler->handle(activemsg); // activemsg in/out
  1391. break;
  1392. case TAG_SYS_PING:
  1393. parent->queryServer().pingpackethandler->handle(parent,false); //,activemsg);
  1394. delete activemsg;
  1395. activemsg = NULL;
  1396. break;
  1397. case TAG_SYS_PING_REPLY:
  1398. parent->queryServer().pingreplypackethandler->handle(parent);
  1399. delete activemsg;
  1400. activemsg = NULL;
  1401. break;
  1402. case TAG_SYS_BCAST:
  1403. activemsg = parent->queryServer().broadcastpackethandler->handle(activemsg);
  1404. break;
  1405. case TAG_SYS_FORWARD:
  1406. activemsg = parent->queryServer().forwardpackethandler->handle(activemsg);
  1407. break;
  1408. default:
  1409. parent->queryServer().userpackethandler->handle(activemsg); // takes ownership
  1410. activemsg = NULL;
  1411. }
  1412. } while (activemsg);
  1413. }
  1414. if (!sizeavail)
  1415. sizeavail = sock->avail_read();
  1416. } while (sizeavail);
  1417. return false; // ok
  1418. }
  1419. catch (IException *e) {
  1420. if (e->errorCode()!=JSOCKERR_graceful_close)
  1421. FLLOG(MCoperatorWarning, unknownJob, e,"MP(Packet Reader)");
  1422. e->Release();
  1423. }
  1424. // error here, so close socket (ignore error as may be closed already)
  1425. try {
  1426. if(parent)
  1427. parent->closeSocket(false, true);
  1428. }
  1429. catch (IException *e) {
  1430. e->Release();
  1431. }
  1432. parent = NULL;
  1433. return false;
  1434. }
  1435. };
  1436. CMPChannel::CMPChannel(CMPServer *_parent,SocketEndpoint &_remoteep)
  1437. {
  1438. channelsock = NULL;
  1439. parent = _parent;
  1440. remoteep = _remoteep;
  1441. localep.set(parent->getPort());
  1442. multitag = TAG_NULL;
  1443. reader = new CMPPacketReader(this);
  1444. closed = false;
  1445. master = false;
  1446. sendwaiting = 0;
  1447. attachaddrval = 0;
  1448. attachep.set(NULL);
  1449. atomic_set(&attachchk, 0);
  1450. }
  1451. void CMPChannel::reset()
  1452. {
  1453. reader->shutdown(); // clear as early as possible
  1454. closeSocket(false, true);
  1455. reader->Release();
  1456. channelsock = NULL;
  1457. multitag = TAG_NULL;
  1458. reader = new CMPPacketReader(this);
  1459. closed = false;
  1460. master = false;
  1461. sendwaiting = 0;
  1462. attachaddrval = 0;
  1463. attachep.set(NULL);
  1464. atomic_set(&attachchk, 0);
  1465. }
  1466. CMPChannel::~CMPChannel()
  1467. {
  1468. reader->shutdown(); // clear as early as possible
  1469. closeSocket();
  1470. reader->Release();
  1471. }
  1472. bool CMPChannel::attachSocket(ISocket *newsock,const SocketEndpoint &_remoteep,const SocketEndpoint &_localep,bool ismaster,size32_t *confirm, unsigned __int64 addrval) // takes ownership if succeeds
  1473. {
  1474. struct attachdTor
  1475. {
  1476. atomic_t &attchk;
  1477. attachdTor(atomic_t &_attchk) : attchk(_attchk) { }
  1478. ~attachdTor() { atomic_dec(&attchk); }
  1479. } attachChk (attachchk);
  1480. #ifdef _FULLTRACE
  1481. PROGLOG("MP: attachSocket on entry, ismaster = %d, confirm = %p, channelsock = %p, addrval = %" I64F "u", ismaster, confirm, channelsock, addrval);
  1482. #endif
  1483. {
  1484. CriticalBlock block(attachsect);
  1485. attachaddrval = addrval;
  1486. attachep = _remoteep;
  1487. atomic_inc(&attachchk);
  1488. }
  1489. CriticalBlock block(connectsect);
  1490. #ifdef _FULLTRACE
  1491. PROGLOG("MP: attachSocket got connectsect, channelsock = %p", channelsock);
  1492. #endif
  1493. // resolution to stop clash i.e. A sends to B at exactly same time B sends to A
  1494. if (channelsock) {
  1495. if (_remoteep.port==0)
  1496. return false;
  1497. StringBuffer ep1;
  1498. StringBuffer ep2;
  1499. _localep.getUrlStr(ep1);
  1500. _remoteep.getUrlStr(ep2);
  1501. LOG(MCdebugInfo(100), unknownJob, "MP: Possible clash between %s->%s %d(%d)",ep1.str(),ep2.str(),(int)ismaster,(int)master);
  1502. try {
  1503. if (ismaster!=master) {
  1504. if (ismaster) {
  1505. LOG(MCdebugInfo(100), unknownJob, "MP: resolving socket attach clash (master)");
  1506. return false;
  1507. }
  1508. else {
  1509. Sleep(50); // give the other side some time to close
  1510. CTimeMon tm(10000);
  1511. if (verifyConnection(tm,false)) {
  1512. LOG(MCdebugInfo(100), unknownJob, "MP: resolving socket attach clash (verified)");
  1513. return false;
  1514. }
  1515. }
  1516. }
  1517. }
  1518. catch (IException *e) {
  1519. FLLOG(MCoperatorWarning, unknownJob, e,"MP attachsocket(1)");
  1520. e->Release();
  1521. }
  1522. try {
  1523. LOG(MCdebugInfo(100), unknownJob, "Message Passing - removing stale socket to %s",ep2.str());
  1524. CriticalUnblock unblock(connectsect);
  1525. closeSocket(true, true);
  1526. #ifdef REFUSE_STALE_CONNECTION
  1527. if (!ismaster)
  1528. return false;
  1529. #endif
  1530. Sleep(100); // pause to allow close socket triggers to run
  1531. }
  1532. catch (IException *e) {
  1533. FLLOG(MCoperatorWarning, unknownJob, e,"MP attachsocket(2)");
  1534. e->Release();
  1535. }
  1536. }
  1537. if (confirm)
  1538. newsock->write(confirm,sizeof(*confirm)); // confirm while still in connectsect
  1539. closed = false;
  1540. reader->init(this);
  1541. channelsock = LINK(newsock);
  1542. #ifdef _FULLTRACE
  1543. PROGLOG("MP: attachSocket before select add");
  1544. #endif
  1545. parent->querySelectHandler().add(channelsock,SELECTMODE_READ,reader);
  1546. #ifdef _FULLTRACE
  1547. PROGLOG("MP: attachSocket after select add");
  1548. #endif
  1549. localep = _localep;
  1550. master = ismaster;
  1551. return true;
  1552. }
  1553. bool CMPChannel::send(MemoryBuffer &mb, mptag_t tag, mptag_t replytag, CTimeMon &tm, bool reply)
  1554. {
  1555. // note must not adjust mb
  1556. assertex(tag!=TAG_NULL);
  1557. assertex(tm.timeout);
  1558. const byte *msg = (const byte *)mb.toByteArray();
  1559. size32_t msgsize = mb.length();
  1560. PacketHeader hdr(msgsize+sizeof(PacketHeader),localep,remoteep,tag,replytag);
  1561. if (closed||(reply&&!isConnected())) { // flag error if has been disconnected
  1562. #ifdef _TRACELINKCLOSED
  1563. LOG(MCdebugInfo(100), unknownJob, "CMPChannel::send closed on entry %d",(int)closed);
  1564. PrintStackReport();
  1565. #endif
  1566. if (!checkReconnect(tm))
  1567. throw new CMPException(MPERR_link_closed,remoteep);
  1568. }
  1569. bool ismulti = (msgsize>MAXDATAPERPACKET);
  1570. // pre-condition - ensure no clashes
  1571. loop {
  1572. sendmutex.lock();
  1573. if (ismulti) {
  1574. if (multitag==TAG_NULL) // don't want to interleave with other multi send
  1575. break;
  1576. }
  1577. else if (multitag!=tag) // don't want to interleave with another of same tag
  1578. break;
  1579. sendwaiting++;
  1580. sendmutex.unlock();
  1581. sendwaitingsig.wait();
  1582. }
  1583. struct Cpostcondition // can we start using eiffel
  1584. {
  1585. Mutex &sendmutex;
  1586. unsigned &sendwaiting;
  1587. Semaphore &sendwaitingsig;
  1588. mptag_t *multitag;
  1589. Cpostcondition(Mutex &_sendmutex,unsigned &_sendwaiting,Semaphore &_sendwaitingsig,mptag_t *_multitag)
  1590. : sendmutex(_sendmutex),sendwaiting(_sendwaiting),sendwaitingsig(_sendwaitingsig)
  1591. {
  1592. multitag = _multitag;
  1593. }
  1594. ~Cpostcondition()
  1595. {
  1596. if (multitag)
  1597. *multitag = TAG_NULL;
  1598. if (sendwaiting) {
  1599. sendwaitingsig.signal(sendwaiting);
  1600. sendwaiting = 0;
  1601. }
  1602. sendmutex.unlock();
  1603. }
  1604. } postcond(sendmutex,sendwaiting,sendwaitingsig,ismulti?&multitag:NULL);
  1605. if (ismulti)
  1606. return parent->multipackethandler->send(this,hdr,mb,tm,sendmutex);
  1607. return parent->userpackethandler->send(this,hdr,mb,tm);
  1608. }
  1609. bool CMPChannel::sendPing(CTimeMon &tm)
  1610. {
  1611. unsigned remaining;
  1612. tm.timedout(&remaining);
  1613. if (!sendmutex.lockWait(remaining))
  1614. return false;
  1615. SocketEndpoint myep(parent->getPort());
  1616. PacketHeader hdr(sizeof(PacketHeader),myep,remoteep,TAG_SYS_PING,TAG_SYS_PING_REPLY);
  1617. bool ret = false;
  1618. try {
  1619. ret = parent->pingpackethandler->send(this,hdr,tm)&&!tm.timedout(&remaining);
  1620. }
  1621. catch (IException *e) {
  1622. FLLOG(MCoperatorWarning, unknownJob, e,"MP ping(1)");
  1623. e->Release();
  1624. }
  1625. sendmutex.unlock();
  1626. if (ret)
  1627. ret = pingsem.wait(remaining);
  1628. return ret;
  1629. }
  1630. bool CMPChannel::sendPingReply(unsigned timeout,bool identifyself)
  1631. {
  1632. CTimeMon mon(timeout);
  1633. unsigned remaining;
  1634. mon.timedout(&remaining);
  1635. if (!sendmutex.lockWait(remaining))
  1636. return false;
  1637. SocketEndpoint myep(parent->getPort());
  1638. MemoryBuffer mb;
  1639. if (identifyself) {
  1640. #ifdef _WIN32
  1641. mb.append(GetCommandLine());
  1642. #endif
  1643. }
  1644. PacketHeader hdr(mb.length()+sizeof(PacketHeader),myep,remoteep,TAG_SYS_PING_REPLY,TAG_NULL);
  1645. bool ret;
  1646. try {
  1647. ret = parent->pingreplypackethandler->send(this,hdr,mb,mon);
  1648. }
  1649. catch (IException *e) {
  1650. FLLOG(MCoperatorWarning, unknownJob, e,"MP ping reply(1)");
  1651. e->Release();
  1652. ret = false;
  1653. }
  1654. sendmutex.unlock();
  1655. return ret;
  1656. }
  1657. // --------------------------------------------------------
  1658. CMPConnectThread::CMPConnectThread(CMPServer *_parent, unsigned port)
  1659. : Thread("MP Connection Thread")
  1660. {
  1661. parent = _parent;
  1662. mpSoMaxConn = 0;
  1663. mpTraceLevel = 0;
  1664. Owned<IPropertyTree> env = getHPCCEnvironment();
  1665. if (env)
  1666. {
  1667. mpSoMaxConn = env->getPropInt("EnvSettings/mpSoMaxConn", 0);
  1668. if (!mpSoMaxConn)
  1669. mpSoMaxConn = env->getPropInt("EnvSettings/ports/mpSoMaxConn", 0);
  1670. mpTraceLevel = env->getPropInt("EnvSettings/mpTraceLevel", 0);
  1671. }
  1672. if (mpSoMaxConn)
  1673. {
  1674. int kernSoMaxConn = 0;
  1675. bool soMaxCheck = check_somaxconn(&kernSoMaxConn);
  1676. if (soMaxCheck && (mpSoMaxConn > kernSoMaxConn))
  1677. WARNLOG("MP: kernel listen queue backlog setting (somaxconn=%d) is lower than environment mpSoMaxConn (%d) setting and should be increased", kernSoMaxConn, mpSoMaxConn);
  1678. }
  1679. if (!mpSoMaxConn)
  1680. mpSoMaxConn = DEFAULT_LISTEN_QUEUE_SIZE;
  1681. if (!port)
  1682. {
  1683. // need to connect early to resolve clash
  1684. unsigned minPort, maxPort;
  1685. if (env)
  1686. {
  1687. minPort = env->getPropInt("EnvSettings/mpStart", 0);
  1688. if (!minPort)
  1689. minPort = env->getPropInt("EnvSettings/ports/mpStart", MP_START_PORT);
  1690. maxPort = env->getPropInt("EnvSettings/mpEnd", 0);
  1691. if (!maxPort)
  1692. maxPort = env->getPropInt("EnvSettings/ports/mpEnd", MP_END_PORT);
  1693. }
  1694. else
  1695. {
  1696. minPort = MP_START_PORT;
  1697. maxPort = MP_END_PORT;
  1698. }
  1699. assertex(maxPort >= minPort);
  1700. Owned<IJSOCK_Exception> lastErr;
  1701. unsigned numPorts = maxPort - minPort + 1;
  1702. for (unsigned retries = 0; retries < numPorts * 3; retries++)
  1703. {
  1704. port = minPort + getRandom() % numPorts;
  1705. try
  1706. {
  1707. listensock = ISocket::create(port, mpSoMaxConn);
  1708. break;
  1709. }
  1710. catch (IJSOCK_Exception *e)
  1711. {
  1712. if (e->errorCode()!=JSOCKERR_port_in_use)
  1713. throw;
  1714. lastErr.setown(e);
  1715. }
  1716. }
  1717. if (!listensock)
  1718. throw lastErr.getClear();
  1719. }
  1720. else
  1721. listensock = NULL; // delay create till running
  1722. parent->setPort(port);
  1723. #ifdef _TRACE
  1724. LOG(MCdebugInfo(100), unknownJob, "MP Connect Thread Init Port = %d", port);
  1725. #endif
  1726. running = false;
  1727. }
  1728. void CMPConnectThread::checkSelfDestruct(void *p,size32_t sz)
  1729. {
  1730. byte *b = (byte *)p;
  1731. while (sz--)
  1732. if (*(b++)!=0xff)
  1733. return;
  1734. // Panic!
  1735. PROGLOG("MP Self destruct invoked");
  1736. try {
  1737. if (listensock) {
  1738. listensock->close();
  1739. listensock->Release();
  1740. listensock=NULL;
  1741. }
  1742. }
  1743. catch (...)
  1744. {
  1745. PROGLOG("MP socket close failure");
  1746. }
  1747. // Kill registered child processes
  1748. PROGLOG("MP self destruct exit");
  1749. queryLogMsgManager()->flushQueue(10*1000);
  1750. #ifdef _WIN32
  1751. ForEachItemIn(i,childprocesslist)
  1752. TerminateProcess((HANDLE)childprocesslist.item(i), 1);
  1753. TerminateProcess(GetCurrentProcess(), 1);
  1754. #else
  1755. ForEachItemIn(i,childprocesslist)
  1756. ::kill((HANDLE)childprocesslist.item(i), SIGTERM);
  1757. ::kill(getpid(), SIGTERM);
  1758. #endif
  1759. _exit(1);
  1760. }
  1761. void CMPConnectThread::start(unsigned short port)
  1762. {
  1763. if (!listensock)
  1764. listensock = ISocket::create(port, mpSoMaxConn);
  1765. running = true;
  1766. Thread::start();
  1767. }
  1768. int CMPConnectThread::run()
  1769. {
  1770. #ifdef _TRACE
  1771. LOG(MCdebugInfo(100), unknownJob, "MP: Connect Thread Starting - accept loop");
  1772. #endif
  1773. while (running) {
  1774. ISocket *sock=NULL;
  1775. try {
  1776. sock=listensock->accept(true);
  1777. #ifdef _FULLTRACE
  1778. StringBuffer s;
  1779. SocketEndpoint ep1;
  1780. sock->getPeerEndpoint(ep1);
  1781. PROGLOG("MP: Connect Thread: socket accepted from %s",ep1.getUrlStr(s).str());
  1782. #endif
  1783. }
  1784. catch (IException *e)
  1785. {
  1786. LOG(MCdebugInfo, unknownJob, e,"MP accept failed");
  1787. throw; // error handling TBD
  1788. }
  1789. if (sock) {
  1790. try {
  1791. sock->set_keep_alive(true);
  1792. size32_t rd;
  1793. SocketEndpoint _remoteep;
  1794. SocketEndpoint hostep;
  1795. SocketEndpointV4 id[2];
  1796. traceSlowReadTms("MP: initial accept packet from", sock, &id[0], sizeof(id), sizeof(id), rd, CONFIRM_TIMEOUT, CONFIRM_TIMEOUT_INTERVAL);
  1797. if (0 == rd)
  1798. {
  1799. if (mpTraceLevel > 1)
  1800. {
  1801. // cannot get peer addresss as socket state is now ss_shutdown (unless we want to allow this in getPeerEndpoint())
  1802. StringBuffer errMsg("MP Connect Thread: connect with no msg received, assumed port monitor check");
  1803. PROGLOG("%s", errMsg.str());
  1804. }
  1805. sock->close();
  1806. sock->Release();
  1807. continue;
  1808. }
  1809. else if (rd != sizeof(id))
  1810. {
  1811. // not sure how to get here as this is not one of the possible outcomes of above: rd == 0 or rd == sizeof(id) or an exception
  1812. SocketEndpoint ep;
  1813. sock->getPeerEndpoint(ep);
  1814. StringBuffer errMsg("MP Connect Thread: invalid number of connection bytes serialized from ");
  1815. ep.getUrlStr(errMsg);
  1816. FLLOG(MCoperatorWarning, unknownJob, "%s", errMsg.str());
  1817. sock->close();
  1818. sock->Release();
  1819. continue;
  1820. }
  1821. id[0].get(_remoteep);
  1822. id[1].get(hostep);
  1823. unsigned __int64 addrval = DIGIT1*id[0].ip[0] + DIGIT2*id[0].ip[1] + DIGIT3*id[0].ip[2] + DIGIT4*id[0].ip[3] + id[0].port;
  1824. #ifdef _TRACE
  1825. PROGLOG("MP: Connect Thread: addrval = %" I64F "u", addrval);
  1826. #endif
  1827. if (_remoteep.isNull() || hostep.isNull())
  1828. {
  1829. SocketEndpoint ep;
  1830. sock->getPeerEndpoint(ep);
  1831. StringBuffer errMsg;
  1832. SocketEndpointV4 zeroTest[2];
  1833. memset(zeroTest, 0x0, sizeof(zeroTest));
  1834. if (memcmp(id, zeroTest, sizeof(id)))
  1835. {
  1836. // JCSMORE, I think _remoteep really must/should match a IP of this local host
  1837. errMsg.append("MP Connect Thread: invalid remote and/or host ep serialized from ");
  1838. ep.getUrlStr(errMsg);
  1839. FLLOG(MCoperatorWarning, unknownJob, "%s", errMsg.str());
  1840. }
  1841. else if (mpTraceLevel > 1)
  1842. {
  1843. // all zeros msg received
  1844. errMsg.append("MP Connect Thread: connect with empty msg received, assumed port monitor check from ");
  1845. ep.getUrlStr(errMsg);
  1846. PROGLOG("%s", errMsg.str());
  1847. }
  1848. sock->close();
  1849. sock->Release();
  1850. continue;
  1851. }
  1852. #ifdef _FULLTRACE
  1853. StringBuffer tmp1;
  1854. _remoteep.getUrlStr(tmp1);
  1855. tmp1.append(' ');
  1856. hostep.getUrlStr(tmp1);
  1857. PROGLOG("MP: Connect Thread: after read %s",tmp1.str());
  1858. #endif
  1859. checkSelfDestruct(&id[0],sizeof(id));
  1860. Linked<CMPChannel> channel = parent->lookup(_remoteep);
  1861. if (!channel->attachSocket(sock,_remoteep,hostep,false,&rd,addrval)) {
  1862. #ifdef _FULLTRACE
  1863. PROGLOG("MP Connect Thread: lookup failed");
  1864. #endif
  1865. }
  1866. else {
  1867. #ifdef _TRACE
  1868. StringBuffer str1;
  1869. StringBuffer str2;
  1870. LOG(MCdebugInfo(100), unknownJob, "MP Connect Thread: connected to %s",_remoteep.getUrlStr(str1).str());
  1871. #endif
  1872. }
  1873. #ifdef _FULLTRACE
  1874. PROGLOG("MP: Connect Thread: after write");
  1875. #endif
  1876. }
  1877. catch (IException *e)
  1878. {
  1879. FLLOG(MCoperatorWarning, unknownJob, e,"MP Connect Thread: Failed to make connection(1)");
  1880. sock->close();
  1881. e->Release();
  1882. }
  1883. try {
  1884. sock->Release();
  1885. }
  1886. catch (IException *e)
  1887. {
  1888. FLLOG(MCoperatorWarning, unknownJob, e,"MP sock release failed");
  1889. e->Release();
  1890. }
  1891. }
  1892. else {
  1893. if (running)
  1894. LOG(MCdebugInfo(100), unknownJob, "MP Connect Thread accept returned NULL");
  1895. }
  1896. }
  1897. #ifdef _TRACE
  1898. LOG(MCdebugInfo(100), unknownJob, "MP Connect Thread Stopping");
  1899. #endif
  1900. return 0;
  1901. }
  1902. // --------------------------------------------------------
  1903. class CMPChannelIterator
  1904. {
  1905. CMPServer &parent;
  1906. CMPChannel *cur;
  1907. public:
  1908. CMPChannelIterator(CMPServer &_parent)
  1909. : parent(_parent)
  1910. {
  1911. cur = NULL;
  1912. }
  1913. bool first()
  1914. {
  1915. cur = NULL;
  1916. return parent.nextChannel(cur);
  1917. }
  1918. bool next()
  1919. {
  1920. return cur&&parent.nextChannel(cur);
  1921. }
  1922. bool isValid()
  1923. {
  1924. return cur!=NULL;
  1925. }
  1926. CMPChannel &query()
  1927. {
  1928. return *cur;
  1929. }
  1930. };
  1931. //-----------------------------------------------------------------------------------
  1932. CMPChannel *CMPServer::lookup(const SocketEndpoint &endpoint)
  1933. {
  1934. // there is an assumption here that no removes will be done within this loop
  1935. CriticalBlock block(sect);
  1936. SocketEndpoint ep = endpoint;
  1937. CMPChannel *e=find(ep);
  1938. // Check for freed channels
  1939. if (e&&e->isClosed()&&(msTick()-e->lastxfer>30*1000))
  1940. e->reset();
  1941. if (checkclosed) {
  1942. checkclosed = false;
  1943. CMPChannel *c = NULL;
  1944. loop {
  1945. c = next(c);
  1946. if (!c) {
  1947. break;
  1948. }
  1949. if (c->isClosed()&&(msTick()-c->lastxfer>30*1000)) {
  1950. removeExact(c);
  1951. c = NULL;
  1952. }
  1953. }
  1954. e=find(ep);
  1955. }
  1956. if (!e) {
  1957. e = new CMPChannel(this,ep);
  1958. add(*e);
  1959. }
  1960. return LINK(e);
  1961. }
  1962. CMPServer::CMPServer(unsigned _port)
  1963. {
  1964. RTsalt=0xff;
  1965. port = 0; // connectthread tells me what port it actually connected on
  1966. checkclosed = false;
  1967. connectthread = new CMPConnectThread(this, _port);
  1968. selecthandler = createSocketSelectHandler();
  1969. pingpackethandler = new PingPacketHandler; // TAG_SYS_PING
  1970. pingreplypackethandler = new PingReplyPacketHandler; // TAG_SYS_PING_REPLY
  1971. forwardpackethandler = new ForwardPacketHandler; // TAG_SYS_FORWARD
  1972. multipackethandler = new MultiPacketHandler; // TAG_SYS_MULTI
  1973. broadcastpackethandler = new BroadcastPacketHandler; // TAG_SYS_BCAST
  1974. userpackethandler = new UserPacketHandler(this); // default
  1975. notifyclosedthread = new CMPNotifyClosedThread(this);
  1976. notifyclosedthread->start();
  1977. selecthandler->start();
  1978. rettag = (int)TAG_REPLY_BASE; // NB negative
  1979. SocketEndpoint ep(port); // NB port set by connectthread constructor
  1980. myNode = createINode(ep);
  1981. }
  1982. CMPServer::~CMPServer()
  1983. {
  1984. #ifdef _TRACEORPHANS
  1985. StringBuffer buf;
  1986. getReceiveQueueDetails(buf);
  1987. if (buf.length())
  1988. LOG(MCdebugInfo(100), unknownJob, "MP: Orphan check\n%s",buf.str());
  1989. #endif
  1990. _releaseAll();
  1991. selecthandler->Release();
  1992. notifyclosedthread->stop();
  1993. notifyclosedthread->Release();
  1994. connectthread->Release();
  1995. delete pingpackethandler;
  1996. delete pingreplypackethandler;
  1997. delete forwardpackethandler;
  1998. delete multipackethandler;
  1999. delete broadcastpackethandler;
  2000. delete userpackethandler;
  2001. ::Release(myNode);
  2002. }
  2003. void CMPServer::checkTagOK(mptag_t tag)
  2004. {
  2005. if ((int)tag<=(int)TAG_REPLY_BASE) {
  2006. int dif = (int)TAG_REPLY_BASE-(int)tag;
  2007. if (dif%16!=RTsalt) {
  2008. ERRLOG("**Invalid MP tag used");
  2009. PrintStackReport();
  2010. }
  2011. }
  2012. }
  2013. bool CMPServer::recv(CMessageBuffer &mbuf, const SocketEndpoint *ep, mptag_t tag, CTimeMon &tm)
  2014. {
  2015. checkTagOK(tag);
  2016. class Cnfy: public CBufferQueueNotify
  2017. {
  2018. public:
  2019. bool aborted;
  2020. CMessageBuffer *result;
  2021. const SocketEndpoint *ep;
  2022. SocketEndpoint closedEp; // used if receiving on RANK_ALL
  2023. mptag_t tag;
  2024. Cnfy(const SocketEndpoint *_ep,mptag_t _tag) { ep = _ep; tag = _tag; result = NULL; aborted=false; }
  2025. bool notify(CMessageBuffer *msg)
  2026. {
  2027. if ((tag==TAG_ALL)||(tag==msg->getTag())) {
  2028. SocketEndpoint senderep = msg->getSender();
  2029. if ((ep==NULL)||ep->equals(senderep)||senderep.isNull()) {
  2030. if (msg->getReplyTag()==TAG_CANCEL)
  2031. delete msg;
  2032. else
  2033. result = msg;
  2034. return true;
  2035. }
  2036. }
  2037. return false;
  2038. }
  2039. bool notifyClosed(SocketEndpoint &_closedEp) // called when connection closed
  2040. {
  2041. if (NULL == ep) { // ep is NULL if receiving on RANK_ALL
  2042. closedEp = _closedEp;
  2043. ep = &closedEp; // used for abort info
  2044. aborted = true;
  2045. return true;
  2046. }
  2047. else if (ep->equals(_closedEp)) {
  2048. aborted = true;
  2049. return true;
  2050. }
  2051. return false;
  2052. }
  2053. } nfy(ep,tag);
  2054. if (receiveq.wait(nfy,false,tm)&&nfy.result) {
  2055. mbuf.transferFrom(*nfy.result);
  2056. delete nfy.result;
  2057. return true;
  2058. }
  2059. if (nfy.aborted) {
  2060. #ifdef _TRACELINKCLOSED
  2061. LOG(MCdebugInfo(100), unknownJob, "CMPserver::recv closed on notify");
  2062. PrintStackReport();
  2063. #endif
  2064. IMP_Exception *e=new CMPException(MPERR_link_closed,*nfy.ep);
  2065. throw e;
  2066. }
  2067. return false;
  2068. }
  2069. void CMPServer::flush(mptag_t tag)
  2070. {
  2071. class Cnfy: public CBufferQueueNotify
  2072. {
  2073. public:
  2074. mptag_t tag;
  2075. Cnfy(mptag_t _tag) { tag = _tag; }
  2076. bool notify(CMessageBuffer *msg)
  2077. {
  2078. return (tag==TAG_ALL)||(tag==msg->getTag());
  2079. }
  2080. bool notifyClosed(SocketEndpoint &closedep) // called when connection closed
  2081. {
  2082. return false;
  2083. }
  2084. } nfy(tag);
  2085. unsigned count = receiveq.flush(nfy);
  2086. if (count)
  2087. PROGLOG("CMPServer::flush(%d) discarded %u buffers",(int)tag,count);
  2088. }
  2089. void CMPServer::cancel(const SocketEndpoint *ep, mptag_t tag)
  2090. {
  2091. CMessageBuffer *cancelmsg = new CMessageBuffer(0);
  2092. SocketEndpoint send;
  2093. if (ep)
  2094. send = *ep;
  2095. cancelmsg->init(send,tag,TAG_CANCEL);
  2096. getReceiveQ().enqueue(cancelmsg);
  2097. }
  2098. unsigned CMPServer::probe(const SocketEndpoint *ep, mptag_t tag,CTimeMon &tm,SocketEndpoint &sender)
  2099. {
  2100. class Cnfy: public CBufferQueueNotify
  2101. {
  2102. public:
  2103. bool aborted;
  2104. SocketEndpoint &sender;
  2105. const SocketEndpoint *ep;
  2106. mptag_t tag;
  2107. bool cancel;
  2108. unsigned count;
  2109. Cnfy(const SocketEndpoint *_ep,mptag_t _tag,SocketEndpoint &_sender) : sender(_sender)
  2110. {
  2111. ep = _ep;
  2112. tag = _tag;
  2113. cancel = false;
  2114. aborted = false;
  2115. count = 0;
  2116. }
  2117. bool notify(CMessageBuffer *msg)
  2118. {
  2119. if (((tag==TAG_ALL)||(tag==msg->getTag()))&&
  2120. ((ep==NULL)||ep->equals(msg->getSender()))) {
  2121. if (count==0) {
  2122. sender = msg->getSender();
  2123. cancel = (msg->getReplyTag()==TAG_CANCEL);
  2124. }
  2125. count++;
  2126. return true;
  2127. }
  2128. return false;
  2129. }
  2130. bool notifyClosed(SocketEndpoint &closedep) // called when connection closed
  2131. {
  2132. if (ep&&ep->equals(closedep)) {
  2133. aborted = true;
  2134. return true;
  2135. }
  2136. return false;
  2137. }
  2138. } nfy(ep,tag,sender);
  2139. if (receiveq.wait(nfy,true,tm)) {
  2140. return nfy.cancel?0:nfy.count;
  2141. }
  2142. if (nfy.aborted) {
  2143. #ifdef _TRACELINKCLOSED
  2144. LOG(MCdebugInfo(100), unknownJob, "CMPserver::probe closed on notify");
  2145. PrintStackReport();
  2146. #endif
  2147. IMP_Exception *e=new CMPException(MPERR_link_closed,*ep);
  2148. throw e;
  2149. }
  2150. return 0;
  2151. }
  2152. void CMPServer::start()
  2153. {
  2154. connectthread->start(getPort());
  2155. }
  2156. void CMPServer::stop()
  2157. {
  2158. selecthandler->stop(true);
  2159. connectthread->stop();
  2160. CMPChannel *c = NULL;
  2161. loop {
  2162. c = (CMPChannel *)next(c);
  2163. if (!c)
  2164. break;
  2165. c->closeSocket();
  2166. }
  2167. }
  2168. void CMPServer::addConnectionMonitor(IConnectionMonitor *monitor)
  2169. {
  2170. // called in critical section CMPServer::sect
  2171. notifyclosedthread->addConnectionMonitor(monitor);
  2172. }
  2173. void CMPServer::removeConnectionMonitor(IConnectionMonitor *monitor)
  2174. {
  2175. // called in critical section CMPServer::sect
  2176. notifyclosedthread->removeConnectionMonitor(monitor);
  2177. }
  2178. void CMPServer::onAdd(void *)
  2179. {
  2180. // not used
  2181. }
  2182. void CMPServer::onRemove(void *e)
  2183. {
  2184. CMPChannel &elem=*(CMPChannel *)e;
  2185. elem.Release();
  2186. }
  2187. unsigned CMPServer::getHashFromElement(const void *e) const
  2188. {
  2189. const CMPChannel &elem=*(const CMPChannel *)e;
  2190. return elem.remoteep.hash(0);
  2191. }
  2192. unsigned CMPServer::getHashFromFindParam(const void *fp) const
  2193. {
  2194. return ((const SocketEndpoint*)fp)->hash(0);
  2195. }
  2196. const void * CMPServer::getFindParam(const void *p) const
  2197. {
  2198. const CMPChannel &elem=*(const CMPChannel *)p;
  2199. return &elem.remoteep;
  2200. }
  2201. bool CMPServer::matchesFindParam(const void * et, const void *fp, unsigned) const
  2202. {
  2203. return ((CMPChannel *)et)->remoteep.equals(*(SocketEndpoint *)fp);
  2204. }
  2205. bool CMPServer::nextChannel(CMPChannel *&cur)
  2206. {
  2207. CriticalBlock block(sect);
  2208. cur = (CMPChannel *)SuperHashTableOf<CMPChannel,SocketEndpoint>::next(cur);
  2209. return cur!=NULL;
  2210. }
  2211. void CMPServer::notifyClosed(SocketEndpoint &ep, bool trace)
  2212. {
  2213. #ifdef _TRACEMPSERVERNOTIFYCLOSED
  2214. if (trace)
  2215. {
  2216. StringBuffer url;
  2217. LOG(MCdebugInfo(100), unknownJob, "MP: CMPServer::notifyClosed %s",ep.getUrlStr(url).str());
  2218. PrintStackReport();
  2219. }
  2220. #endif
  2221. notifyclosedthread->notify(ep);
  2222. }
  2223. // --------------------------------------------------------
  2224. class CInterCommunicator: public CInterface, public IInterCommunicator
  2225. {
  2226. CMPServer *parent;
  2227. public:
  2228. IMPLEMENT_IINTERFACE;
  2229. bool send (CMessageBuffer &mbuf, INode *dst, mptag_t tag, unsigned timeout=MP_WAIT_FOREVER)
  2230. {
  2231. if (!dst)
  2232. return false;
  2233. size32_t msgsize = mbuf.length();
  2234. if (dst->equals(queryMyNode())) {
  2235. CMessageBuffer *msg = new CMessageBuffer();
  2236. mptag_t reply = mbuf.getReplyTag();
  2237. msg->transferFrom(mbuf);
  2238. msg->init(dst->endpoint(),tag,reply);
  2239. parent->getReceiveQ().enqueue(msg);
  2240. mbuf.clear(); // for consistent semantics
  2241. return true;
  2242. }
  2243. CTimeMon tm(timeout);
  2244. Owned<CMPChannel> channel = parent->lookup(dst->endpoint());
  2245. unsigned remaining;
  2246. if (tm.timedout(&remaining))
  2247. return false;
  2248. if (!channel->send(mbuf,tag,mbuf.getReplyTag(),tm,false))
  2249. return false;
  2250. mbuf.clear(); // for consistent semantics
  2251. return true;
  2252. }
  2253. bool verifyConnection(INode *node, unsigned timeout)
  2254. {
  2255. CriticalBlock block(verifysect);
  2256. CTimeMon tm(timeout);
  2257. Owned<CMPChannel> channel = parent->lookup(node->endpoint());
  2258. unsigned remaining;
  2259. if (tm.timedout(&remaining))
  2260. return false;
  2261. return channel->verifyConnection(tm,true);
  2262. }
  2263. void verifyAll(StringBuffer &log)
  2264. {
  2265. CMPChannelIterator iter(*parent);
  2266. if (iter.first()) {
  2267. do {
  2268. CriticalBlock block(verifysect);
  2269. CTimeMon tm(5000);
  2270. CMPChannel &channel = iter.query();
  2271. if (!channel.isClosed()) {
  2272. channel.queryEpStr(log).append(' ');
  2273. if (channel.verifyConnection(tm,false))
  2274. log.append("OK\n");
  2275. else
  2276. log.append("FAILED\n");
  2277. }
  2278. }
  2279. while (iter.next());
  2280. }
  2281. }
  2282. bool verifyAll(IGroup *group,bool duplex, unsigned timeout)
  2283. {
  2284. CriticalBlock block(verifysect);
  2285. CTimeMon tm(timeout);
  2286. rank_t myrank = group->rank(parent->queryMyNode());
  2287. {
  2288. ForEachNodeInGroup(rank,*group) {
  2289. bool doverify;
  2290. if (duplex)
  2291. doverify = (myrank!=rank);
  2292. else if ((rank&1)==(myrank&1))
  2293. doverify = (myrank>rank);
  2294. else
  2295. doverify = (myrank<rank);
  2296. if (doverify) {
  2297. Owned<CMPChannel> channel = parent->lookup(group->queryNode(rank).endpoint());
  2298. unsigned remaining;
  2299. if (tm.timedout(&remaining)) {
  2300. return false;
  2301. }
  2302. if (!channel->verifyConnection(tm,true)) {
  2303. return false;
  2304. }
  2305. }
  2306. }
  2307. }
  2308. if (!duplex) {
  2309. ForEachNodeInGroup(rank,*group) {
  2310. bool doverify = ((rank&1)==(myrank&1))?(myrank<rank):(myrank>rank);
  2311. if (doverify) {
  2312. Owned<CMPChannel> channel = parent->lookup(group->queryNode(rank).endpoint());
  2313. while (!channel->verifyConnection(tm,false)) {
  2314. unsigned remaining;
  2315. if (tm.timedout(&remaining))
  2316. return false;
  2317. CriticalUnblock unblock(verifysect);
  2318. Sleep(100);
  2319. }
  2320. }
  2321. }
  2322. }
  2323. return true;
  2324. }
  2325. unsigned probe(INode *src, mptag_t tag, INode **sender=NULL, unsigned timeout=0)
  2326. {
  2327. if (sender)
  2328. *sender = NULL;
  2329. SocketEndpoint res;
  2330. CTimeMon tm(timeout);
  2331. unsigned ret = parent->probe(src?&src->endpoint():NULL,tag,tm,res);
  2332. if (ret!=0) {
  2333. if (sender)
  2334. *sender = createINode(res);
  2335. return ret;
  2336. }
  2337. return 0;
  2338. }
  2339. bool recv(CMessageBuffer &mbuf, INode *src, mptag_t tag, INode **sender=NULL, unsigned timeout=MP_WAIT_FOREVER)
  2340. {
  2341. if (sender)
  2342. *sender = NULL;
  2343. CTimeMon tm(timeout);
  2344. loop
  2345. {
  2346. try
  2347. {
  2348. if (parent->recv(mbuf,src?&src->endpoint():NULL,tag,tm))
  2349. {
  2350. if (sender)
  2351. *sender = createINode(mbuf.getSender());
  2352. return true;
  2353. }
  2354. return false;
  2355. }
  2356. catch (IMP_Exception *e)
  2357. {
  2358. if (MPERR_link_closed != e->errorCode())
  2359. throw;
  2360. const SocketEndpoint &ep = e->queryEndpoint();
  2361. if (src && (ep == src->endpoint()))
  2362. throw;
  2363. // ignoring closed endpoint
  2364. e->Release();
  2365. // loop around and recv again
  2366. }
  2367. }
  2368. }
  2369. void flush(mptag_t tag)
  2370. {
  2371. parent->flush(tag);
  2372. }
  2373. bool sendRecv(CMessageBuffer &mbuff, INode *dst, mptag_t dsttag, unsigned timeout=MP_WAIT_FOREVER)
  2374. {
  2375. assertex(dst);
  2376. mptag_t replytag = parent->createReplyTag();
  2377. CTimeMon tm(timeout);
  2378. mbuff.setReplyTag(replytag);
  2379. unsigned remaining;
  2380. if (tm.timedout(&remaining))
  2381. return false;
  2382. if (!send(mbuff,dst,dsttag,remaining)||tm.timedout(&remaining))
  2383. return false;
  2384. mbuff.clear();
  2385. return recv(mbuff,dst,replytag,NULL,remaining);
  2386. }
  2387. bool reply(CMessageBuffer &mbuff, unsigned timeout=MP_WAIT_FOREVER)
  2388. {
  2389. Owned<INode> dst(createINode(mbuff.getSender()));
  2390. return send(mbuff,dst,mbuff.getReplyTag(),timeout);
  2391. }
  2392. void cancel(INode *src, mptag_t tag)
  2393. {
  2394. parent->cancel(src?&src->endpoint():NULL,tag);
  2395. }
  2396. void disconnect(INode *node)
  2397. {
  2398. CriticalBlock block(verifysect);
  2399. Owned<CMPChannel> channel = parent->lookup(node->endpoint());
  2400. channel->closeSocket();
  2401. parent->removeChannel(channel);
  2402. }
  2403. CInterCommunicator(CMPServer *_parent)
  2404. {
  2405. parent = _parent;
  2406. }
  2407. ~CInterCommunicator()
  2408. {
  2409. }
  2410. };
  2411. class CCommunicator: public CInterface, public ICommunicator
  2412. {
  2413. IGroup *group;
  2414. CMPServer *parent;
  2415. bool outer;
  2416. rank_t myrank;
  2417. const SocketEndpoint &queryEndpoint(rank_t rank)
  2418. {
  2419. return group->queryNode(rank).endpoint();
  2420. }
  2421. CMPChannel *getChannel(rank_t rank)
  2422. {
  2423. return parent->lookup(queryEndpoint(rank));
  2424. }
  2425. public:
  2426. IMPLEMENT_IINTERFACE;
  2427. bool send (CMessageBuffer &mbuf, rank_t dstrank, mptag_t tag, unsigned timeout)
  2428. {
  2429. // send does not corrupt mbuf
  2430. if (dstrank==RANK_NULL)
  2431. return false;
  2432. if (dstrank==myrank) {
  2433. CMessageBuffer *msg = mbuf.clone();
  2434. // change sender
  2435. msg->init(parent->queryMyNode()->endpoint(),tag,mbuf.getReplyTag());
  2436. parent->getReceiveQ().enqueue(msg);
  2437. }
  2438. else {
  2439. CTimeMon tm(timeout);
  2440. rank_t endrank;
  2441. if (dstrank==RANK_ALL) {
  2442. send(mbuf,myrank,tag,timeout);
  2443. dstrank = RANK_ALL_OTHER;
  2444. }
  2445. if (dstrank==RANK_ALL_OTHER) {
  2446. dstrank = 0;
  2447. endrank = group->ordinality()-1;
  2448. }
  2449. else if (dstrank==RANK_RANDOM) {
  2450. if (group->ordinality()>1) {
  2451. do {
  2452. dstrank = getRandom()%group->ordinality();
  2453. } while (dstrank==myrank);
  2454. }
  2455. else {
  2456. assertex(myrank!=0);
  2457. dstrank = 0;
  2458. }
  2459. endrank = dstrank;
  2460. }
  2461. else
  2462. endrank = dstrank;
  2463. for (;dstrank<=endrank;dstrank++) {
  2464. if (dstrank!=myrank) {
  2465. Owned<CMPChannel> channel = getChannel(dstrank);
  2466. unsigned remaining;
  2467. if (tm.timedout(&remaining))
  2468. return false;
  2469. if (!channel->send(mbuf,tag,mbuf.getReplyTag(),tm,false))
  2470. return false;
  2471. }
  2472. }
  2473. }
  2474. return true;
  2475. }
  2476. void barrier(void)
  2477. {
  2478. #ifdef _TRACE
  2479. PrintLog("MP: barrier enter");
  2480. #endif
  2481. /*
  2482. * Use the dissemination algorithm described in:
  2483. * Debra Hensgen, Raphael Finkel, and Udi Manbet, "Two Algorithms for Barrier Synchronization,"
  2484. * International Journal of Parallel Programming, 17(1):1-17, 1988.
  2485. * It uses ceiling(lgp) steps. In step k, 0 <= k <= (ceiling(lgp)-1),
  2486. * process i sends to process (i + 2^k) % p and receives from process (i - 2^k + p) % p.
  2487. */
  2488. int numranks = group->ordinality();
  2489. CMessageBuffer mb;
  2490. rank_t r;
  2491. int mask = 0x1;
  2492. while (mask < numranks)
  2493. {
  2494. int dst = (myrank + mask) % numranks;
  2495. int src = (myrank - mask + numranks) % numranks;
  2496. #ifdef _TRACE
  2497. PrintLog("MP: barrier: send to %d, recv from %d", dst, src);
  2498. #endif
  2499. // NOTE: MPI method MUST use sendrecv so as to not send/recv deadlock ...
  2500. mb.clear();
  2501. mb.append("MPTAG_BARRIER");
  2502. bool oks = send(mb,dst,MPTAG_BARRIER,120000);
  2503. mb.clear();
  2504. bool okr = recv(mb,src,MPTAG_BARRIER,&r);
  2505. if (!oks && !okr)
  2506. {
  2507. PrintLog("MP: barrier: Error sending or recving");
  2508. break;
  2509. }
  2510. mask <<= 1;
  2511. }
  2512. #ifdef _TRACE
  2513. PrintLog("MP: barrier leave");
  2514. #endif
  2515. }
  2516. bool verifyConnection(rank_t rank, unsigned timeout)
  2517. {
  2518. CriticalBlock block(verifysect);
  2519. assertex(rank!=RANK_RANDOM);
  2520. assertex(rank!=RANK_ALL);
  2521. CTimeMon tm(timeout);
  2522. Owned<CMPChannel> channel = getChannel(rank);
  2523. unsigned remaining;
  2524. if (tm.timedout(&remaining))
  2525. return false;
  2526. return channel->verifyConnection(tm,true);
  2527. }
  2528. bool verifyAll(bool duplex, unsigned timeout)
  2529. {
  2530. CriticalBlock block(verifysect);
  2531. CTimeMon tm(timeout);
  2532. {
  2533. ForEachNodeInGroup(rank,*group) {
  2534. bool doverify;
  2535. if (duplex)
  2536. doverify = (rank!=myrank);
  2537. else if ((rank&1)==(myrank&1))
  2538. doverify = (myrank>rank);
  2539. else
  2540. doverify = (myrank<rank);
  2541. if (doverify) {
  2542. Owned<CMPChannel> channel = getChannel(rank);
  2543. unsigned remaining;
  2544. if (tm.timedout(&remaining)) {
  2545. return false;
  2546. }
  2547. if (!channel->verifyConnection(tm,true))
  2548. return false;
  2549. }
  2550. }
  2551. }
  2552. if (!duplex) {
  2553. ForEachNodeInGroup(rank,*group) {
  2554. bool doverify = ((rank&1)==(myrank&1))?(myrank<rank):(myrank>rank);
  2555. if (doverify) {
  2556. Owned<CMPChannel> channel = getChannel(rank);
  2557. while (!channel->verifyConnection(tm,false)) {
  2558. unsigned remaining;
  2559. if (tm.timedout(&remaining))
  2560. return false;
  2561. CriticalUnblock unblock(verifysect);
  2562. Sleep(100);
  2563. }
  2564. }
  2565. }
  2566. }
  2567. return true;
  2568. }
  2569. unsigned probe(rank_t srcrank, mptag_t tag, rank_t *sender, unsigned timeout=0)
  2570. {
  2571. assertex(srcrank!=RANK_NULL);
  2572. SocketEndpoint res;
  2573. CTimeMon tm(timeout);
  2574. unsigned ret = parent->probe((srcrank==RANK_ALL)?NULL:&queryEndpoint(srcrank),tag,tm,res);
  2575. if (ret!=0) {
  2576. if (sender)
  2577. *sender = group->rank(res);
  2578. return ret;
  2579. }
  2580. if (sender)
  2581. *sender = RANK_NULL;
  2582. return 0;
  2583. }
  2584. bool recv(CMessageBuffer &mbuf, rank_t srcrank, mptag_t tag, rank_t *sender, unsigned timeout=MP_WAIT_FOREVER)
  2585. {
  2586. assertex(srcrank!=RANK_NULL);
  2587. const SocketEndpoint *srcep=NULL;
  2588. if (srcrank==RANK_ALL) {
  2589. if (!outer&&(group->ordinality()==1)) // minor optimization (useful in Dali)
  2590. srcep = &queryEndpoint(0);
  2591. }
  2592. else
  2593. srcep = &queryEndpoint(srcrank);
  2594. CTimeMon tm(timeout);
  2595. loop
  2596. {
  2597. try
  2598. {
  2599. if (parent->recv(mbuf,(srcrank==RANK_ALL)?NULL:&queryEndpoint(srcrank),tag,tm))
  2600. {
  2601. if (sender)
  2602. *sender = group->rank(mbuf.getSender());
  2603. return true;
  2604. }
  2605. if (sender)
  2606. *sender = RANK_NULL;
  2607. return false;
  2608. }
  2609. catch (IMP_Exception *e)
  2610. {
  2611. if (MPERR_link_closed != e->errorCode())
  2612. throw;
  2613. const SocketEndpoint &ep = e->queryEndpoint();
  2614. if (RANK_NULL != group->rank(ep))
  2615. throw;
  2616. // ignoring closed endpoint from outside the communicator group
  2617. e->Release();
  2618. // loop around and recv again
  2619. }
  2620. }
  2621. }
  2622. void flush(mptag_t tag)
  2623. {
  2624. parent->flush(tag);
  2625. }
  2626. IGroup &queryGroup() { return *group; }
  2627. IGroup *getGroup() { return LINK(group); }
  2628. bool sendRecv(CMessageBuffer &mbuff, rank_t sendrank, mptag_t sendtag, unsigned timeout=MP_WAIT_FOREVER)
  2629. {
  2630. assertex((sendrank!=RANK_NULL)&&(sendrank!=RANK_ALL));
  2631. if (sendrank==RANK_RANDOM) {
  2632. if (group->ordinality()>1) {
  2633. do {
  2634. sendrank = getRandom()%group->ordinality();
  2635. } while (sendrank==myrank);
  2636. }
  2637. else {
  2638. assertex(myrank!=0);
  2639. sendrank = 0;
  2640. }
  2641. }
  2642. mptag_t replytag = parent->createReplyTag();
  2643. CTimeMon tm(timeout);
  2644. mbuff.setReplyTag(replytag);
  2645. unsigned remaining;
  2646. if (tm.timedout(&remaining))
  2647. return false;
  2648. if (!send(mbuff,sendrank,sendtag,remaining)||tm.timedout(&remaining))
  2649. return false;
  2650. mbuff.clear();
  2651. return recv(mbuff,sendrank,replytag,NULL,remaining);
  2652. }
  2653. bool reply(CMessageBuffer &mbuf, unsigned timeout=MP_WAIT_FOREVER)
  2654. {
  2655. mptag_t replytag = mbuf.getReplyTag();
  2656. rank_t dstrank = group->rank(mbuf.getSender());
  2657. if (dstrank!=RANK_NULL) {
  2658. if (send (mbuf, dstrank, replytag,timeout)) {
  2659. mbuf.setReplyTag(TAG_NULL);
  2660. return true;
  2661. }
  2662. return false;
  2663. }
  2664. CTimeMon tm(timeout);
  2665. Owned<CMPChannel> channel = parent->lookup(mbuf.getSender());
  2666. unsigned remaining;
  2667. if (tm.timedout(&remaining)) {
  2668. return false;
  2669. }
  2670. if (channel->send(mbuf,replytag,TAG_NULL,tm, true)) {
  2671. mbuf.setReplyTag(TAG_NULL);
  2672. return true;
  2673. }
  2674. return false;
  2675. }
  2676. void cancel(rank_t srcrank, mptag_t tag)
  2677. {
  2678. assertex(srcrank!=RANK_NULL);
  2679. parent->cancel((srcrank==RANK_ALL)?NULL:&queryEndpoint(srcrank),tag);
  2680. }
  2681. void disconnect(INode *node)
  2682. {
  2683. CriticalBlock block(verifysect);
  2684. Linked<CMPChannel> channel = parent->lookup(node->endpoint());
  2685. channel->closeSocket();
  2686. parent->removeChannel(channel);
  2687. }
  2688. CCommunicator(CMPServer *_parent,IGroup *_group, bool _outer)
  2689. {
  2690. outer = _outer;
  2691. parent = _parent;
  2692. group = LINK(_group);
  2693. myrank = group->rank(parent->queryMyNode());
  2694. }
  2695. ~CCommunicator()
  2696. {
  2697. group->Release();
  2698. }
  2699. };
  2700. // Additional CMPServer methods
  2701. ICommunicator *CMPServer::createCommunicator(IGroup *group, bool outer)
  2702. {
  2703. return new CCommunicator(this,group,outer);
  2704. }
  2705. ///////////////////////////////////
  2706. IMPServer *startNewMPServer(unsigned port)
  2707. {
  2708. assertex(sizeof(PacketHeader)==32);
  2709. CMPServer *mpServer = new CMPServer(port);
  2710. mpServer->start();
  2711. return mpServer;
  2712. }
  2713. class CGlobalMPServer : public CMPServer
  2714. {
  2715. int nestLevel;
  2716. bool paused;
  2717. IInterCommunicator *worldcomm;
  2718. public:
  2719. static CriticalSection sect;
  2720. CGlobalMPServer(unsigned _port) : CMPServer(_port)
  2721. {
  2722. worldcomm = NULL;
  2723. nestLevel = 0;
  2724. }
  2725. ~CGlobalMPServer()
  2726. {
  2727. ::Release(worldcomm);
  2728. }
  2729. IInterCommunicator &queryWorldCommunicator()
  2730. {
  2731. if (!worldcomm)
  2732. worldcomm = new CInterCommunicator(this);
  2733. return *worldcomm;
  2734. }
  2735. unsigned incNest() { return ++nestLevel; }
  2736. unsigned decNest() { return --nestLevel; }
  2737. unsigned queryNest() { return nestLevel; }
  2738. bool isPaused() const { return paused; }
  2739. void setPaused(bool onOff) { paused = onOff; }
  2740. };
  2741. CriticalSection CGlobalMPServer::sect;
  2742. static CGlobalMPServer *globalMPServer;
  2743. MODULE_INIT(INIT_PRIORITY_STANDARD)
  2744. {
  2745. globalMPServer = NULL;
  2746. return true;
  2747. }
  2748. MODULE_EXIT()
  2749. {
  2750. ::Release(globalMPServer);
  2751. }
  2752. void startMPServer(unsigned port, bool paused)
  2753. {
  2754. assertex(sizeof(PacketHeader)==32);
  2755. CriticalBlock block(CGlobalMPServer::sect);
  2756. if (NULL == globalMPServer)
  2757. {
  2758. globalMPServer = new CGlobalMPServer(port);
  2759. initMyNode(globalMPServer->getPort());
  2760. }
  2761. if (0 == globalMPServer->queryNest())
  2762. {
  2763. if (paused)
  2764. {
  2765. globalMPServer->setPaused(paused);
  2766. return;
  2767. }
  2768. queryLogMsgManager()->setPort(globalMPServer->getPort());
  2769. globalMPServer->start();
  2770. globalMPServer->setPaused(false);
  2771. }
  2772. globalMPServer->incNest();
  2773. }
  2774. void stopMPServer()
  2775. {
  2776. CGlobalMPServer *_globalMPServer = NULL;
  2777. {
  2778. CriticalBlock block(CGlobalMPServer::sect);
  2779. if (NULL == globalMPServer)
  2780. return;
  2781. if (0 == globalMPServer->decNest())
  2782. {
  2783. stopLogMsgReceivers();
  2784. #ifdef _TRACE
  2785. LOG(MCdebugInfo(100), unknownJob, "MP: Stopping MP Server");
  2786. #endif
  2787. _globalMPServer = globalMPServer;
  2788. globalMPServer = NULL;
  2789. }
  2790. }
  2791. if (NULL == _globalMPServer)
  2792. return;
  2793. _globalMPServer->stop();
  2794. _globalMPServer->Release();
  2795. #ifdef _TRACE
  2796. LOG(MCdebugInfo(100), unknownJob, "MP: Stopped MP Server");
  2797. #endif
  2798. CriticalBlock block(CGlobalMPServer::sect);
  2799. initMyNode(0);
  2800. }
  2801. bool hasMPServerStarted()
  2802. {
  2803. CriticalBlock block(CGlobalMPServer::sect);
  2804. return globalMPServer != NULL;
  2805. }
  2806. IInterCommunicator &queryWorldCommunicator()
  2807. {
  2808. CriticalBlock block(CGlobalMPServer::sect);
  2809. assertex(globalMPServer);
  2810. return globalMPServer->queryWorldCommunicator();
  2811. }
  2812. mptag_t createReplyTag()
  2813. {
  2814. assertex(globalMPServer);
  2815. return globalMPServer->createReplyTag();
  2816. }
  2817. ICommunicator *createCommunicator(IGroup *group, bool outer)
  2818. {
  2819. assertex(globalMPServer);
  2820. return globalMPServer->createCommunicator(group, outer);
  2821. }
  2822. StringBuffer &getReceiveQueueDetails(StringBuffer &buf)
  2823. {
  2824. CriticalBlock block(CGlobalMPServer::sect);
  2825. if (globalMPServer)
  2826. globalMPServer->getReceiveQueueDetails(buf);
  2827. return buf;
  2828. }
  2829. void addMPConnectionMonitor(IConnectionMonitor *monitor)
  2830. {
  2831. CriticalBlock block(CGlobalMPServer::sect);
  2832. assertex(globalMPServer);
  2833. globalMPServer->addConnectionMonitor(monitor);
  2834. }
  2835. void removeMPConnectionMonitor(IConnectionMonitor *monitor)
  2836. {
  2837. CriticalBlock block(CGlobalMPServer::sect);
  2838. if (globalMPServer)
  2839. globalMPServer->removeConnectionMonitor(monitor);
  2840. }
  2841. IMPServer *getMPServer()
  2842. {
  2843. CriticalBlock block(CGlobalMPServer::sect);
  2844. assertex(globalMPServer);
  2845. return LINK(globalMPServer);
  2846. }
  2847. void registerSelfDestructChildProcess(HANDLE handle)
  2848. {
  2849. CriticalBlock block(childprocesssect);
  2850. if (handle!=(HANDLE)-1)
  2851. childprocesslist.append((unsigned)handle);
  2852. }
  2853. void unregisterSelfDestructChildProcess(HANDLE handle)
  2854. {
  2855. CriticalBlock block(childprocesssect);
  2856. if (handle!=(HANDLE)-1)
  2857. childprocesslist.zap((unsigned)handle);
  2858. }