mpcomm.cpp 90 KB

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