ccdqueue.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101
  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. #include <platform.h>
  14. #include <jlib.hpp>
  15. #include <jio.hpp>
  16. #include <jqueue.tpp>
  17. #include <jsocket.hpp>
  18. #include <jlog.hpp>
  19. #include "jisem.hpp"
  20. #include "udplib.hpp"
  21. #include "udptopo.hpp"
  22. #include "ccd.hpp"
  23. #include "ccddebug.hpp"
  24. #include "ccdquery.hpp"
  25. #include "ccdstate.hpp"
  26. #include "ccdqueue.ipp"
  27. #include "ccdsnmp.hpp"
  28. #ifdef _USE_CPPUNIT
  29. #include <cppunit/extensions/HelperMacros.h>
  30. #endif
  31. using roxiemem::OwnedRoxieRow;
  32. using roxiemem::OwnedConstRoxieRow;
  33. using roxiemem::IRowManager;
  34. using roxiemem::DataBuffer;
  35. //============================================================================================
  36. RoxiePacketHeader::RoxiePacketHeader(const RemoteActivityId &_remoteId, ruid_t _uid, unsigned _channel, unsigned _overflowSequence)
  37. {
  38. packetlength = sizeof(RoxiePacketHeader);
  39. #ifdef TIME_PACKETS
  40. tick = 0;
  41. #endif
  42. init(_remoteId, _uid, _channel, _overflowSequence);
  43. }
  44. RoxiePacketHeader::RoxiePacketHeader(const RoxiePacketHeader &source, unsigned _activityId, unsigned subChannel) : serverId(source.serverId)
  45. {
  46. // Used to create the header to send a callback to originating server or an IBYTI to a buddy
  47. activityId = _activityId;
  48. uid = source.uid;
  49. queryHash = source.queryHash;
  50. channel = source.channel;
  51. overflowSequence = source.overflowSequence;
  52. continueSequence = source.continueSequence;
  53. if (_activityId >= ROXIE_ACTIVITY_SPECIAL_FIRST && _activityId <= ROXIE_ACTIVITY_SPECIAL_LAST)
  54. overflowSequence |= OUTOFBAND_SEQUENCE; // Need to make sure it is not treated as dup of actual reply in the udp layer
  55. retries = getSubChannelMask(subChannel) | (source.retries & ~ROXIE_RETRIES_MASK);
  56. #ifdef TIME_PACKETS
  57. tick = source.tick;
  58. #endif
  59. #ifdef SUBCHANNELS_IN_HEADER
  60. memcpy(subChannels, source.subChannels, sizeof(subChannels));
  61. #endif
  62. packetlength = sizeof(RoxiePacketHeader);
  63. }
  64. unsigned RoxiePacketHeader::getSubChannelMask(unsigned subChannel)
  65. {
  66. return SUBCHANNEL_MASK << (SUBCHANNEL_BITS * subChannel);
  67. }
  68. unsigned RoxiePacketHeader::priorityHash() const
  69. {
  70. // Used to determine which agent to act as primary and which as secondary for a given packet (thus spreading the load)
  71. // It's important that we do NOT include channel (since that would result in different values for the different agents responding to a broadcast)
  72. // We also don't include continueSequence since we'd prefer continuations to go the same way as original
  73. unsigned hash = serverId.hash();
  74. hash = hashc((const unsigned char *) &uid, sizeof(uid), hash);
  75. hash += overflowSequence; // MORE - is this better than hashing?
  76. if (traceLevel > 9)
  77. {
  78. StringBuffer s;
  79. DBGLOG("Calculating hash: %s hash was %d", toString(s).str(), hash);
  80. }
  81. return hash;
  82. }
  83. void RoxiePacketHeader::copy(const RoxiePacketHeader &oh)
  84. {
  85. // used for saving away kill packets for later matching by match
  86. uid = oh.uid;
  87. overflowSequence = oh.overflowSequence;
  88. continueSequence = oh.continueSequence;
  89. serverId = oh.serverId;
  90. channel = oh.channel;
  91. // MORE - would it be safer, maybe even faster to copy the rest too?
  92. }
  93. bool RoxiePacketHeader::matchPacket(const RoxiePacketHeader &oh) const
  94. {
  95. // used when matching up a kill packet against a pending one...
  96. // DO NOT compare activityId - they are not supposed to match, since 0 in activityid identifies ibyti!
  97. return
  98. oh.uid==uid &&
  99. (oh.overflowSequence & ~OUTOFBAND_SEQUENCE) == (overflowSequence & ~OUTOFBAND_SEQUENCE) &&
  100. oh.continueSequence == continueSequence &&
  101. oh.serverId==serverId &&
  102. oh.channel==channel;
  103. }
  104. void RoxiePacketHeader::init(const RemoteActivityId &_remoteId, ruid_t _uid, unsigned _channel, unsigned _overflowSequence)
  105. {
  106. retries = 0;
  107. activityId = _remoteId.activityId;
  108. queryHash = _remoteId.queryHash;
  109. uid = _uid;
  110. serverId = myNode;
  111. channel = _channel;
  112. overflowSequence = _overflowSequence;
  113. continueSequence = 0;
  114. #ifdef SUBCHANNELS_IN_HEADER
  115. clearSubChannels();
  116. #endif
  117. }
  118. #ifdef SUBCHANNELS_IN_HEADER
  119. void RoxiePacketHeader::clearSubChannels()
  120. {
  121. for (unsigned idx = 0; idx < MAX_SUBCHANNEL; idx++)
  122. subChannels[idx].clear();
  123. }
  124. #endif
  125. StringBuffer &RoxiePacketHeader::toString(StringBuffer &ret) const
  126. {
  127. const IpAddress serverIP = serverId.getIpAddress();
  128. ret.append("activityId=");
  129. switch(activityId & ~ROXIE_PRIORITY_MASK)
  130. {
  131. case 0: ret.append("IBYTI"); break;
  132. case ROXIE_UNLOAD: ret.append("ROXIE_UNLOAD"); break;
  133. case ROXIE_PING: ret.append("ROXIE_PING"); break;
  134. case ROXIE_TRACEINFO: ret.append("ROXIE_TRACEINFO"); break;
  135. case ROXIE_DEBUGREQUEST: ret.append("ROXIE_DEBUGREQUEST"); break;
  136. case ROXIE_DEBUGCALLBACK: ret.append("ROXIE_DEBUGCALLBACK"); break;
  137. case ROXIE_FILECALLBACK: ret.append("ROXIE_FILECALLBACK"); break;
  138. case ROXIE_ALIVE: ret.append("ROXIE_ALIVE"); break;
  139. case ROXIE_KEYEDLIMIT_EXCEEDED: ret.append("ROXIE_KEYEDLIMIT_EXCEEDED"); break;
  140. case ROXIE_LIMIT_EXCEEDED: ret.append("ROXIE_LIMIT_EXCEEDED"); break;
  141. case ROXIE_EXCEPTION: ret.append("ROXIE_EXCEPTION"); break;
  142. default:
  143. ret.appendf("%u", (activityId & ~(ROXIE_ACTIVITY_FETCH | ROXIE_PRIORITY_MASK)));
  144. if (activityId & ROXIE_ACTIVITY_FETCH)
  145. ret.appendf(" (fetch part)");
  146. break;
  147. }
  148. ret.appendf(" uid=" RUIDF " pri=", uid);
  149. switch(activityId & ROXIE_PRIORITY_MASK)
  150. {
  151. case ROXIE_SLA_PRIORITY: ret.append("SLA"); break;
  152. case ROXIE_HIGH_PRIORITY: ret.append("HIGH"); break;
  153. case ROXIE_LOW_PRIORITY: ret.append("LOW"); break;
  154. default: ret.append("???"); break;
  155. }
  156. ret.appendf(" queryHash=%" I64F "x ch=%u seq=%d cont=%d server=", queryHash, channel, overflowSequence, continueSequence);
  157. serverIP.getIpText(ret);
  158. if (retries)
  159. {
  160. if (retries==QUERY_ABORTED)
  161. ret.append(" retries=QUERY_ABORTED");
  162. else
  163. {
  164. if (retries & ROXIE_RETRIES_MASK)
  165. ret.appendf(" retries=%04x", retries);
  166. if (retries & ROXIE_FASTLANE)
  167. ret.appendf(" FASTLANE");
  168. if (retries & ROXIE_BROADCAST)
  169. ret.appendf(" BROADCAST");
  170. }
  171. }
  172. #ifdef SUBCHANNELS_IN_HEADER
  173. ret.append(" subchannels=");
  174. for (unsigned idx = 0; idx < MAX_SUBCHANNEL; idx++)
  175. {
  176. if (subChannels[idx].isNull())
  177. break;
  178. if (idx)
  179. ret.append(',');
  180. subChannels[idx].getTraceText(ret);
  181. if (subChannels[idx].isMe())
  182. {
  183. ret.append("(me)");
  184. }
  185. }
  186. #endif
  187. return ret;
  188. }
  189. bool RoxiePacketHeader::allChannelsFailed()
  190. {
  191. unsigned mask = (1 << (getNumAgents(channel) * SUBCHANNEL_BITS)) - 1;
  192. return (retries & mask) == mask;
  193. }
  194. bool RoxiePacketHeader::retry()
  195. {
  196. bool worthRetrying = false;
  197. unsigned mask = SUBCHANNEL_MASK;
  198. unsigned numAgents = getNumAgents(channel);
  199. for (unsigned subChannel = 0; subChannel < numAgents; subChannel++)
  200. {
  201. unsigned subRetries = (retries & mask) >> (subChannel * SUBCHANNEL_BITS);
  202. if (subRetries != SUBCHANNEL_MASK)
  203. subRetries++;
  204. if (subRetries != SUBCHANNEL_MASK)
  205. worthRetrying = true;
  206. retries = (retries & ~mask) | (subRetries << (subChannel * SUBCHANNEL_BITS));
  207. mask <<= SUBCHANNEL_BITS;
  208. }
  209. return worthRetrying;
  210. }
  211. void RoxiePacketHeader::setException(unsigned subChannel)
  212. {
  213. retries |= SUBCHANNEL_MASK << (SUBCHANNEL_BITS * subChannel);
  214. }
  215. unsigned RoxiePacketHeader::thisChannelRetries(unsigned subChannel)
  216. {
  217. unsigned shift = SUBCHANNEL_BITS * subChannel;
  218. unsigned mask = SUBCHANNEL_MASK << shift;
  219. return (retries & mask) >> shift;
  220. }
  221. //============================================================================================
  222. unsigned getReplicationLevel(unsigned channel)
  223. {
  224. if (!channel)
  225. return 0;
  226. Owned<const ITopologyServer> topology = getTopology();
  227. return topology->queryChannelInfo(channel).replicationLevel();
  228. }
  229. //============================================================================================
  230. // This function maps a agent number to the multicast ip used to talk to it.
  231. IpAddress multicastBase("239.1.1.1"); // TBD IPv6 (need IPv6 multicast addresses?
  232. IpAddress multicastLast("239.1.5.254");
  233. const IpAddress &getChannelIp(IpAddress &ip, unsigned _channel)
  234. {
  235. // need to be careful to avoid the .0's and the .255's (not sure why...)
  236. ip = multicastBase;
  237. if (!ip.ipincrement(_channel,1,254,1,0xffff)
  238. ||(ip.ipcompare(multicastLast)>0))
  239. throw MakeStringException(ROXIE_MULTICAST_ERROR, "Out-of-range multicast channel %d", _channel);
  240. return ip;
  241. }
  242. static Owned<ISocket> multicastSocket;
  243. void joinMulticastChannel(unsigned channel)
  244. {
  245. IpAddress multicastIp;
  246. getChannelIp(multicastIp, channel);
  247. SocketEndpoint ep(ccdMulticastPort, multicastIp);
  248. StringBuffer epStr;
  249. ep.getUrlStr(epStr);
  250. if (!multicastSocket->join_multicast_group(ep))
  251. throw MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to join multicast channel %d (%s)", channel, epStr.str());
  252. if (traceLevel)
  253. DBGLOG("Joined multicast channel %d (%s)", channel, epStr.str());
  254. }
  255. static SocketEndpointArray multicastEndpoints; // indexed by channel
  256. void setMulticastEndpoints(unsigned numChannels)
  257. {
  258. for (unsigned channel = 0; channel <= numChannels; channel++) // NOTE - channel 0 is special, and numChannels does not include it
  259. {
  260. IpAddress multicastIp;
  261. getChannelIp(multicastIp, channel);
  262. multicastEndpoints.append(SocketEndpoint(ccdMulticastPort, multicastIp));
  263. }
  264. }
  265. void openMulticastSocket()
  266. {
  267. if (!multicastSocket)
  268. {
  269. multicastSocket.setown(ISocket::udp_create(ccdMulticastPort));
  270. if (multicastTTL)
  271. {
  272. multicastSocket->set_ttl(multicastTTL);
  273. DBGLOG("Roxie: multicastTTL: %u", multicastTTL);
  274. }
  275. else
  276. DBGLOG("Roxie: multicastTTL not set");
  277. multicastSocket->set_receive_buffer_size(udpMulticastBufferSize);
  278. size32_t actualSize = multicastSocket->get_receive_buffer_size();
  279. if (actualSize < udpMulticastBufferSize)
  280. {
  281. DBGLOG("Roxie: multicast socket buffer size could not be set (requested=%d actual %d", udpMulticastBufferSize, actualSize);
  282. throwUnexpected();
  283. }
  284. if (traceLevel)
  285. DBGLOG("Roxie: multicast socket created port=%d sockbuffsize=%d actual %d", ccdMulticastPort, udpMulticastBufferSize, actualSize);
  286. if (roxieMulticastEnabled && !localAgent)
  287. {
  288. Owned<const ITopologyServer> topology = getTopology();
  289. for (unsigned channel : topology->queryChannels())
  290. {
  291. assertex(channel);
  292. joinMulticastChannel(channel);
  293. }
  294. joinMulticastChannel(0); // all agents also listen on channel 0
  295. }
  296. }
  297. }
  298. void closeMulticastSockets()
  299. {
  300. multicastSocket.clear();
  301. }
  302. static bool channelWrite(RoxiePacketHeader &buf, bool includeSelf)
  303. {
  304. size32_t minwrote = 0;
  305. if (roxieMulticastEnabled)
  306. {
  307. return multicastSocket->udp_write_to(multicastEndpoints.item(buf.channel), &buf, buf.packetlength) == buf.packetlength;
  308. }
  309. else
  310. {
  311. #ifdef SUBCHANNELS_IN_HEADER
  312. // In the containerized system, the list of subchannel IPs is captured in the packet header to ensure everyone is using the
  313. // same snapshot of the topology state.
  314. // If the subchannel IPs are not set, fill them in now. If they are set, use them.
  315. if (buf.subChannels[0].isNull())
  316. {
  317. Owned<const ITopologyServer> topo = getTopology();
  318. const SocketEndpointArray &eps = topo->queryAgents(buf.channel);
  319. if (!eps.ordinality())
  320. throw makeStringExceptionV(0, "No agents available for channel %d", buf.channel);
  321. if (buf.channel==0)
  322. {
  323. // Note that we expand any writes on channel 0 here, since we need to capture the server's view of what agents are on each channel
  324. bool allOk = true;
  325. if (traceRoxiePackets)
  326. {
  327. StringBuffer header;
  328. DBGLOG("Translating packet sent to channel 0: %s", buf.toString(header).str());
  329. }
  330. for (unsigned channel = 0; channel < numChannels; channel++)
  331. {
  332. buf.channel = channel+1;
  333. if (!channelWrite(buf, true))
  334. allOk = false;
  335. buf.clearSubChannels();
  336. }
  337. buf.channel = 0;
  338. return allOk;
  339. }
  340. unsigned hdrHashVal = buf.priorityHash();
  341. unsigned numAgents = eps.ordinality();
  342. unsigned subChannel = (hdrHashVal % numAgents);
  343. for (unsigned idx = 0; idx < MAX_SUBCHANNEL; idx++)
  344. {
  345. if (idx == numAgents)
  346. break;
  347. buf.subChannels[idx].setIp(eps.item(subChannel));
  348. subChannel++;
  349. if (subChannel == numAgents)
  350. subChannel = 0;
  351. }
  352. }
  353. else
  354. {
  355. assert(buf.channel != 0);
  356. }
  357. for (unsigned subChannel = 0; subChannel < MAX_SUBCHANNEL; subChannel++)
  358. {
  359. if (buf.subChannels[subChannel].isNull())
  360. break;
  361. if (includeSelf || !buf.subChannels[subChannel].isMe())
  362. {
  363. if (traceRoxiePackets)
  364. {
  365. StringBuffer s, header;
  366. DBGLOG("Writing %d bytes to subchannel %d (%s) %s", buf.packetlength, subChannel, buf.subChannels[subChannel].getTraceText(s).str(), buf.toString(header).str());
  367. }
  368. SocketEndpoint ep(ccdMulticastPort, buf.subChannels[subChannel].getIpAddress());
  369. size32_t wrote = multicastSocket->udp_write_to(ep, &buf, buf.packetlength);
  370. if (!subChannel || wrote < minwrote)
  371. minwrote = wrote;
  372. if (delaySubchannelPackets)
  373. MilliSleep(100);
  374. }
  375. else if (traceRoxiePackets)
  376. {
  377. StringBuffer s, header;
  378. DBGLOG("NOT writing %d bytes to subchannel %d (%s) %s", buf.packetlength, subChannel, buf.subChannels[subChannel].getTraceText(s).str(), buf.toString(header).str());
  379. }
  380. }
  381. #else
  382. Owned<const ITopologyServer> topo = getTopology();
  383. const SocketEndpointArray &eps = topo->queryAgents(buf.channel);
  384. if (!eps.ordinality())
  385. throw makeStringExceptionV(0, "No agents available for channel %d", buf.channel);
  386. ForEachItemIn(idx, eps)
  387. {
  388. size32_t wrote = multicastSocket->udp_write_to(eps.item(idx), &buf, buf.packetlength);
  389. if (!idx || wrote < minwrote)
  390. minwrote = wrote;
  391. }
  392. #endif
  393. }
  394. return minwrote==buf.packetlength;
  395. }
  396. //============================================================================================
  397. class CRoxieQueryPacket : implements IRoxieQueryPacket, public CInterface
  398. {
  399. protected:
  400. RoxiePacketHeader *data;
  401. const byte *continuationData;
  402. unsigned continuationLength;
  403. const byte *smartStepInfoData;
  404. unsigned smartStepInfoLength;
  405. const byte *contextData;
  406. unsigned contextLength;
  407. const byte *traceInfo;
  408. unsigned traceLength;
  409. public:
  410. IMPLEMENT_IINTERFACE;
  411. CRoxieQueryPacket(const void *_data, int lengthRemaining) : data((RoxiePacketHeader *) _data)
  412. {
  413. assertex(lengthRemaining >= (int) sizeof(RoxiePacketHeader));
  414. data->packetlength = lengthRemaining;
  415. const byte *finger = (const byte *) (data + 1);
  416. lengthRemaining -= sizeof(RoxiePacketHeader);
  417. if (data->activityId == ROXIE_FILECALLBACK || data->activityId == ROXIE_DEBUGCALLBACK || data->retries == QUERY_ABORTED)
  418. {
  419. continuationData = NULL;
  420. continuationLength = 0;
  421. smartStepInfoData = NULL;
  422. smartStepInfoLength = 0;
  423. traceInfo = NULL;
  424. traceLength = 0;
  425. }
  426. else
  427. {
  428. if (data->continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)
  429. {
  430. assertex(lengthRemaining >= (int) sizeof(unsigned short));
  431. continuationLength = *(unsigned short *) finger;
  432. continuationData = finger + sizeof(unsigned short);
  433. finger = continuationData + continuationLength;
  434. lengthRemaining -= continuationLength + sizeof(unsigned short);
  435. }
  436. else
  437. {
  438. continuationData = NULL;
  439. continuationLength = 0;
  440. }
  441. if (data->continueSequence & CONTINUE_SEQUENCE_SKIPTO)
  442. {
  443. assertex(lengthRemaining >= (int) sizeof(unsigned short));
  444. smartStepInfoLength = *(unsigned short *) finger;
  445. smartStepInfoData = finger + sizeof(unsigned short);
  446. finger = smartStepInfoData + smartStepInfoLength;
  447. lengthRemaining -= smartStepInfoLength + sizeof(unsigned short);
  448. }
  449. else
  450. {
  451. smartStepInfoData = NULL;
  452. smartStepInfoLength = 0;
  453. }
  454. assertex(lengthRemaining > 1);
  455. traceInfo = finger;
  456. lengthRemaining--;
  457. if (*finger++ & LOGGING_DEBUGGERACTIVE)
  458. {
  459. assertex(lengthRemaining >= (int) sizeof(unsigned short));
  460. unsigned short debugLen = *(unsigned short *) finger;
  461. finger += debugLen + sizeof(unsigned short);
  462. lengthRemaining -= debugLen + sizeof(unsigned short);
  463. }
  464. for (;;)
  465. {
  466. assertex(lengthRemaining>0);
  467. if (!*finger)
  468. {
  469. lengthRemaining--;
  470. finger++;
  471. break;
  472. }
  473. lengthRemaining--;
  474. finger++;
  475. }
  476. traceLength = finger - traceInfo;
  477. }
  478. assertex(lengthRemaining >= 0);
  479. contextData = finger;
  480. contextLength = lengthRemaining;
  481. }
  482. ~CRoxieQueryPacket()
  483. {
  484. free(data);
  485. }
  486. virtual RoxiePacketHeader &queryHeader() const
  487. {
  488. return *data;
  489. }
  490. virtual const void *queryContinuationData() const
  491. {
  492. return continuationData;
  493. }
  494. virtual unsigned getContinuationLength() const
  495. {
  496. return continuationLength;
  497. }
  498. virtual const byte *querySmartStepInfoData() const
  499. {
  500. return smartStepInfoData;
  501. }
  502. virtual unsigned getSmartStepInfoLength() const
  503. {
  504. return smartStepInfoLength;
  505. }
  506. virtual const byte *queryTraceInfo() const
  507. {
  508. return traceInfo;
  509. }
  510. virtual unsigned getTraceLength() const
  511. {
  512. return traceLength;
  513. }
  514. virtual const void *queryContextData() const
  515. {
  516. return contextData;
  517. }
  518. virtual unsigned getContextLength() const
  519. {
  520. return contextLength;
  521. }
  522. virtual IRoxieQueryPacket *clonePacket(unsigned channel) const
  523. {
  524. unsigned length = data->packetlength;
  525. RoxiePacketHeader *newdata = (RoxiePacketHeader *) malloc(length);
  526. memcpy(newdata, data, length);
  527. newdata->channel = channel;
  528. newdata->retries |= ROXIE_BROADCAST;
  529. return createRoxiePacket(newdata, length);
  530. }
  531. virtual IRoxieQueryPacket *insertSkipData(size32_t skipDataLen, const void *skipData) const
  532. {
  533. assertex((data->continueSequence & CONTINUE_SEQUENCE_SKIPTO) == 0); // Should not already be any skipto info in the source packet
  534. unsigned newDataSize = data->packetlength + sizeof(unsigned short) + skipDataLen;
  535. char *newdata = (char *) malloc(newDataSize);
  536. unsigned headSize = sizeof(RoxiePacketHeader);
  537. if (data->continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)
  538. headSize += sizeof(unsigned short) + continuationLength;
  539. memcpy(newdata, data, headSize); // copy in leading part of old data
  540. ((RoxiePacketHeader *) newdata)->continueSequence |= CONTINUE_SEQUENCE_SKIPTO; // set flag indicating new data is present
  541. *(unsigned short *) (newdata + headSize) = skipDataLen; // add length field for new data
  542. memcpy(newdata + headSize + sizeof(unsigned short), skipData, skipDataLen); // copy in new data
  543. memcpy(newdata + headSize + sizeof(unsigned short) + skipDataLen, ((char *) data) + headSize, data->packetlength - headSize); // copy in remaining old data
  544. return createRoxiePacket(newdata, newDataSize);
  545. }
  546. virtual unsigned hash() const
  547. {
  548. // This is used for Roxie server-side caching. The hash includes some of the header and all of the payload.
  549. unsigned hash = 0;
  550. if (continuationLength)
  551. hash = hashc((const unsigned char *) continuationData, continuationLength, hash);
  552. if (smartStepInfoLength)
  553. hash = hashc((const unsigned char *) smartStepInfoData, smartStepInfoLength, hash);
  554. // NOTE - don't hash the trace info!
  555. hash = hashc((const unsigned char *) contextData, contextLength, hash);
  556. hash = hashc((const unsigned char *) &data->channel, sizeof(data->channel), hash);
  557. hash = hashc((const unsigned char *) &data->overflowSequence, sizeof(data->overflowSequence), hash);
  558. hash = hashc((const unsigned char *) &data->continueSequence, sizeof(data->continueSequence), hash);
  559. // MORE - sequence fields should always be zero for anything we are caching I think... (?)
  560. // Note - no point hashing activityId (as cache is local to one activity) or serverIP (likewise)
  561. return hash;
  562. }
  563. virtual bool cacheMatch(const IRoxieQueryPacket *c) const
  564. {
  565. // note - this checks whether it's a repeat from Roxie server's point-of-view
  566. // So fields that are compared are the same as the ones that are hashed....
  567. RoxiePacketHeader &h = c->queryHeader();
  568. if (data->channel == h.channel && data->overflowSequence == h.overflowSequence && data->continueSequence == h.continueSequence)
  569. {
  570. if (continuationLength) // note - we already checked that sequences match
  571. {
  572. if (continuationLength != c->getContinuationLength())
  573. return false;
  574. if (memcmp(continuationData,c->queryContinuationData(),continuationLength)!=0)
  575. return false;
  576. }
  577. if (smartStepInfoLength)
  578. {
  579. if (smartStepInfoLength != c->getSmartStepInfoLength())
  580. return false;
  581. if (memcmp(smartStepInfoData,c->querySmartStepInfoData(),smartStepInfoLength)!=0)
  582. return false;
  583. }
  584. // NOTE - trace info NOT compared
  585. if (contextLength == c->getContextLength() && memcmp(contextData, c->queryContextData(), contextLength)==0)
  586. return true;
  587. }
  588. return false;
  589. }
  590. };
  591. extern IRoxieQueryPacket *createRoxiePacket(void *_data, unsigned _len)
  592. {
  593. if ((unsigned short)_len != _len && !localAgent)
  594. {
  595. StringBuffer s;
  596. RoxiePacketHeader *header = (RoxiePacketHeader *) _data;
  597. header->toString(s);
  598. free(_data);
  599. throw MakeStringException(ROXIE_PACKET_ERROR, "Packet length %d exceeded maximum sending packet %s", _len, s.str());
  600. }
  601. return new CRoxieQueryPacket(_data, _len);
  602. }
  603. extern IRoxieQueryPacket *createRoxiePacket(MemoryBuffer &m)
  604. {
  605. unsigned length = m.length(); // don't make assumptions about evaluation order of parameters...
  606. return createRoxiePacket(m.detachOwn(), length);
  607. }
  608. //=================================================================================
  609. AgentContextLogger::AgentContextLogger()
  610. {
  611. GetHostIp(ip);
  612. set(NULL);
  613. }
  614. AgentContextLogger::AgentContextLogger(IRoxieQueryPacket *packet)
  615. {
  616. GetHostIp(ip);
  617. set(packet);
  618. }
  619. void AgentContextLogger::set(IRoxieQueryPacket *packet)
  620. {
  621. anyOutput = false;
  622. intercept = false;
  623. debuggerActive = false;
  624. checkingHeap = false;
  625. aborted = false;
  626. stats.reset();
  627. start = msTick();
  628. if (packet)
  629. {
  630. CriticalBlock b(crit);
  631. RoxiePacketHeader &header = packet->queryHeader();
  632. const byte *traceInfo = packet->queryTraceInfo();
  633. unsigned traceLength = packet->getTraceLength();
  634. unsigned char loggingFlags = *traceInfo;
  635. if (loggingFlags & LOGGING_FLAGSPRESENT) // should always be true.... but this flag is handy to avoid flags byte ever being NULL
  636. {
  637. traceInfo++;
  638. traceLength--;
  639. if (loggingFlags & LOGGING_INTERCEPTED)
  640. intercept = true;
  641. if (loggingFlags & LOGGING_TRACELEVELSET)
  642. {
  643. ctxTraceLevel = (*traceInfo++ - 1); // avoid null byte here in case anyone still thinks there's just a null-terminated string
  644. traceLength--;
  645. }
  646. if (loggingFlags & LOGGING_BLIND)
  647. blind = true;
  648. if (loggingFlags & LOGGING_CHECKINGHEAP)
  649. checkingHeap = true;
  650. if (loggingFlags & LOGGING_DEBUGGERACTIVE)
  651. {
  652. assertex(traceLength > sizeof(unsigned short));
  653. debuggerActive = true;
  654. unsigned short debugLen = *(unsigned short *) traceInfo;
  655. traceInfo += debugLen + sizeof(unsigned short);
  656. traceLength -= debugLen + sizeof(unsigned short);
  657. }
  658. // Passing the wuid via the logging context prefix is a lot of a hack...
  659. if (loggingFlags & LOGGING_WUID)
  660. {
  661. unsigned wuidLen = 0;
  662. while (wuidLen < traceLength)
  663. {
  664. if (traceInfo[wuidLen]=='@'||traceInfo[wuidLen]==':')
  665. break;
  666. wuidLen++;
  667. }
  668. wuid.set((const char *) traceInfo, wuidLen);
  669. }
  670. }
  671. channel = header.channel;
  672. StringBuffer s(traceLength, (const char *) traceInfo);
  673. s.append("|");
  674. ip.getIpText(s);
  675. s.append(':').append(channel);
  676. StringContextLogger::set(s.str());
  677. if (intercept || mergeAgentStatistics)
  678. {
  679. RoxiePacketHeader newHeader(header, ROXIE_TRACEINFO, 0); // subchannel not relevant
  680. output.setown(ROQ->createOutputStream(newHeader, true, *this));
  681. }
  682. }
  683. else
  684. {
  685. StringContextLogger::set("");
  686. channel = 0;
  687. }
  688. }
  689. void AgentContextLogger::putStatProcessed(unsigned subGraphId, unsigned actId, unsigned idx, unsigned processed, unsigned strands) const
  690. {
  691. if (output && mergeAgentStatistics)
  692. {
  693. MemoryBuffer buf;
  694. buf.append((char) LOG_CHILDCOUNT); // A special log entry for the stats
  695. buf.append(subGraphId);
  696. buf.append(actId);
  697. buf.append(idx);
  698. buf.append(processed);
  699. buf.append(strands);
  700. }
  701. }
  702. void AgentContextLogger::putStats(unsigned subGraphId, unsigned actId, const CRuntimeStatisticCollection &stats) const
  703. {
  704. if (output && mergeAgentStatistics)
  705. {
  706. MemoryBuffer buf;
  707. buf.append((char) LOG_CHILDSTATS); // A special log entry for the stats
  708. buf.append(subGraphId);
  709. buf.append(actId);
  710. if (stats.serialize(buf))
  711. {
  712. unsigned len = buf.length();
  713. void *ret = output->getBuffer(len, true);
  714. memcpy(ret, buf.toByteArray(), len);
  715. output->putBuffer(ret, len, true);
  716. anyOutput = true;
  717. }
  718. }
  719. }
  720. void AgentContextLogger::flush()
  721. {
  722. if (output)
  723. {
  724. CriticalBlock b(crit);
  725. if (mergeAgentStatistics)
  726. {
  727. MemoryBuffer buf;
  728. buf.append((char) LOG_STATVALUES); // A special log entry for the stats
  729. if (stats.serialize(buf))
  730. {
  731. unsigned len = buf.length();
  732. void *ret = output->getBuffer(len, true);
  733. memcpy(ret, buf.toByteArray(), len);
  734. output->putBuffer(ret, len, true);
  735. anyOutput = true;
  736. }
  737. }
  738. ForEachItemIn(idx, log)
  739. {
  740. MemoryBuffer buf;
  741. LogItem &logItem = log.item(idx);
  742. logItem.serialize(buf);
  743. unsigned len = buf.length();
  744. void *ret = output->getBuffer(len, true);
  745. memcpy(ret, buf.toByteArray(), len);
  746. output->putBuffer(ret, len, true);
  747. anyOutput = true;
  748. }
  749. log.kill();
  750. if (anyOutput)
  751. output->flush();
  752. output.clear();
  753. }
  754. }
  755. //=================================================================================
  756. static SpinLock onDemandQueriesCrit;
  757. static MapXToMyClass<hash64_t, hash64_t, IQueryFactory> onDemandQueryCache;
  758. void sendUnloadMessage(hash64_t hash, const char *id, const IRoxieContextLogger &logctx)
  759. {
  760. unsigned packetSize = sizeof(RoxiePacketHeader) + sizeof(char) + strlen(id) + 1;
  761. void *packetData = malloc(packetSize);
  762. RoxiePacketHeader *header = (RoxiePacketHeader *) packetData;
  763. RemoteActivityId unloadId(ROXIE_UNLOAD, hash);
  764. header->init(unloadId, 0, 0, 0);
  765. char *finger = (char *) (header + 1);
  766. *finger++ = (char) LOGGING_FLAGSPRESENT;
  767. strcpy(finger, id);
  768. finger += strlen(id)+1;
  769. if (traceLevel > 1)
  770. DBGLOG("UNLOAD sent for query %s", id);
  771. Owned<IRoxieQueryPacket> packet = createRoxiePacket(packetData, packetSize);
  772. ROQ->sendPacket(packet, logctx);
  773. }
  774. void doUnload(IRoxieQueryPacket *packet, const IRoxieContextLogger &logctx)
  775. {
  776. const RoxiePacketHeader &header = packet->queryHeader();
  777. unsigned channelNo = header.channel;
  778. logctx.CTXLOG("Unload received for channel %d", channelNo);
  779. hash64_t hashValue = header.queryHash;
  780. hashValue = rtlHash64Data(sizeof(channelNo), &channelNo, hashValue);
  781. SpinBlock b(onDemandQueriesCrit);
  782. onDemandQueryCache.remove(hashValue);
  783. }
  784. void cacheOnDemandQuery(hash64_t hashValue, unsigned channelNo, IQueryFactory *query)
  785. {
  786. hashValue = rtlHash64Data(sizeof(channelNo), &channelNo, hashValue);
  787. SpinBlock b(onDemandQueriesCrit);
  788. onDemandQueryCache.setValue(hashValue, query);
  789. }
  790. //=================================================================================
  791. struct PingRecord
  792. {
  793. unsigned tick;
  794. IpAddress senderIP;
  795. };
  796. void doPing(IRoxieQueryPacket *packet, const IRoxieContextLogger &logctx)
  797. {
  798. const RoxiePacketHeader &header = packet->queryHeader();
  799. const IpAddress serverIP = header.serverId.getIpAddress();
  800. unsigned contextLength = packet->getContextLength();
  801. if (contextLength != sizeof(PingRecord))
  802. {
  803. StringBuffer s;
  804. throw MakeStringException(ROXIE_UNKNOWN_SERVER, "Unexpected data size %d (expected %d) in PING: %s", contextLength, (unsigned) sizeof(PingRecord), header.toString(s).str());
  805. }
  806. const PingRecord *data = (const PingRecord *) packet->queryContextData();
  807. if (!serverIP.ipequals(data->senderIP))
  808. {
  809. StringBuffer s;
  810. throw MakeStringException(ROXIE_UNKNOWN_SERVER, "Message received from unknown Roxie server %s", header.toString(s).str());
  811. }
  812. RoxiePacketHeader newHeader(header, ROXIE_PING, 0); // subchannel not relevant
  813. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  814. void *ret = output->getBuffer(contextLength, false);
  815. memcpy(ret, data, contextLength);
  816. output->putBuffer(ret, contextLength, false);
  817. output->flush();
  818. }
  819. //=================================================================================
  820. static ThreadId roxiePacketReaderThread = 0;
  821. class IBYTIbuffer
  822. {
  823. // This class is used to track a finite set of recently-received IBYTI messages, that may have arrived before the messages they refer to
  824. // It is accessed ONLY from the main reader thread and as such does not need to be threadsafe (but does need to be fast).
  825. // We use a circular buffer, and don't bother removing anything (just treat old items as expired). If the buffer overflows we will end up
  826. // discarding the oldest tracked orphaned IBYTI - but that's ok, no worse than if we hadn't tracked them at all.
  827. public:
  828. IBYTIbuffer(unsigned _numOrphans) : numOrphans(_numOrphans)
  829. {
  830. assertex(numOrphans);
  831. orphans = new RoxiePacketHeader[numOrphans];
  832. tail = 0;
  833. }
  834. void noteOrphan(const RoxiePacketHeader &hdr)
  835. {
  836. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  837. unsigned now = msTick();
  838. // We could trace that the buffer may be too small, if (orphans[tail].activityId >= now)
  839. orphans[tail].copy(hdr);
  840. orphans[tail].activityId = now + IBYTIbufferLifetime;
  841. tail++;
  842. if (tail == numOrphans)
  843. tail = 0;
  844. }
  845. bool lookup(const RoxiePacketHeader &hdr) const
  846. {
  847. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  848. unsigned now = msTick();
  849. unsigned lookat = tail;
  850. do
  851. {
  852. if (!lookat)
  853. lookat = numOrphans;
  854. lookat--;
  855. if ((int) (orphans[lookat].activityId - now) < 0) // Watch out for wrapping
  856. break; // expired;
  857. if (orphans[lookat].matchPacket(hdr))
  858. return true;
  859. } while (lookat != tail);
  860. return false;
  861. }
  862. private:
  863. RoxiePacketHeader *orphans = nullptr;
  864. unsigned tail = 0;
  865. unsigned numOrphans = 0;
  866. };
  867. //=================================================================================
  868. //
  869. // RoxieQueue - holds pending transactions on a roxie agent
  870. class RoxieQueue : public CInterface, implements IThreadFactory
  871. {
  872. Owned <IThreadPool> workers;
  873. QueueOf<IRoxieQueryPacket, true> waiting;
  874. Semaphore available;
  875. CriticalSection qcrit;
  876. unsigned headRegionSize;
  877. unsigned numWorkers;
  878. RelaxedAtomic<unsigned> started;
  879. std::atomic<unsigned> idle;
  880. IBYTIbuffer *myIBYTIbuffer = nullptr;
  881. void noteQueued()
  882. {
  883. maxQueueLength.store_max(++queueLength);
  884. // NOTE - there is a small race condition here - if idle is 1 but two enqueue's happen
  885. // close enough together that the signal has not yet caused idle to come back down to zero, then the
  886. // desired new thread may not be created. It's unlikely, and it's benign in that the query is still
  887. // processed and the thread will be created next time the HWM is reached.
  888. if (started < numWorkers && idle==0)
  889. {
  890. workers->start(this);
  891. started++;
  892. }
  893. }
  894. public:
  895. IMPLEMENT_IINTERFACE;
  896. RoxieQueue(unsigned _headRegionSize, unsigned _numWorkers)
  897. {
  898. headRegionSize = _headRegionSize;
  899. numWorkers = _numWorkers;
  900. workers.setown(createThreadPool("RoxieWorkers", this, NULL, numWorkers));
  901. started = 0;
  902. idle = 0;
  903. if (IBYTIbufferSize)
  904. myIBYTIbuffer = new IBYTIbuffer(IBYTIbufferSize);
  905. }
  906. ~RoxieQueue()
  907. {
  908. delete myIBYTIbuffer;
  909. }
  910. virtual IPooledThread *createNew();
  911. void abortChannel(unsigned channel);
  912. void start()
  913. {
  914. if (prestartAgentThreads)
  915. {
  916. while (started < numWorkers)
  917. {
  918. workers->start(this);
  919. started++;
  920. }
  921. }
  922. }
  923. IPooledThreadIterator *running()
  924. {
  925. return workers->running();
  926. }
  927. void stopAll()
  928. {
  929. workers->stopAll(true);
  930. signal(workers->runningCount());
  931. }
  932. void join()
  933. {
  934. workers->joinAll(true);
  935. workers.clear(); // Breaks a cyclic reference count that would stop us from releasing RoxieReceiverThread otherwise
  936. }
  937. void enqueue(IRoxieQueryPacket *x)
  938. {
  939. {
  940. #ifdef TIME_PACKETS
  941. x->queryHeader().tick = msTick();
  942. #endif
  943. CriticalBlock qc(qcrit);
  944. waiting.enqueue(x);
  945. noteQueued();
  946. }
  947. available.signal();
  948. }
  949. void enqueueUnique(IRoxieQueryPacket *x, unsigned subChannel)
  950. {
  951. RoxiePacketHeader &header = x->queryHeader();
  952. #ifdef TIME_PACKETS
  953. header.tick = msTick();
  954. #endif
  955. bool found = false;
  956. {
  957. CriticalBlock qc(qcrit);
  958. unsigned len = waiting.ordinality();
  959. unsigned i;
  960. for (i = 0; i < len; i++)
  961. {
  962. IRoxieQueryPacket *queued = waiting.item(i);
  963. if (queued && queued->queryHeader().matchPacket(header))
  964. {
  965. found = true;
  966. break;
  967. }
  968. }
  969. if (!found)
  970. waiting.enqueue(x);
  971. }
  972. if (found)
  973. {
  974. if (traceLevel > 0)
  975. {
  976. StringBuffer xx;
  977. AgentContextLogger l(x);
  978. l.CTXLOG("Ignored retry on subchannel %u for queued activity %s", subChannel, header.toString(xx).str());
  979. }
  980. if (!subChannel)
  981. retriesIgnoredPrm++;
  982. else
  983. retriesIgnoredSec++;
  984. x->Release();
  985. }
  986. else
  987. {
  988. available.signal();
  989. noteQueued();
  990. if (traceLevel > 10)
  991. {
  992. AgentContextLogger l(x);
  993. StringBuffer xx;
  994. l.CTXLOG("enqueued %s", header.toString(xx).str());
  995. }
  996. }
  997. }
  998. bool remove(RoxiePacketHeader &x)
  999. {
  1000. unsigned scanLength = 0;
  1001. IRoxieQueryPacket *found = nullptr;
  1002. {
  1003. CriticalBlock qc(qcrit);
  1004. unsigned len = waiting.ordinality();
  1005. unsigned i;
  1006. for (i = 0; i < len; i++)
  1007. {
  1008. IRoxieQueryPacket *queued = waiting.item(i);
  1009. if (queued)
  1010. {
  1011. scanLength++;
  1012. if (queued->queryHeader().matchPacket(x))
  1013. {
  1014. waiting.set(i, NULL);
  1015. found = queued;
  1016. break;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. if (found)
  1022. {
  1023. #ifdef _DEBUG
  1024. RoxiePacketHeader &header = found->queryHeader();
  1025. AgentContextLogger l(found);
  1026. StringBuffer xx;
  1027. l.CTXLOG("discarded %s", header.toString(xx).str());
  1028. #endif
  1029. found->Release();
  1030. queueLength--;
  1031. if (scanLength > maxScanLength)
  1032. maxScanLength = scanLength;
  1033. totScanLength += scanLength;
  1034. totScans++;
  1035. return true;
  1036. }
  1037. else
  1038. return false;
  1039. }
  1040. void wait()
  1041. {
  1042. idle++;
  1043. available.wait();
  1044. idle--;
  1045. }
  1046. void signal(unsigned num)
  1047. {
  1048. available.signal(num);
  1049. }
  1050. IRoxieQueryPacket *dequeue()
  1051. {
  1052. CriticalBlock qc(qcrit);
  1053. unsigned lim = waiting.ordinality();
  1054. if (lim)
  1055. {
  1056. if (headRegionSize)
  1057. {
  1058. if (lim > headRegionSize)
  1059. lim = headRegionSize;
  1060. return waiting.dequeue(fastRand() % lim);
  1061. }
  1062. return waiting.dequeue();
  1063. }
  1064. else
  1065. return NULL;
  1066. }
  1067. unsigned getHeadRegionSize() const
  1068. {
  1069. return headRegionSize;
  1070. }
  1071. unsigned setHeadRegionSize(unsigned newsize)
  1072. {
  1073. unsigned ret = headRegionSize;
  1074. headRegionSize = newsize;
  1075. return ret;
  1076. }
  1077. void noteOrphanIBYTI(const RoxiePacketHeader &hdr)
  1078. {
  1079. if (myIBYTIbuffer)
  1080. myIBYTIbuffer->noteOrphan(hdr);
  1081. }
  1082. bool lookupOrphanIBYTI(const RoxiePacketHeader &hdr) const
  1083. {
  1084. if (myIBYTIbuffer)
  1085. return myIBYTIbuffer->lookup(hdr);
  1086. else
  1087. return false;
  1088. }
  1089. };
  1090. class CRoxieWorker : public CInterface, implements IPooledThread
  1091. {
  1092. RoxieQueue *queue;
  1093. CriticalSection actCrit;
  1094. Semaphore ibytiSem;
  1095. bool stopped;
  1096. bool abortJob;
  1097. bool busy;
  1098. Owned<IRoxieAgentActivity> activity;
  1099. Owned<IRoxieQueryPacket> packet;
  1100. Owned<const ITopologyServer> topology;
  1101. AgentContextLogger logctx;
  1102. public:
  1103. IMPLEMENT_IINTERFACE;
  1104. CRoxieWorker()
  1105. {
  1106. queue = NULL;
  1107. stopped = false;
  1108. busy = false;
  1109. abortJob = false;
  1110. }
  1111. virtual void init(void *_r) override
  1112. {
  1113. queue = (RoxieQueue *) _r;
  1114. stopped = false;
  1115. busy = false;
  1116. abortJob = false;
  1117. }
  1118. virtual bool canReuse() const override
  1119. {
  1120. return true;
  1121. }
  1122. virtual bool stop() override
  1123. {
  1124. stopped = true;
  1125. return true;
  1126. }
  1127. inline void setActivity(IRoxieAgentActivity *act)
  1128. {
  1129. CriticalBlock b(actCrit);
  1130. activity.setown(act);
  1131. }
  1132. inline bool match(RoxiePacketHeader &h)
  1133. {
  1134. // There is a window between getting packet from queue and being able to match it.
  1135. // This could cause some deduping to fail, but it does not matter if it does (so long as it is rare!)
  1136. CriticalBlock b(actCrit);
  1137. return packet && packet->queryHeader().matchPacket(h);
  1138. }
  1139. void abortChannel(unsigned channel)
  1140. {
  1141. CriticalBlock b(actCrit);
  1142. if (packet && packet->queryHeader().channel==channel)
  1143. {
  1144. abortJob = true;
  1145. if (doIbytiDelay)
  1146. ibytiSem.signal();
  1147. if (activity)
  1148. activity->abort();
  1149. }
  1150. }
  1151. bool checkAbort(RoxiePacketHeader &h, bool checkRank, bool &queryFound, bool &preActivity)
  1152. {
  1153. CriticalBlock b(actCrit);
  1154. if (packet && packet->queryHeader().matchPacket(h))
  1155. {
  1156. queryFound = true;
  1157. abortJob = true;
  1158. if (doIbytiDelay)
  1159. ibytiSem.signal();
  1160. if (activity)
  1161. {
  1162. // Try to stop/abort a job after it starts only if IBYTI comes from a higher priority agent
  1163. // (more primary in the rank). The agents with higher rank will hold the lower bits of the retries field in IBYTI packet).
  1164. #ifdef SUBCHANNELS_IN_HEADER
  1165. if (!checkRank || h.getRespondingSubChannel() < h.mySubChannel())
  1166. #else
  1167. if (!checkRank || topology->queryChannelInfo(h.channel).otherAgentHasPriority(h.priorityHash(), h.getRespondingSubChannel()))
  1168. #endif
  1169. {
  1170. activity->abort();
  1171. return true;
  1172. }
  1173. else
  1174. {
  1175. return false;
  1176. }
  1177. }
  1178. if (busy)
  1179. {
  1180. preActivity = true;
  1181. return true;
  1182. }
  1183. }
  1184. return false;
  1185. }
  1186. void throwRemoteException(IException *E, IRoxieAgentActivity *activity, IRoxieQueryPacket *packet, bool isUser)
  1187. {
  1188. try
  1189. {
  1190. if (activity && (logctx.queryTraceLevel() > 1))
  1191. {
  1192. StringBuffer act;
  1193. activity->toString(act);
  1194. logctx.CTXLOG("throwRemoteException, activity %s, isUser=%d", act.str(), (int) isUser);
  1195. if (!isUser)
  1196. EXCLOG(E, "throwRemoteException");
  1197. }
  1198. RoxiePacketHeader &header = packet->queryHeader();
  1199. #ifdef SUBCHANNELS_IN_HEADER
  1200. unsigned mySubChannel = header.mySubChannel();
  1201. #else
  1202. unsigned mySubChannel = topology->queryChannelInfo(header.channel).subChannel();
  1203. #endif
  1204. // I failed to do the query, but already sent out IBYTI - resend it so someone else can try
  1205. if (!isUser)
  1206. {
  1207. StringBuffer s;
  1208. s.append("Exception in agent for packet ");
  1209. header.toString(s);
  1210. logctx.logOperatorException(E, NULL, 0, "%s", s.str());
  1211. header.setException(mySubChannel);
  1212. if (!header.allChannelsFailed() && !localAgent)
  1213. {
  1214. if (logctx.queryTraceLevel() > 1)
  1215. logctx.CTXLOG("resending packet from agent in case others want to try it");
  1216. ROQ->sendPacket(packet, logctx);
  1217. }
  1218. }
  1219. RoxiePacketHeader newHeader(header, ROXIE_EXCEPTION, mySubChannel);
  1220. if (isUser)
  1221. newHeader.retries = (unsigned short) -1;
  1222. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  1223. StringBuffer message("<Exception>");
  1224. message.appendf("<Code>%d</Code><Message>", E->errorCode());
  1225. StringBuffer err;
  1226. E->errorMessage(err);
  1227. encodeXML(err.str(), message);
  1228. message.append("</Message></Exception>");
  1229. unsigned len = message.length();
  1230. void *ret = output->getBuffer(len+1, true);
  1231. memcpy(ret, message.str(), len+1);
  1232. output->putBuffer(ret, len+1, true);
  1233. output->flush();
  1234. E->Release();
  1235. }
  1236. catch (IException *EInE)
  1237. {
  1238. EXCLOG(EInE, "Exception during throwRemoteException");
  1239. E->Release();
  1240. EInE->Release();
  1241. }
  1242. catch (...)
  1243. {
  1244. logctx.CTXLOG("Unknown Exception during throwRemoteException");
  1245. E->Release();
  1246. }
  1247. }
  1248. void doActivity()
  1249. {
  1250. RoxiePacketHeader &header = packet->queryHeader();
  1251. unsigned channel = header.channel;
  1252. hash64_t queryHash = packet->queryHeader().queryHash;
  1253. unsigned activityId = packet->queryHeader().activityId & ~ROXIE_PRIORITY_MASK;
  1254. Owned<IQueryFactory> queryFactory = getQueryFactory(queryHash, channel);
  1255. #ifdef SUBCHANNELS_IN_HEADER
  1256. unsigned mySubChannel = header.mySubChannel();
  1257. #else
  1258. unsigned numAgents = topology->queryAgents(channel).ordinality();
  1259. unsigned mySubChannel = topology->queryChannelInfo(channel).subChannel();
  1260. #endif
  1261. if (!queryFactory && logctx.queryWuid())
  1262. {
  1263. Owned <IRoxieDaliHelper> daliHelper = connectToDali();
  1264. Owned<IConstWorkUnit> wu = daliHelper->attachWorkunit(logctx.queryWuid(), NULL);
  1265. queryFactory.setown(createAgentQueryFactoryFromWu(wu, channel));
  1266. if (queryFactory)
  1267. cacheOnDemandQuery(queryHash, channel, queryFactory);
  1268. }
  1269. if (!queryFactory)
  1270. {
  1271. StringBuffer hdr;
  1272. IException *E = MakeStringException(MSGAUD_operator, ROXIE_UNKNOWN_QUERY, "Roxie agent received request for unregistered query: %s", packet->queryHeader().toString(hdr).str());
  1273. EXCLOG(E, "doActivity");
  1274. throwRemoteException(E, activity, packet, false);
  1275. return;
  1276. }
  1277. try
  1278. {
  1279. bool debugging = logctx.queryDebuggerActive();
  1280. #ifdef SUBCHANNELS_IN_HEADER
  1281. if (debugging)
  1282. {
  1283. if (!mySubChannel)
  1284. abortJob = true; // when debugging, we always run on primary only... should really have sent to primary only too...
  1285. }
  1286. else if (doIbytiDelay && mySubChannel)
  1287. {
  1288. unsigned delay = 0;
  1289. for (unsigned subChannel = 0; subChannel < mySubChannel; subChannel++)
  1290. delay += getIbytiDelay(header.subChannels[subChannel].getIpAddress());
  1291. unsigned start;
  1292. if (traceRoxiePackets)
  1293. {
  1294. StringBuffer x;
  1295. DBGLOG("YES myTurnToDelay subchannel=%u delay=%u %s", mySubChannel, delay, header.toString(x).str());
  1296. start = msTick();
  1297. }
  1298. if (delay)
  1299. ibytiSem.wait(delay);
  1300. if (traceRoxiePackets)
  1301. {
  1302. StringBuffer x;
  1303. DBGLOG("Delay done, abortJob=%d, elapsed=%d", (int) abortJob, msTick()-start);
  1304. }
  1305. if (!abortJob)
  1306. {
  1307. for (unsigned subChannel = 0; subChannel < mySubChannel; subChannel++)
  1308. noteNodeSick(header.subChannels[subChannel].getIpAddress());
  1309. }
  1310. }
  1311. #else
  1312. if (debugging)
  1313. {
  1314. if (mySubChannel)
  1315. abortJob = true; // when debugging, we always run on primary only...
  1316. }
  1317. else if (doIbytiDelay && (numAgents > 1))
  1318. {
  1319. unsigned hdrHashVal = header.priorityHash();
  1320. unsigned primarySubChannel = (hdrHashVal % numAgents);
  1321. if (primarySubChannel != mySubChannel)
  1322. {
  1323. unsigned delay = topology->queryChannelInfo(channel).getIbytiDelay(primarySubChannel);
  1324. if (logctx.queryTraceLevel() > 6)
  1325. {
  1326. StringBuffer x;
  1327. logctx.CTXLOG("YES myTurnToDelayIBYTI subchannel=%u delay=%u hash=%u %s", mySubChannel, delay, hdrHashVal, header.toString(x).str());
  1328. }
  1329. // MORE: if we are dealing with a query that was on channel 0, we may want a longer delay
  1330. // (since the theory about duplicated work not mattering when cluster is idle does not hold up)
  1331. if (delay)
  1332. {
  1333. ibytiSem.wait(delay);
  1334. if (!abortJob)
  1335. topology->queryChannelInfo(channel).noteChannelsSick(primarySubChannel);
  1336. if (logctx.queryTraceLevel() > 8)
  1337. {
  1338. StringBuffer x;
  1339. logctx.CTXLOG("Buddy did%s send IBYTI, updated delay : %s",
  1340. abortJob ? "" : " NOT", header.toString(x).str());
  1341. }
  1342. }
  1343. }
  1344. else
  1345. {
  1346. #ifndef NO_IBYTI_DELAYS_COUNT
  1347. if (!mySubChannel)
  1348. ibytiNoDelaysPrm++;
  1349. else
  1350. ibytiNoDelaysSec++;
  1351. #endif
  1352. if (logctx.queryTraceLevel() > 6)
  1353. {
  1354. StringBuffer x;
  1355. logctx.CTXLOG("NOT myTurnToDelayIBYTI subchannel=%u hash=%u %s", mySubChannel, hdrHashVal, header.toString(x).str());
  1356. }
  1357. }
  1358. }
  1359. #endif
  1360. if (abortJob)
  1361. {
  1362. CriticalBlock b(actCrit);
  1363. busy = false; // Keep order - before setActivity below
  1364. if (logctx.queryTraceLevel() > 5)
  1365. {
  1366. StringBuffer x;
  1367. logctx.CTXLOG("Stop before processing - activity aborted %s", header.toString(x).str());
  1368. }
  1369. return;
  1370. }
  1371. if (!debugging)
  1372. ROQ->sendIbyti(header, logctx, mySubChannel);
  1373. activitiesStarted++;
  1374. Owned <IAgentActivityFactory> factory = queryFactory->getAgentActivityFactory(activityId);
  1375. assertex(factory);
  1376. setActivity(factory->createActivity(logctx, packet));
  1377. Owned<IMessagePacker> output = activity->process();
  1378. if (logctx.queryTraceLevel() > 5)
  1379. {
  1380. StringBuffer x;
  1381. logctx.CTXLOG("done processing %s", header.toString(x).str());
  1382. }
  1383. if (output)
  1384. {
  1385. activitiesCompleted++;
  1386. busy = false; // Keep order - before setActivity below
  1387. setActivity(NULL); // Ensures all stats are merged from child queries etc
  1388. logctx.flush();
  1389. output->flush();
  1390. }
  1391. }
  1392. catch (IUserException *E)
  1393. {
  1394. throwRemoteException(E, activity, packet, true);
  1395. }
  1396. catch (IException *E)
  1397. {
  1398. if (E->errorCode()!=ROXIE_ABORT_ERROR)
  1399. throwRemoteException(E, activity, packet, false);
  1400. else
  1401. E->Release();
  1402. }
  1403. catch (...)
  1404. {
  1405. throwRemoteException(MakeStringException(ROXIE_MULTICAST_ERROR, "Unknown exception"), activity, packet, false);
  1406. }
  1407. busy = false; // Keep order - before setActivity below
  1408. setActivity(NULL);
  1409. }
  1410. virtual void threadmain() override
  1411. {
  1412. while (!stopped)
  1413. {
  1414. try
  1415. {
  1416. for (;;)
  1417. {
  1418. queue->wait();
  1419. if (stopped)
  1420. break;
  1421. agentsActive++;
  1422. maxAgentsActive.store_max(agentsActive);
  1423. abortJob = false;
  1424. busy = true;
  1425. if (doIbytiDelay)
  1426. ibytiSem.reinit(0U); // Make sure sem is is in no-signaled state
  1427. packet.setown(queue->dequeue());
  1428. if (packet)
  1429. {
  1430. queueLength--;
  1431. RoxiePacketHeader &header = packet->queryHeader();
  1432. logctx.set(packet);
  1433. #ifdef TIME_PACKETS
  1434. {
  1435. unsigned now = msTick();
  1436. unsigned packetWait = now-header.tick;
  1437. header.tick = now;
  1438. packetWaitMax.store_max(packetWait);
  1439. packetWaitElapsed += packetWait;
  1440. packetWaitCount++;
  1441. }
  1442. #endif
  1443. topology.setown(getTopology());
  1444. if (logctx.queryTraceLevel() > 10)
  1445. {
  1446. StringBuffer x;
  1447. logctx.CTXLOG("dequeued %s", header.toString(x).str());
  1448. }
  1449. if ((header.activityId & ~ROXIE_PRIORITY_MASK) == ROXIE_UNLOAD)
  1450. {
  1451. doUnload(packet, logctx);
  1452. }
  1453. else if ((header.activityId & ~ROXIE_PRIORITY_MASK) == ROXIE_PING)
  1454. {
  1455. doPing(packet, logctx);
  1456. }
  1457. else if ((header.activityId & ~ROXIE_PRIORITY_MASK) == ROXIE_DEBUGREQUEST)
  1458. {
  1459. // MORE - we need to make sure only executed on primary, and that the proxyId (== pointer to DebugGraphManager) is still valid.
  1460. // It may be that there is not a lot of point using the pointer - may as well use an non-reused ID and look it up in a global hash table of active ones
  1461. doDebugRequest(packet, logctx);
  1462. }
  1463. else if (header.channel)
  1464. doActivity();
  1465. else
  1466. throwUnexpected(); // channel 0 requests translated earlier now
  1467. #ifdef TIME_PACKETS
  1468. {
  1469. unsigned now = msTick();
  1470. unsigned packetRun = now-header.tick;
  1471. packetRunMax.store_max(packetRun);
  1472. packetRunElapsed += packetRun;
  1473. packetRunCount++;
  1474. }
  1475. #endif
  1476. }
  1477. busy = false;
  1478. {
  1479. CriticalBlock b(actCrit);
  1480. packet.clear();
  1481. topology.clear();
  1482. logctx.set(NULL);
  1483. }
  1484. agentsActive--;
  1485. }
  1486. }
  1487. catch(IException *E)
  1488. {
  1489. CriticalBlock b(actCrit);
  1490. EXCLOG(E);
  1491. if (packet)
  1492. {
  1493. throwRemoteException(E, NULL, packet, false);
  1494. packet.clear();
  1495. }
  1496. else
  1497. E->Release();
  1498. topology.clear();
  1499. }
  1500. catch(...)
  1501. {
  1502. CriticalBlock b(actCrit);
  1503. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception in Roxie worker thread");
  1504. EXCLOG(E);
  1505. if (packet)
  1506. {
  1507. throwRemoteException(E.getClear(), NULL, packet, false);
  1508. packet.clear();
  1509. }
  1510. topology.clear();
  1511. }
  1512. }
  1513. }
  1514. };
  1515. IPooledThread *RoxieQueue::createNew()
  1516. {
  1517. return new CRoxieWorker;
  1518. }
  1519. void RoxieQueue::abortChannel(unsigned channel)
  1520. {
  1521. Owned<IPooledThreadIterator> wi = workers->running();
  1522. ForEach(*wi)
  1523. {
  1524. CRoxieWorker &w = (CRoxieWorker &) wi->query();
  1525. w.abortChannel(channel);
  1526. }
  1527. }
  1528. //=================================================================================
  1529. class CallbackEntry : implements IPendingCallback, public CInterface
  1530. {
  1531. const RoxiePacketHeader &header;
  1532. StringAttr lfn;
  1533. InterruptableSemaphore ready;
  1534. MemoryBuffer data;
  1535. bool gotData;
  1536. public:
  1537. IMPLEMENT_IINTERFACE;
  1538. CallbackEntry(const RoxiePacketHeader &_header, const char *_lfn) : header(_header), lfn(_lfn)
  1539. {
  1540. gotData = false;
  1541. }
  1542. virtual bool wait(unsigned msecs)
  1543. {
  1544. return ready.wait(msecs);
  1545. }
  1546. virtual MemoryBuffer &queryData()
  1547. {
  1548. return data;
  1549. }
  1550. bool matches(RoxiePacketHeader &cand, const char *_lfn)
  1551. {
  1552. return (cand.matchPacket(header) && (!_lfn|| stricmp(_lfn, lfn)==0));
  1553. }
  1554. void doFileCallback(unsigned _len, const void *_data, bool aborted)
  1555. {
  1556. // MORE - make sure we call this for whole query abort as well as for callback abort
  1557. if (aborted)
  1558. ready.interrupt(MakeStringException(0, "Interrupted"));
  1559. else if (!gotData)
  1560. {
  1561. gotData = true;
  1562. data.append(_len, _data);
  1563. ready.signal();
  1564. }
  1565. }
  1566. };
  1567. class RoxieReceiverBase : implements IRoxieOutputQueueManager, public CInterface
  1568. {
  1569. protected:
  1570. #ifdef ROXIE_SLA_LOGIC
  1571. RoxieQueue slaQueue;
  1572. #endif
  1573. RoxieQueue hiQueue;
  1574. RoxieQueue loQueue;
  1575. unsigned numWorkers;
  1576. public:
  1577. IMPLEMENT_IINTERFACE;
  1578. #ifdef ROXIE_SLA_LOGIC
  1579. RoxieReceiverBase(unsigned _numWorkers) : slaQueue(headRegionSize, _numWorkers), hiQueue(headRegionSize, _numWorkers), loQueue(headRegionSize, _numWorkers), numWorkers(_numWorkers)
  1580. #else
  1581. RoxieReceiverBase(unsigned _numWorkers) : hiQueue(headRegionSize, _numWorkers), loQueue(headRegionSize, _numWorkers), numWorkers(_numWorkers)
  1582. #endif
  1583. {
  1584. }
  1585. virtual unsigned getHeadRegionSize() const
  1586. {
  1587. return loQueue.getHeadRegionSize();
  1588. }
  1589. virtual void setHeadRegionSize(unsigned newSize)
  1590. {
  1591. #ifdef ROXIE_SLA_LOGIC
  1592. slaQueue.setHeadRegionSize(newSize);
  1593. #endif
  1594. hiQueue.setHeadRegionSize(newSize);
  1595. loQueue.setHeadRegionSize(newSize);
  1596. }
  1597. virtual void start()
  1598. {
  1599. loQueue.start();
  1600. hiQueue.start();
  1601. #ifdef ROXIE_SLA_LOGIC
  1602. slaQueue.start();
  1603. #endif
  1604. }
  1605. virtual void stop()
  1606. {
  1607. loQueue.stopAll();
  1608. hiQueue.stopAll();
  1609. #ifdef ROXIE_SLA_LOGIC
  1610. slaQueue.stopAll();
  1611. #endif
  1612. }
  1613. virtual void join()
  1614. {
  1615. loQueue.join();
  1616. hiQueue.join();
  1617. #ifdef ROXIE_SLA_LOGIC
  1618. slaQueue.join();
  1619. #endif
  1620. }
  1621. IArrayOf<CallbackEntry> callbacks;
  1622. CriticalSection callbacksCrit;
  1623. virtual IPendingCallback *notePendingCallback(const RoxiePacketHeader &header, const char *lfn)
  1624. {
  1625. CriticalBlock b(callbacksCrit);
  1626. CallbackEntry *callback = new CallbackEntry(header, lfn);
  1627. callbacks.append(*callback);
  1628. return callback;
  1629. }
  1630. virtual void removePendingCallback(IPendingCallback *goer)
  1631. {
  1632. if (goer)
  1633. {
  1634. CriticalBlock b(callbacksCrit);
  1635. callbacks.zap(static_cast<CallbackEntry &>(*goer));
  1636. }
  1637. }
  1638. protected:
  1639. void doFileCallback(IRoxieQueryPacket *packet)
  1640. {
  1641. // This is called on the main agent reader thread so needs to be as fast as possible to avoid lost packets
  1642. const char *lfn;
  1643. const char *data;
  1644. unsigned len;
  1645. RoxiePacketHeader &header = packet->queryHeader();
  1646. if (header.activityId == ROXIE_FILECALLBACK || header.activityId == ROXIE_DEBUGCALLBACK)
  1647. {
  1648. lfn = (const char *) packet->queryContextData();
  1649. unsigned namelen = strlen(lfn) + 1;
  1650. data = lfn + namelen;
  1651. len = packet->getContextLength() - namelen;
  1652. }
  1653. else
  1654. {
  1655. lfn = data = NULL; // used when query aborted
  1656. len = 0;
  1657. }
  1658. CriticalBlock b(callbacksCrit);
  1659. ForEachItemIn(idx, callbacks)
  1660. {
  1661. CallbackEntry &c = callbacks.item(idx);
  1662. if (c.matches(header, lfn))
  1663. {
  1664. if (traceLevel > 10)
  1665. DBGLOG("callback return matched a waiting query");
  1666. c.doFileCallback(len, data, header.retries==QUERY_ABORTED);
  1667. }
  1668. }
  1669. }
  1670. };
  1671. #ifdef _MSC_VER
  1672. #pragma warning ( push )
  1673. #pragma warning ( disable: 4355 )
  1674. #endif
  1675. class RoxieThrottledPacketSender : public Thread
  1676. {
  1677. TokenBucket &bucket;
  1678. InterruptableSemaphore queued;
  1679. Semaphore started;
  1680. unsigned maxPacketSize;
  1681. SafeQueueOf<IRoxieQueryPacket, false> queue;
  1682. class DECL_EXCEPTION StoppedException: public IException, public CInterface
  1683. {
  1684. public:
  1685. IMPLEMENT_IINTERFACE;
  1686. int errorCode() const { return 0; }
  1687. StringBuffer & errorMessage(StringBuffer &str) const { return str.append("Stopped"); }
  1688. MessageAudience errorAudience() const { return MSGAUD_user; }
  1689. };
  1690. void enqueue(IRoxieQueryPacket *packet)
  1691. {
  1692. packet->Link();
  1693. queue.enqueue(packet);
  1694. queued.signal();
  1695. }
  1696. IRoxieQueryPacket *dequeue()
  1697. {
  1698. queued.wait();
  1699. return queue.dequeue();
  1700. }
  1701. public:
  1702. RoxieThrottledPacketSender(TokenBucket &_bucket, unsigned _maxPacketSize)
  1703. : Thread("RoxieThrottledPacketSender"), bucket(_bucket), maxPacketSize(_maxPacketSize)
  1704. {
  1705. start();
  1706. started.wait();
  1707. }
  1708. ~RoxieThrottledPacketSender()
  1709. {
  1710. stop();
  1711. join();
  1712. }
  1713. virtual int run()
  1714. {
  1715. started.signal();
  1716. for (;;)
  1717. {
  1718. try
  1719. {
  1720. Owned<IRoxieQueryPacket> packet = dequeue();
  1721. RoxiePacketHeader &header = packet->queryHeader();
  1722. unsigned length = packet->queryHeader().packetlength;
  1723. {
  1724. MTIME_SECTION(queryActiveTimer(), "bucket_wait");
  1725. bucket.wait((length / 1024) + 1);
  1726. }
  1727. if (!channelWrite(header, true))
  1728. DBGLOG("Roxie packet write wrote too little");
  1729. packetsSent++;
  1730. }
  1731. catch (StoppedException *E)
  1732. {
  1733. E->Release();
  1734. break;
  1735. }
  1736. catch (IException *E)
  1737. {
  1738. EXCLOG(E);
  1739. E->Release();
  1740. }
  1741. catch (...)
  1742. {
  1743. }
  1744. }
  1745. return 0;
  1746. }
  1747. virtual void sendPacket(IRoxieQueryPacket *x, const IRoxieContextLogger &logctx)
  1748. {
  1749. RoxiePacketHeader &header = x->queryHeader();
  1750. unsigned length = x->queryHeader().packetlength;
  1751. assertex (header.activityId & ~ROXIE_PRIORITY_MASK);
  1752. switch (header.retries & ROXIE_RETRIES_MASK)
  1753. {
  1754. case (QUERY_ABORTED & ROXIE_RETRIES_MASK):
  1755. {
  1756. StringBuffer s;
  1757. logctx.CTXLOG("Aborting packet size=%d: %s", length, header.toString(s).str());
  1758. }
  1759. break;
  1760. default:
  1761. {
  1762. StringBuffer s;
  1763. logctx.CTXLOG("Resending packet size=%d: %s", length, header.toString(s).str());
  1764. }
  1765. break;
  1766. case 0:
  1767. if (logctx.queryTraceLevel() > 8)
  1768. {
  1769. StringBuffer s;
  1770. logctx.CTXLOG("Sending packet size=%d: %s", length, header.toString(s).str());
  1771. }
  1772. break;
  1773. }
  1774. if (length > maxPacketSize)
  1775. {
  1776. StringBuffer s;
  1777. throw MakeStringException(ROXIE_PACKET_ERROR, "Maximum packet length %d exceeded sending packet %s", maxPacketSize, header.toString(s).str());
  1778. }
  1779. enqueue(x);
  1780. }
  1781. void stop()
  1782. {
  1783. // bucket.stop();
  1784. queued.interrupt(new StoppedException);
  1785. }
  1786. };
  1787. class RoxieSocketQueueManager : public RoxieReceiverBase
  1788. {
  1789. protected:
  1790. Linked<ISendManager> sendManager;
  1791. Linked<IReceiveManager> receiveManager;
  1792. Owned<RoxieThrottledPacketSender> throttledPacketSendManager;
  1793. Owned<TokenBucket> bucket;
  1794. unsigned maxPacketSize = 0;
  1795. std::atomic<bool> running = { false };
  1796. class ReceiverThread : public Thread
  1797. {
  1798. RoxieSocketQueueManager &parent;
  1799. public:
  1800. ReceiverThread(RoxieSocketQueueManager &_parent) : Thread("RoxieSocketQueueManager"), parent(_parent) {}
  1801. int run()
  1802. {
  1803. // Raise the priority so ibyti's get through in a timely fashion
  1804. #if defined( __linux__) || defined(__APPLE__)
  1805. setLinuxThreadPriority(3);
  1806. #else
  1807. adjustPriority(1);
  1808. #endif
  1809. roxiePacketReaderThread = GetCurrentThreadId();
  1810. return parent.run();
  1811. }
  1812. } readThread;
  1813. public:
  1814. RoxieSocketQueueManager(unsigned _numWorkers) : RoxieReceiverBase(_numWorkers), readThread(*this)
  1815. {
  1816. maxPacketSize = multicastSocket->get_max_send_size();
  1817. if ((maxPacketSize==0)||(maxPacketSize>65535))
  1818. maxPacketSize = 65535;
  1819. }
  1820. virtual void sendPacket(IRoxieQueryPacket *x, const IRoxieContextLogger &logctx)
  1821. {
  1822. if (throttledPacketSendManager)
  1823. throttledPacketSendManager->sendPacket(x, logctx);
  1824. else
  1825. {
  1826. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendPacket");
  1827. RoxiePacketHeader &header = x->queryHeader();
  1828. unsigned length = x->queryHeader().packetlength;
  1829. assertex (header.activityId & ~ROXIE_PRIORITY_MASK);
  1830. StringBuffer s;
  1831. switch (header.retries & ROXIE_RETRIES_MASK)
  1832. {
  1833. case (QUERY_ABORTED & ROXIE_RETRIES_MASK):
  1834. logctx.CTXLOG("Aborting packet size=%d: %s", length, header.toString(s).str());
  1835. break;
  1836. default:
  1837. logctx.CTXLOG("Resending packet size=%d: %s", length, header.toString(s).str());
  1838. break;
  1839. case 0:
  1840. if (logctx.queryTraceLevel() > 8)
  1841. logctx.CTXLOG("Sending packet size=%d: %s", length, header.toString(s).str());
  1842. break;
  1843. }
  1844. if (length > maxPacketSize)
  1845. {
  1846. StringBuffer s;
  1847. throw MakeStringException(ROXIE_PACKET_ERROR, "Maximum packet length %d exceeded sending packet %s", maxPacketSize, header.toString(s).str());
  1848. }
  1849. if (!channelWrite(header, true))
  1850. logctx.CTXLOG("Roxie packet write wrote too little");
  1851. packetsSent++;
  1852. }
  1853. }
  1854. virtual void sendIbyti(RoxiePacketHeader &header, const IRoxieContextLogger &logctx, unsigned subChannel) override
  1855. {
  1856. #ifdef SUBCHANNELS_IN_HEADER
  1857. if (!header.hasBuddies())
  1858. return;
  1859. #endif
  1860. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendIbyti");
  1861. RoxiePacketHeader ibytiHeader(header, header.activityId & ROXIE_PRIORITY_MASK, subChannel);
  1862. if (logctx.queryTraceLevel() > 8)
  1863. {
  1864. StringBuffer s; logctx.CTXLOG("Sending IBYTI packet %s", ibytiHeader.toString(s).str());
  1865. }
  1866. channelWrite(ibytiHeader, false); // don't send to self
  1867. ibytiPacketsSent++;
  1868. }
  1869. virtual void sendAbort(RoxiePacketHeader &header, const IRoxieContextLogger &logctx) override
  1870. {
  1871. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendAbort");
  1872. RoxiePacketHeader abortHeader(header, header.activityId & ROXIE_PRIORITY_MASK, 0); // subChannel irrelevant - we are about to overwrite retries anyway
  1873. abortHeader.retries = QUERY_ABORTED;
  1874. if (logctx.queryTraceLevel() > 8)
  1875. {
  1876. StringBuffer s; logctx.CTXLOG("Sending ABORT packet %s", abortHeader.toString(s).str());
  1877. }
  1878. if (!channelWrite(abortHeader, true))
  1879. logctx.CTXLOG("sendAbort wrote too little");
  1880. abortsSent++;
  1881. }
  1882. virtual void sendAbortCallback(const RoxiePacketHeader &header, const char *lfn, const IRoxieContextLogger &logctx) override
  1883. {
  1884. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendAbortCallback");
  1885. RoxiePacketHeader abortHeader(header, ROXIE_FILECALLBACK, 0); // subChannel irrelevant - we are about to overwrite retries anyway
  1886. abortHeader.retries = QUERY_ABORTED;
  1887. abortHeader.packetlength += strlen(lfn)+1;
  1888. MemoryBuffer data;
  1889. data.append(sizeof(abortHeader), &abortHeader).append(lfn);
  1890. if (logctx.queryTraceLevel() > 5)
  1891. {
  1892. StringBuffer s; logctx.CTXLOG("Sending ABORT FILECALLBACK packet %s for file %s", abortHeader.toString(s).str(), lfn);
  1893. }
  1894. if (!channelWrite(*(RoxiePacketHeader *) data.toByteArray(), true))
  1895. logctx.CTXLOG("sendAbortCallback wrote too little");
  1896. abortsSent++;
  1897. }
  1898. virtual IMessagePacker *createOutputStream(RoxiePacketHeader &header, bool outOfBand, const IRoxieContextLogger &logctx)
  1899. {
  1900. unsigned qnum = outOfBand ? 0 : ((header.retries & ROXIE_FASTLANE) || !fastLaneQueue) ? 1 : 2;
  1901. if (logctx.queryTraceLevel() > 8)
  1902. {
  1903. StringBuffer s; logctx.CTXLOG("Creating Output Stream for reply packet on Q=%d - %s", qnum, header.toString(s).str());
  1904. }
  1905. return sendManager->createMessagePacker(header.uid, header.getSequenceId(), &header, sizeof(RoxiePacketHeader), header.serverId, qnum);
  1906. }
  1907. virtual bool replyPending(RoxiePacketHeader &header)
  1908. {
  1909. return sendManager->dataQueued(header.uid, header.getSequenceId(), header.serverId);
  1910. }
  1911. virtual bool abortCompleted(RoxiePacketHeader &header)
  1912. {
  1913. return sendManager->abortData(header.uid, header.getSequenceId(), header.serverId);
  1914. }
  1915. bool abortRunning(RoxiePacketHeader &header, RoxieQueue &queue, bool checkRank, bool &preActivity)
  1916. {
  1917. bool queryFound = false;
  1918. bool ret = false;
  1919. Owned<IPooledThreadIterator> wi = queue.running();
  1920. ForEach(*wi)
  1921. {
  1922. CRoxieWorker &w = (CRoxieWorker &) wi->query();
  1923. if (w.checkAbort(header, checkRank, queryFound, preActivity))
  1924. {
  1925. ret = true;
  1926. break;
  1927. }
  1928. else if (queryFound)
  1929. {
  1930. ret = false;
  1931. break;
  1932. }
  1933. }
  1934. if (!checkRank)
  1935. {
  1936. if (traceLevel > 8)
  1937. DBGLOG("discarding data for aborted query");
  1938. ROQ->abortCompleted(header);
  1939. }
  1940. return ret;
  1941. }
  1942. void doIbyti(RoxiePacketHeader &header, RoxieQueue &queue
  1943. #ifndef SUBCHANNELS_IN_HEADER
  1944. , const ITopologyServer* topology
  1945. #endif
  1946. )
  1947. {
  1948. assert(!localAgent);
  1949. bool preActivity = false;
  1950. #ifdef SUBCHANNELS_IN_HEADER
  1951. unsigned mySubChannel = header.mySubChannel();
  1952. #else
  1953. const ChannelInfo &channelInfo = topology->queryChannelInfo(header.channel);
  1954. unsigned mySubChannel = channelInfo.subChannel();
  1955. #endif
  1956. if (header.retries == QUERY_ABORTED)
  1957. {
  1958. abortRunning(header, queue, false, preActivity);
  1959. queue.remove(header);
  1960. if (traceRoxiePackets || traceLevel > 10)
  1961. {
  1962. StringBuffer s;
  1963. DBGLOG("Abort activity %s", header.toString(s).str());
  1964. }
  1965. }
  1966. else
  1967. {
  1968. ibytiPacketsReceived++;
  1969. unsigned subChannel = header.getRespondingSubChannel();
  1970. if (subChannel == mySubChannel)
  1971. {
  1972. if (traceRoxiePackets || traceLevel > 10)
  1973. DBGLOG("doIBYTI packet was from self");
  1974. ibytiPacketsFromSelf++;
  1975. }
  1976. else
  1977. {
  1978. #ifndef SUBCHANNELS_IN_HEADER
  1979. channelInfo.noteChannelHealthy(subChannel);
  1980. #else
  1981. noteNodeHealthy(header.subChannels[subChannel].getIpAddress());
  1982. #endif
  1983. bool foundInQ = queue.remove(header);
  1984. if (foundInQ)
  1985. {
  1986. if (traceRoxiePackets || traceLevel > 10)
  1987. {
  1988. StringBuffer s;
  1989. DBGLOG("Removed activity from Q : %s", header.toString(s).str());
  1990. }
  1991. ibytiPacketsWorked++;
  1992. return;
  1993. }
  1994. if (abortRunning(header, queue, true, preActivity))
  1995. {
  1996. if (traceRoxiePackets || traceLevel > 10)
  1997. {
  1998. StringBuffer s;
  1999. DBGLOG("Aborted running activity : %s", header.toString(s).str());
  2000. }
  2001. if (preActivity)
  2002. ibytiPacketsWorked++;
  2003. else
  2004. ibytiPacketsHalfWorked++;
  2005. return;
  2006. }
  2007. if (traceRoxiePackets || traceLevel > 10)
  2008. {
  2009. StringBuffer s;
  2010. DBGLOG("doIBYTI packet was too late (or too early) : %s", header.toString(s).str());
  2011. }
  2012. ibytiPacketsTooLate++; // meaning either I started and reserve the right to finish, or I finished already
  2013. if (IBYTIbufferSize)
  2014. queue.noteOrphanIBYTI(header);
  2015. }
  2016. }
  2017. }
  2018. void processMessage(MemoryBuffer &mb, RoxiePacketHeader &header, RoxieQueue &queue)
  2019. {
  2020. // NOTE - this thread needs to do as little as possible - just read packets and queue them up - otherwise we can get packet loss due to buffer overflow
  2021. // DO NOT put tracing on this thread except at very high tracelevels!
  2022. #ifdef SUBCHANNELS_IN_HEADER
  2023. unsigned mySubchannel = header.mySubChannel();
  2024. #else
  2025. Owned<const ITopologyServer> topology = getTopology();
  2026. if (!header.channel)
  2027. {
  2028. // Turn broadcast packet (channel 0), as early as possible, into non-0 channel packets.
  2029. // So retries and other communication with Roxie server (which uses non-0 channel numbers) will not cause double work or confusion.
  2030. // Unfortunately this is bad news for dropping packets
  2031. const std::vector<unsigned> channels = topology->queryChannels();
  2032. Owned<IRoxieQueryPacket> packet = createRoxiePacket(mb);
  2033. for (unsigned i = 1; i < channels.size(); i++)
  2034. queue.enqueue(packet->clonePacket(channels[i]));
  2035. header.channel = channels[0];
  2036. queue.enqueue(packet.getClear());
  2037. return;
  2038. }
  2039. unsigned mySubchannel = topology->queryChannelInfo(header.channel).subChannel();
  2040. #endif
  2041. if (header.activityId == ROXIE_FILECALLBACK || header.activityId == ROXIE_DEBUGCALLBACK )
  2042. {
  2043. Owned<IRoxieQueryPacket> packet = createRoxiePacket(mb);
  2044. if (traceLevel > 10)
  2045. {
  2046. StringBuffer s;
  2047. DBGLOG("ROXIE_CALLBACK %s", header.toString(s).str());
  2048. }
  2049. doFileCallback(packet);
  2050. }
  2051. else if ((header.activityId & ~ROXIE_PRIORITY_MASK) == 0)
  2052. doIbyti(header, queue
  2053. #ifndef SUBCHANNELS_IN_HEADER
  2054. , topology
  2055. #endif
  2056. ); // MORE - check how fast this is!
  2057. else if (IBYTIbufferSize && queue.lookupOrphanIBYTI(header))
  2058. {
  2059. if (traceRoxiePackets || traceLevel > 10)
  2060. {
  2061. StringBuffer s;
  2062. DBGLOG("doIBYTI packet was too early : %s", header.toString(s).str());
  2063. }
  2064. ibytiPacketsTooLate--;
  2065. ibytiPacketsTooEarly++;
  2066. }
  2067. else
  2068. {
  2069. Owned<IRoxieQueryPacket> packet = createRoxiePacket(mb);
  2070. AgentContextLogger logctx(packet);
  2071. unsigned retries = header.thisChannelRetries(mySubchannel);
  2072. if (retries)
  2073. {
  2074. // MORE - is this fast enough? By the time I am seeing retries I may already be under load. Could move onto a separate thread
  2075. assertex(header.channel); // should never see a retry on channel 0
  2076. if (retries >= SUBCHANNEL_MASK)
  2077. return; // someone sent a failure or something - ignore it
  2078. // Send back an out-of-band immediately, to let Roxie server know that channel is still active
  2079. if (!(testAgentFailure & 0x800))
  2080. {
  2081. RoxiePacketHeader newHeader(header, ROXIE_ALIVE, mySubchannel);
  2082. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  2083. output->flush();
  2084. }
  2085. // If it's a retry, look it up against already running, or output stream, or input queue
  2086. // if found, send an IBYTI and discard retry request
  2087. if (!mySubchannel)
  2088. retriesReceivedPrm++;
  2089. else
  2090. retriesReceivedSec++;
  2091. bool alreadyRunning = false;
  2092. Owned<IPooledThreadIterator> wi = queue.running();
  2093. ForEach(*wi)
  2094. {
  2095. CRoxieWorker &w = (CRoxieWorker &) wi->query();
  2096. if (w.match(header))
  2097. {
  2098. alreadyRunning = true;
  2099. if (!mySubchannel)
  2100. retriesIgnoredPrm++;
  2101. else
  2102. retriesIgnoredSec++;
  2103. ROQ->sendIbyti(header, logctx, mySubchannel);
  2104. if (logctx.queryTraceLevel() > 10)
  2105. {
  2106. StringBuffer xx; logctx.CTXLOG("Ignored retry on subchannel %u for running activity %s", mySubchannel, header.toString(xx).str());
  2107. }
  2108. break;
  2109. }
  2110. }
  2111. if (!alreadyRunning && checkCompleted && ROQ->replyPending(header))
  2112. {
  2113. alreadyRunning = true;
  2114. if (!mySubchannel)
  2115. retriesIgnoredPrm++;
  2116. else
  2117. retriesIgnoredSec++;
  2118. ROQ->sendIbyti(header, logctx, mySubchannel);
  2119. if (logctx.queryTraceLevel() > 10)
  2120. {
  2121. StringBuffer xx; logctx.CTXLOG("Ignored retry on subchannel %u for completed activity %s", mySubchannel, header.toString(xx).str());
  2122. }
  2123. }
  2124. if (!alreadyRunning)
  2125. {
  2126. if (logctx.queryTraceLevel() > 10)
  2127. {
  2128. StringBuffer xx; logctx.CTXLOG("Retry %d received on subchannel %u for %s", retries+1, mySubchannel, header.toString(xx).str());
  2129. }
  2130. queue.enqueueUnique(packet.getClear(), mySubchannel);
  2131. }
  2132. }
  2133. else // first time (not a retry).
  2134. queue.enqueue(packet.getClear());
  2135. }
  2136. }
  2137. int run()
  2138. {
  2139. if (traceLevel)
  2140. DBGLOG("RoxieSocketQueueManager::run() starting: doIbytiDelay=%s minIbytiDelay=%u initIbytiDelay=%u",
  2141. doIbytiDelay?"YES":"NO", minIbytiDelay, initIbytiDelay);
  2142. for (;;)
  2143. {
  2144. MemoryBuffer mb;
  2145. try
  2146. {
  2147. // NOTE - this thread needs to do as little as possible - just read packets and queue them up - otherwise we can get packet loss due to buffer overflow
  2148. // DO NOT put tracing on this thread except at very high tracelevels!
  2149. unsigned l;
  2150. multicastSocket->read(mb.reserve(maxPacketSize), sizeof(RoxiePacketHeader), maxPacketSize, l, 5);
  2151. mb.setLength(l);
  2152. packetsReceived++;
  2153. RoxiePacketHeader &header = *(RoxiePacketHeader *) mb.toByteArray();
  2154. if (l != header.packetlength)
  2155. DBGLOG("sock->read returned %d but packetlength was %d", l, header.packetlength);
  2156. if (traceRoxiePackets || traceLevel > 10)
  2157. {
  2158. StringBuffer s;
  2159. DBGLOG("Read roxie packet: %s", header.toString(s).str());
  2160. }
  2161. #ifdef ROXIE_SLA_LOGIC
  2162. if (header.activityId & ROXIE_SLA_PRIORITY)
  2163. processMessage(mb, header, slaQueue);
  2164. else
  2165. #endif
  2166. if (header.activityId & ROXIE_HIGH_PRIORITY)
  2167. processMessage(mb, header, hiQueue);
  2168. else
  2169. processMessage(mb, header, loQueue);
  2170. }
  2171. catch (IException *E)
  2172. {
  2173. if (running)
  2174. {
  2175. // MORE: Maybe we should utilize IException::errorCode - not just text ??
  2176. if (E->errorCode()==JSOCKERR_timeout_expired)
  2177. E->Release();
  2178. else if (roxiemem::memPoolExhausted())
  2179. {
  2180. //MORE: I think this should probably be based on the error code instead.
  2181. EXCLOG(E, "Exception reading or processing roxie packet");
  2182. E->Release();
  2183. MilliSleep(1000); // Give a chance for mem free
  2184. }
  2185. else
  2186. {
  2187. EXCLOG(E, "Exception reading or processing roxie packet");
  2188. E->Release();
  2189. // MORE: Protect with try logic, in case udp_create throws exception ?
  2190. // What to do if create fails (ie exception is caught) ?
  2191. if (multicastSocket)
  2192. {
  2193. multicastSocket->close();
  2194. multicastSocket.clear();
  2195. openMulticastSocket();
  2196. }
  2197. }
  2198. }
  2199. else
  2200. {
  2201. E->Release();
  2202. break;
  2203. }
  2204. }
  2205. }
  2206. return 0;
  2207. }
  2208. void start()
  2209. {
  2210. RoxieReceiverBase::start();
  2211. running = true;
  2212. readThread.start();
  2213. }
  2214. void stop()
  2215. {
  2216. if (running)
  2217. {
  2218. running = false;
  2219. multicastSocket->close();
  2220. }
  2221. RoxieReceiverBase::stop();
  2222. }
  2223. void join()
  2224. {
  2225. readThread.join();
  2226. RoxieReceiverBase::join();
  2227. }
  2228. virtual IReceiveManager *queryReceiveManager()
  2229. {
  2230. return receiveManager;
  2231. }
  2232. };
  2233. class RoxieUdpSocketQueueManager : public RoxieSocketQueueManager
  2234. {
  2235. public:
  2236. RoxieUdpSocketQueueManager(unsigned snifferChannel, unsigned _numWorkers) : RoxieSocketQueueManager(_numWorkers)
  2237. {
  2238. int udpQueueSize = topology->getPropInt("@udpQueueSize", UDP_QUEUE_SIZE);
  2239. int udpSendQueueSize = topology->getPropInt("@udpSendQueueSize", UDP_SEND_QUEUE_SIZE);
  2240. int udpMaxSlotsPerClient = topology->getPropInt("@udpMaxSlotsPerClient", 0x7fffffff);
  2241. if (topology->getPropInt("@sendMaxRate", 0))
  2242. {
  2243. unsigned sendMaxRate = topology->getPropInt("@sendMaxRate");
  2244. unsigned sendMaxRatePeriod = topology->getPropInt("@sendMaxRatePeriod", 1);
  2245. bucket.setown(new TokenBucket(sendMaxRate, sendMaxRatePeriod, sendMaxRate));
  2246. throttledPacketSendManager.setown(new RoxieThrottledPacketSender(*bucket, maxPacketSize));
  2247. }
  2248. IpAddress snifferIp;
  2249. getChannelIp(snifferIp, snifferChannel);
  2250. if (udpMaxSlotsPerClient > udpQueueSize)
  2251. udpMaxSlotsPerClient = udpQueueSize;
  2252. unsigned serverFlowPort = topology->getPropInt("@serverFlowPort", CCD_SERVER_FLOW_PORT);
  2253. unsigned dataPort = topology->getPropInt("@dataPort", CCD_DATA_PORT);
  2254. unsigned clientFlowPort = topology->getPropInt("@clientFlowPort", CCD_CLIENT_FLOW_PORT);
  2255. unsigned snifferPort = topology->getPropInt("@snifferPort", CCD_SNIFFER_PORT);
  2256. receiveManager.setown(createReceiveManager(serverFlowPort, dataPort, clientFlowPort, snifferPort, snifferIp, udpQueueSize, udpMaxSlotsPerClient));
  2257. sendManager.setown(createSendManager(serverFlowPort, dataPort, clientFlowPort, snifferPort, snifferIp, udpSendQueueSize, fastLaneQueue ? 3 : 2, bucket));
  2258. }
  2259. };
  2260. class RoxieAeronSocketQueueManager : public RoxieSocketQueueManager
  2261. {
  2262. public:
  2263. RoxieAeronSocketQueueManager(unsigned _numWorkers) : RoxieSocketQueueManager(_numWorkers)
  2264. {
  2265. unsigned dataPort = topology->getPropInt("@dataPort", CCD_DATA_PORT);
  2266. SocketEndpoint ep(dataPort, myNode.getIpAddress());
  2267. receiveManager.setown(createAeronReceiveManager(ep));
  2268. assertex(!myNode.getIpAddress().isNull());
  2269. sendManager.setown(createAeronSendManager(dataPort, fastLaneQueue ? 3 : 2, myNode.getIpAddress()));
  2270. }
  2271. };
  2272. #ifdef _MSC_VER
  2273. #pragma warning( pop )
  2274. #endif
  2275. //==================================================================================================
  2276. interface ILocalMessageCollator : extends IMessageCollator
  2277. {
  2278. virtual void enqueueMessage(bool outOfBand, void *data, unsigned datalen, void *meta, unsigned metalen, void *header, unsigned headerlen) = 0;
  2279. };
  2280. interface ILocalReceiveManager : extends IReceiveManager
  2281. {
  2282. virtual ILocalMessageCollator *lookupCollator(ruid_t id) = 0;
  2283. };
  2284. class LocalMessagePacker : public CDummyMessagePacker
  2285. {
  2286. MemoryBuffer meta;
  2287. MemoryBuffer header;
  2288. Linked<ILocalReceiveManager> rm;
  2289. ruid_t id;
  2290. bool outOfBand;
  2291. public:
  2292. IMPLEMENT_IINTERFACE;
  2293. LocalMessagePacker(RoxiePacketHeader &_header, bool _outOfBand, ILocalReceiveManager *_rm) : rm(_rm), outOfBand(_outOfBand)
  2294. {
  2295. id = _header.uid;
  2296. header.append(sizeof(RoxiePacketHeader), &_header);
  2297. }
  2298. virtual void flush() override;
  2299. virtual void sendMetaInfo(const void *buf, unsigned len) override
  2300. {
  2301. meta.append(len, buf);
  2302. }
  2303. };
  2304. class CLocalMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2305. {
  2306. void *data;
  2307. unsigned datalen;
  2308. unsigned pos;
  2309. Linked<IRowManager> rowManager;
  2310. public:
  2311. IMPLEMENT_IINTERFACE;
  2312. CLocalMessageUnpackCursor(IRowManager *_rowManager, void *_data, unsigned _datalen)
  2313. : rowManager(_rowManager)
  2314. {
  2315. datalen = _datalen;
  2316. data = _data;
  2317. pos = 0;
  2318. }
  2319. ~CLocalMessageUnpackCursor()
  2320. {
  2321. }
  2322. virtual bool atEOF() const
  2323. {
  2324. return datalen==pos;
  2325. }
  2326. virtual bool isSerialized() const
  2327. {
  2328. // NOTE: tempting to think that we could avoid serializing in localAgent case, but have to be careful about the lifespan of the rowManager...
  2329. return true;
  2330. }
  2331. virtual const void * getNext(int length)
  2332. {
  2333. if (pos==datalen)
  2334. return NULL;
  2335. assertex(pos + length <= datalen);
  2336. void * cur = ((char *) data) + pos;
  2337. pos += length;
  2338. void * ret = rowManager->allocate(length, 0);
  2339. memcpy(ret, cur, length);
  2340. //No need for finalize since only contains plain data.
  2341. return ret;
  2342. }
  2343. };
  2344. class CLocalMessageResult : implements IMessageResult, public CInterface
  2345. {
  2346. void *data;
  2347. void *meta;
  2348. void *header;
  2349. unsigned datalen, metalen, headerlen;
  2350. unsigned pos;
  2351. public:
  2352. IMPLEMENT_IINTERFACE;
  2353. CLocalMessageResult(void *_data, unsigned _datalen, void *_meta, unsigned _metalen, void *_header, unsigned _headerlen)
  2354. {
  2355. datalen = _datalen;
  2356. metalen = _metalen;
  2357. headerlen = _headerlen;
  2358. data = _data;
  2359. meta = _meta;
  2360. header = _header;
  2361. pos = 0;
  2362. }
  2363. ~CLocalMessageResult()
  2364. {
  2365. free(data);
  2366. free(meta);
  2367. free(header);
  2368. }
  2369. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2370. {
  2371. return new CLocalMessageUnpackCursor(rowMgr, data, datalen);
  2372. }
  2373. virtual const void *getMessageHeader(unsigned &length) const
  2374. {
  2375. length = headerlen;
  2376. return header;
  2377. }
  2378. virtual const void *getMessageMetadata(unsigned &length) const
  2379. {
  2380. length = metalen;
  2381. return meta;
  2382. }
  2383. virtual void discard() const
  2384. {
  2385. }
  2386. };
  2387. class CLocalMessageCollator : implements ILocalMessageCollator, public CInterface
  2388. {
  2389. InterruptableSemaphore sem;
  2390. QueueOf<IMessageResult, false> pending;
  2391. CriticalSection crit;
  2392. Linked<IRowManager> rowManager; // Linked to ensure it lives longer than me
  2393. Linked<ILocalReceiveManager> receiveManager;
  2394. ruid_t id;
  2395. unsigned totalBytesReceived;
  2396. public:
  2397. IMPLEMENT_IINTERFACE;
  2398. CLocalMessageCollator(IRowManager *_rowManager, ruid_t _ruid);
  2399. ~CLocalMessageCollator();
  2400. virtual ruid_t queryRUID() const
  2401. {
  2402. return id;
  2403. }
  2404. virtual IMessageResult* getNextResult(unsigned time_out, bool &anyActivity)
  2405. {
  2406. anyActivity = false;
  2407. if (!sem.wait(time_out))
  2408. return NULL;
  2409. anyActivity = true;
  2410. CriticalBlock c(crit);
  2411. return pending.dequeue();
  2412. }
  2413. virtual void interrupt(IException *E)
  2414. {
  2415. sem.interrupt(E);
  2416. }
  2417. virtual void enqueueMessage(bool outOfBand, void *data, unsigned datalen, void *meta, unsigned metalen, void *header, unsigned headerlen)
  2418. {
  2419. CriticalBlock c(crit);
  2420. if (outOfBand)
  2421. pending.enqueueHead(new CLocalMessageResult(data, datalen, meta, metalen, header, headerlen));
  2422. else
  2423. pending.enqueue(new CLocalMessageResult(data, datalen, meta, metalen, header, headerlen));
  2424. sem.signal();
  2425. totalBytesReceived += datalen + metalen + headerlen;
  2426. }
  2427. virtual unsigned queryBytesReceived() const
  2428. {
  2429. return totalBytesReceived;
  2430. }
  2431. };
  2432. class RoxieLocalReceiveManager : implements ILocalReceiveManager, public CInterface
  2433. {
  2434. MapXToMyClass<ruid_t, ruid_t, ILocalMessageCollator> collators;
  2435. CriticalSection crit;
  2436. Owned<StringContextLogger> logctx;
  2437. public:
  2438. IMPLEMENT_IINTERFACE;
  2439. RoxieLocalReceiveManager() : logctx(new StringContextLogger("RoxieLocalReceiveManager"))
  2440. {
  2441. }
  2442. virtual IMessageCollator *createMessageCollator(IRowManager *manager, ruid_t ruid)
  2443. {
  2444. ILocalMessageCollator *collator = new CLocalMessageCollator(manager, ruid);
  2445. CriticalBlock b(crit);
  2446. collators.setValue(ruid, collator);
  2447. return collator;
  2448. }
  2449. virtual void detachCollator(const IMessageCollator *collator)
  2450. {
  2451. ruid_t id = collator->queryRUID();
  2452. CriticalBlock b(crit);
  2453. collators.setValue(id, NULL);
  2454. }
  2455. virtual ILocalMessageCollator *lookupCollator(ruid_t id)
  2456. {
  2457. CriticalBlock b(crit);
  2458. ILocalMessageCollator *ret = collators.getValue(id);
  2459. if (!ret)
  2460. ret = collators.getValue(RUID_DISCARD);
  2461. return LINK(ret);
  2462. }
  2463. };
  2464. void LocalMessagePacker::flush()
  2465. {
  2466. // MORE - I think this means we don't send anything until whole message available in localAgent mode, which
  2467. // may not be optimal.
  2468. data.setLength(lastput);
  2469. Owned<ILocalMessageCollator> collator = rm->lookupCollator(id);
  2470. if (collator)
  2471. {
  2472. unsigned datalen = data.length();
  2473. unsigned metalen = meta.length();
  2474. unsigned headerlen = header.length();
  2475. collator->enqueueMessage(outOfBand, data.detach(), datalen, meta.detach(), metalen, header.detach(), headerlen);
  2476. }
  2477. // otherwise Roxie server is no longer interested and we can simply discard
  2478. }
  2479. CLocalMessageCollator::CLocalMessageCollator(IRowManager *_rowManager, ruid_t _ruid)
  2480. : rowManager(_rowManager), id(_ruid)
  2481. {
  2482. totalBytesReceived = 0;
  2483. }
  2484. CLocalMessageCollator::~CLocalMessageCollator()
  2485. {
  2486. IMessageResult *goer;
  2487. for (;;)
  2488. {
  2489. goer = pending.dequeue();
  2490. if (!goer)
  2491. break;
  2492. goer->Release();
  2493. }
  2494. }
  2495. class RoxieLocalQueueManager : public RoxieReceiverBase
  2496. {
  2497. Linked<RoxieLocalReceiveManager> receiveManager;
  2498. public:
  2499. RoxieLocalQueueManager(unsigned _numWorkers) : RoxieReceiverBase(_numWorkers)
  2500. {
  2501. receiveManager.setown(new RoxieLocalReceiveManager);
  2502. }
  2503. virtual void sendPacket(IRoxieQueryPacket *packet, const IRoxieContextLogger &logctx) override
  2504. {
  2505. RoxiePacketHeader &header = packet->queryHeader();
  2506. unsigned retries = header.thisChannelRetries(0);
  2507. if (header.activityId == ROXIE_FILECALLBACK || header.activityId == ROXIE_DEBUGCALLBACK )
  2508. {
  2509. if (traceLevel > 5)
  2510. {
  2511. StringBuffer s;
  2512. DBGLOG("ROXIE_CALLBACK %s", header.toString(s).str());
  2513. }
  2514. doFileCallback(packet);
  2515. }
  2516. else if (retries < SUBCHANNEL_MASK)
  2517. {
  2518. if (retries)
  2519. {
  2520. // Send back an out-of-band immediately, to let Roxie server know that channel is still active
  2521. RoxiePacketHeader newHeader(header, ROXIE_ALIVE, 0);
  2522. Owned<IMessagePacker> output = createOutputStream(newHeader, true, logctx);
  2523. output->flush();
  2524. return; // No point sending the retry in localAgent mode
  2525. }
  2526. RoxieQueue *targetQueue;
  2527. #ifdef ROXIE_SLA_LOGIC
  2528. if (header.activityId & ROXIE_SLA_PRIORITY)
  2529. targetQueue = &slaQueue;
  2530. else
  2531. #endif
  2532. if (header.activityId & ROXIE_HIGH_PRIORITY)
  2533. targetQueue = &hiQueue;
  2534. else
  2535. targetQueue = &loQueue;
  2536. if (header.channel)
  2537. {
  2538. targetQueue->enqueue(LINK(packet));
  2539. }
  2540. else
  2541. {
  2542. #ifdef SUBCHANNELS_IN_HEADER
  2543. // In SUBCHANNELS_IN_HEADER mode this translation has been done on server before sending
  2544. throwUnexpected();
  2545. #else
  2546. // Turn broadcast packet (channel 0), as early as possible, into non-0 channel packets.
  2547. // So retries and other communication with Roxie server (which uses non-0 channel numbers) will not cause double work or confusion.
  2548. for (unsigned i = 0; i < numChannels; i++)
  2549. {
  2550. targetQueue->enqueue(packet->clonePacket(i+1));
  2551. }
  2552. #endif
  2553. }
  2554. }
  2555. }
  2556. virtual void sendIbyti(RoxiePacketHeader &header, const IRoxieContextLogger &logctx, unsigned subChannel) override
  2557. {
  2558. // Don't do IBYTI's when local agent - no buddy to talk to anyway
  2559. }
  2560. virtual void sendAbort(RoxiePacketHeader &header, const IRoxieContextLogger &logctx) override
  2561. {
  2562. MTIME_SECTION(queryActiveTimer(), "RoxieLocalQueueManager::sendAbort");
  2563. RoxiePacketHeader abortHeader(header, header.activityId & ROXIE_PRIORITY_MASK, 0);
  2564. abortHeader.retries = QUERY_ABORTED;
  2565. if (logctx.queryTraceLevel() > 8)
  2566. {
  2567. StringBuffer s; logctx.CTXLOG("Sending ABORT packet %s", abortHeader.toString(s).str());
  2568. }
  2569. MemoryBuffer data;
  2570. data.append(sizeof(abortHeader), &abortHeader);
  2571. Owned<IRoxieQueryPacket> packet = createRoxiePacket(data);
  2572. sendPacket(packet, logctx);
  2573. abortsSent++;
  2574. }
  2575. virtual void sendAbortCallback(const RoxiePacketHeader &header, const char *lfn, const IRoxieContextLogger &logctx) override
  2576. {
  2577. MTIME_SECTION(queryActiveTimer(), "RoxieLocalQueueManager::sendAbortCallback");
  2578. RoxiePacketHeader abortHeader(header, ROXIE_FILECALLBACK, 0);
  2579. abortHeader.retries = QUERY_ABORTED;
  2580. MemoryBuffer data;
  2581. data.append(sizeof(abortHeader), &abortHeader).append(lfn);
  2582. if (logctx.queryTraceLevel() > 5)
  2583. {
  2584. StringBuffer s; logctx.CTXLOG("Sending ABORT FILECALLBACK packet %s for file %s", abortHeader.toString(s).str(), lfn);
  2585. }
  2586. Owned<IRoxieQueryPacket> packet = createRoxiePacket(data);
  2587. sendPacket(packet, logctx);
  2588. abortsSent++;
  2589. }
  2590. virtual IMessagePacker *createOutputStream(RoxiePacketHeader &header, bool outOfBand, const IRoxieContextLogger &logctx) override
  2591. {
  2592. return new LocalMessagePacker(header, outOfBand, receiveManager);
  2593. }
  2594. virtual IReceiveManager *queryReceiveManager() override
  2595. {
  2596. return receiveManager;
  2597. }
  2598. virtual bool replyPending(RoxiePacketHeader &header) override
  2599. {
  2600. // MORE - should really have some code here! But returning true is a reasonable approximation.
  2601. return true;
  2602. }
  2603. virtual bool abortCompleted(RoxiePacketHeader &header) override
  2604. {
  2605. // MORE - should really have some code here!
  2606. return false;
  2607. }
  2608. };
  2609. IRoxieOutputQueueManager *ROQ;
  2610. extern IRoxieOutputQueueManager *createOutputQueueManager(unsigned snifferChannel, unsigned numWorkers)
  2611. {
  2612. if (localAgent)
  2613. return new RoxieLocalQueueManager(numWorkers);
  2614. else if (useAeron)
  2615. return new RoxieAeronSocketQueueManager(numWorkers);
  2616. else
  2617. return new RoxieUdpSocketQueueManager(snifferChannel, numWorkers);
  2618. }
  2619. //================================================================================================================================
  2620. class PacketDiscarder : public Thread, implements IPacketDiscarder
  2621. {
  2622. bool aborted;
  2623. Owned<IRowManager> rowManager; // not completely sure I need one... maybe I do
  2624. Owned<IMessageCollator> mc;
  2625. public:
  2626. IMPLEMENT_IINTERFACE;
  2627. PacketDiscarder()
  2628. {
  2629. aborted = false;
  2630. };
  2631. ~PacketDiscarder()
  2632. {
  2633. if (mc)
  2634. ROQ->queryReceiveManager()->detachCollator(mc);
  2635. mc.clear();
  2636. }
  2637. virtual int run()
  2638. {
  2639. Owned<StringContextLogger> logctx = new StringContextLogger("PacketDiscarder");
  2640. rowManager.setown(roxiemem::createRowManager(0, NULL, *logctx, NULL, false));
  2641. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, RUID_DISCARD));
  2642. try
  2643. {
  2644. while (!aborted)
  2645. {
  2646. bool anyActivity = false;
  2647. Owned<IMessageResult> mr = mc->getNextResult(5000, anyActivity);
  2648. if (mr)
  2649. {
  2650. if (traceLevel > 4)
  2651. DBGLOG("Discarding unwanted message");
  2652. unsigned headerLen;
  2653. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(headerLen);
  2654. if (headerLen)
  2655. {
  2656. switch (header.activityId)
  2657. {
  2658. case ROXIE_FILECALLBACK:
  2659. {
  2660. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  2661. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  2662. if (len)
  2663. {
  2664. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  2665. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  2666. const char *rowdata = (const char *) row.get();
  2667. // bool isOpt = * (bool *) rowdata;
  2668. // bool isLocal = * (bool *) (rowdata+1);
  2669. ROQ->sendAbortCallback(header, rowdata+2, *logctx);
  2670. }
  2671. else
  2672. DBGLOG("Unrecognized format in discarded file callback");
  2673. break;
  2674. }
  2675. // MORE - ROXIE_ALIVE perhaps should go here too? debug callbacks? Actually any standard query results should too (though by the time I see them here it's too late (that may change once start streaming)
  2676. }
  2677. }
  2678. else
  2679. DBGLOG("Unwanted message had no header?!");
  2680. }
  2681. else if (!anyActivity)
  2682. {
  2683. // to avoid leaking partial unwanted packets, we clear out mc periodically...
  2684. ROQ->queryReceiveManager()->detachCollator(mc);
  2685. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, RUID_DISCARD));
  2686. }
  2687. }
  2688. }
  2689. catch (IException * E)
  2690. {
  2691. if (!aborted || QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  2692. EXCLOG(E);
  2693. ::Release(E);
  2694. }
  2695. return 0;
  2696. }
  2697. virtual void start()
  2698. {
  2699. Thread::start();
  2700. }
  2701. virtual void stop()
  2702. {
  2703. if (mc)
  2704. mc->interrupt();
  2705. aborted = true;
  2706. join();
  2707. }
  2708. };
  2709. IPacketDiscarder *createPacketDiscarder()
  2710. {
  2711. IPacketDiscarder *packetDiscarder = new PacketDiscarder;
  2712. packetDiscarder->start();
  2713. return packetDiscarder;
  2714. }
  2715. //================================================================================================================================
  2716. // There are various possibly interesting ways to reply to a ping:
  2717. // Reply as soon as receive, or put it on the queue like other messages?
  2718. // Reply for every channel, or just once for every agent?
  2719. // Should I send on channel 0 or round-robin the channels?
  2720. // My gut feeling is that knowing what channels are responding is useful so should reply on every unsuspended channel,
  2721. // and that the delay caused by queuing system is an interesting part of what we want to measure (though nice to know minimum possible too)
  2722. unsigned pingInterval = 60;
  2723. class PingTimer : public Thread
  2724. {
  2725. bool aborted;
  2726. Owned<IRowManager> rowManager;
  2727. Owned<IMessageCollator> mc;
  2728. StringContextLogger logctx;
  2729. void sendPing(unsigned priorityMask)
  2730. {
  2731. try
  2732. {
  2733. unsigned packetSize = sizeof(RoxiePacketHeader) + sizeof(char) + strlen("PING") + 1 + sizeof(PingRecord);
  2734. void *packetData = malloc(packetSize);
  2735. RoxiePacketHeader *header = (RoxiePacketHeader *) packetData;
  2736. RemoteActivityId pingId(ROXIE_PING | priorityMask, 0);
  2737. header->init(pingId, 0, 0, 0);
  2738. char *finger = (char *) (header + 1);
  2739. *finger++ = (char) LOGGING_FLAGSPRESENT;
  2740. strcpy(finger, "PING");
  2741. finger += strlen("PING")+1;
  2742. if (traceLevel > 1)
  2743. DBGLOG("PING sent");
  2744. PingRecord data;
  2745. data.senderIP.ipset(myNode.getIpAddress());
  2746. data.tick = usTick();
  2747. memcpy(finger, &data, sizeof(PingRecord));
  2748. Owned<IRoxieQueryPacket> packet = createRoxiePacket(packetData, packetSize);
  2749. ROQ->sendPacket(packet, logctx);
  2750. }
  2751. catch (IException *E)
  2752. {
  2753. EXCLOG(E);
  2754. E->Release();
  2755. }
  2756. }
  2757. public:
  2758. PingTimer() : logctx("PingTimer")
  2759. {
  2760. aborted = false;
  2761. };
  2762. ~PingTimer()
  2763. {
  2764. if (mc)
  2765. ROQ->queryReceiveManager()->detachCollator(mc);
  2766. mc.clear();
  2767. }
  2768. virtual int run()
  2769. {
  2770. rowManager.setown(roxiemem::createRowManager(1, NULL, queryDummyContextLogger(), NULL, false));
  2771. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, RUID_PING));
  2772. unsigned pingsReceived = 0;
  2773. unsigned pingsElapsed = 0;
  2774. sendPing(ROXIE_HIGH_PRIORITY);
  2775. while (!aborted)
  2776. {
  2777. bool anyActivity = false;
  2778. Owned<IMessageResult> mr = mc->getNextResult(pingInterval*1000, anyActivity);
  2779. if (mr)
  2780. {
  2781. unsigned headerLen;
  2782. const RoxiePacketHeader *header = (const RoxiePacketHeader *) mr->getMessageHeader(headerLen);
  2783. Owned<IMessageUnpackCursor> mu = mr->getCursor(rowManager);
  2784. PingRecord *answer = (PingRecord *) mu->getNext(sizeof(PingRecord));
  2785. if (answer && mu->atEOF() && headerLen==sizeof(RoxiePacketHeader))
  2786. {
  2787. unsigned elapsed = usTick() - answer->tick;
  2788. pingsReceived++;
  2789. pingsElapsed += elapsed;
  2790. if (traceLevel > 10)
  2791. DBGLOG("PING reply channel=%d, time %d", header->channel, elapsed); // DBGLOG is slower than the pings so be careful!
  2792. }
  2793. else
  2794. DBGLOG("PING reply, garbled result");
  2795. ReleaseRoxieRow(answer);
  2796. }
  2797. else if (!anyActivity)
  2798. {
  2799. if (!pingsReceived && roxieMulticastEnabled)
  2800. DBGLOG("PING: NO replies received! Please check multicast settings, and that your network supports multicast.");
  2801. else if (traceLevel)
  2802. DBGLOG("PING: %d replies received, average delay %uus", pingsReceived, pingsReceived ? pingsElapsed / pingsReceived : 0);
  2803. pingsReceived = 0;
  2804. pingsElapsed = 0;
  2805. sendPing(ROXIE_HIGH_PRIORITY); // MORE - we could think about alternating the priority or sending pings on high and low at the same time...
  2806. }
  2807. }
  2808. return 0;
  2809. }
  2810. void stop()
  2811. {
  2812. if (mc)
  2813. mc->interrupt();
  2814. aborted = true;
  2815. }
  2816. static CriticalSection crit;
  2817. } *pingTimer;
  2818. CriticalSection PingTimer::crit;
  2819. extern void startPingTimer()
  2820. {
  2821. CriticalBlock b(PingTimer::crit);
  2822. if (!pingTimer)
  2823. {
  2824. pingTimer = new PingTimer();
  2825. pingTimer->start();
  2826. }
  2827. }
  2828. extern void stopPingTimer()
  2829. {
  2830. CriticalBlock b(PingTimer::crit);
  2831. if (pingTimer)
  2832. {
  2833. pingTimer->stop();
  2834. pingTimer->join();
  2835. delete pingTimer;
  2836. pingTimer = NULL;
  2837. }
  2838. }