mpcomm.cpp 75 KB

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