mpcomm.cpp 95 KB

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