mpcomm.cpp 77 KB

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