mpcomm.cpp 88 KB

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