mpcomm.cpp 79 KB

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