mpcomm.cpp 104 KB

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