mpcomm.cpp 92 KB

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