mpcomm.cpp 104 KB

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