ccdqueue.cpp 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332
  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. };
  547. extern IRoxieQueryPacket *createRoxiePacket(void *_data, unsigned _len)
  548. {
  549. if ((unsigned short)_len != _len && !localAgent)
  550. {
  551. StringBuffer s;
  552. RoxiePacketHeader *header = (RoxiePacketHeader *) _data;
  553. header->toString(s);
  554. free(_data);
  555. throw MakeStringException(ROXIE_PACKET_ERROR, "Packet length %d exceeded maximum sending packet %s", _len, s.str());
  556. }
  557. return new CRoxieQueryPacket(_data, _len);
  558. }
  559. extern IRoxieQueryPacket *createRoxiePacket(MemoryBuffer &m)
  560. {
  561. unsigned length = m.length(); // don't make assumptions about evaluation order of parameters...
  562. return createRoxiePacket(m.detachOwn(), length);
  563. }
  564. //=================================================================================
  565. AgentContextLogger::AgentContextLogger()
  566. {
  567. GetHostIp(ip);
  568. set(NULL);
  569. }
  570. AgentContextLogger::AgentContextLogger(IRoxieQueryPacket *packet)
  571. {
  572. GetHostIp(ip);
  573. set(packet);
  574. }
  575. void AgentContextLogger::set(IRoxieQueryPacket *packet)
  576. {
  577. anyOutput = false;
  578. intercept = false;
  579. debuggerActive = false;
  580. checkingHeap = false;
  581. aborted = false;
  582. stats.reset();
  583. start = msTick();
  584. if (packet)
  585. {
  586. CriticalBlock b(crit);
  587. RoxiePacketHeader &header = packet->queryHeader();
  588. const byte *traceInfo = packet->queryTraceInfo();
  589. unsigned traceLength = packet->getTraceLength();
  590. unsigned char loggingFlags = *traceInfo;
  591. if (loggingFlags & LOGGING_FLAGSPRESENT) // should always be true.... but this flag is handy to avoid flags byte ever being NULL
  592. {
  593. traceInfo++;
  594. traceLength--;
  595. if (loggingFlags & LOGGING_INTERCEPTED)
  596. intercept = true;
  597. if (loggingFlags & LOGGING_TRACELEVELSET)
  598. {
  599. ctxTraceLevel = (*traceInfo++ - 1); // avoid null byte here in case anyone still thinks there's just a null-terminated string
  600. traceLength--;
  601. }
  602. if (loggingFlags & LOGGING_BLIND)
  603. blind = true;
  604. if (loggingFlags & LOGGING_CHECKINGHEAP)
  605. checkingHeap = true;
  606. if (loggingFlags & LOGGING_DEBUGGERACTIVE)
  607. {
  608. assertex(traceLength > sizeof(unsigned short));
  609. debuggerActive = true;
  610. unsigned short debugLen = *(unsigned short *) traceInfo;
  611. traceInfo += debugLen + sizeof(unsigned short);
  612. traceLength -= debugLen + sizeof(unsigned short);
  613. }
  614. // Passing the wuid via the logging context prefix is a lot of a hack...
  615. if (loggingFlags & LOGGING_WUID)
  616. {
  617. unsigned wuidLen = 0;
  618. while (wuidLen < traceLength)
  619. {
  620. if (traceInfo[wuidLen]=='@'||traceInfo[wuidLen]==':')
  621. break;
  622. wuidLen++;
  623. }
  624. wuid.set((const char *) traceInfo, wuidLen);
  625. }
  626. }
  627. channel = header.channel;
  628. StringBuffer s(traceLength, (const char *) traceInfo);
  629. s.append("|");
  630. ip.getIpText(s);
  631. s.append(':').append(channel);
  632. StringContextLogger::set(s.str());
  633. if (intercept || mergeAgentStatistics)
  634. {
  635. RoxiePacketHeader newHeader(header, ROXIE_TRACEINFO, 0); // subchannel not relevant
  636. output.setown(ROQ->createOutputStream(newHeader, true, *this));
  637. }
  638. }
  639. else
  640. {
  641. StringContextLogger::set("");
  642. channel = 0;
  643. }
  644. }
  645. void AgentContextLogger::putStatProcessed(unsigned subGraphId, unsigned actId, unsigned idx, unsigned processed, unsigned strands) const
  646. {
  647. if (output && mergeAgentStatistics)
  648. {
  649. MemoryBuffer buf;
  650. buf.append((char) LOG_CHILDCOUNT); // A special log entry for the stats
  651. buf.append(subGraphId);
  652. buf.append(actId);
  653. buf.append(idx);
  654. buf.append(processed);
  655. buf.append(strands);
  656. }
  657. }
  658. void AgentContextLogger::putStats(unsigned subGraphId, unsigned actId, const CRuntimeStatisticCollection &stats) const
  659. {
  660. if (output && mergeAgentStatistics)
  661. {
  662. MemoryBuffer buf;
  663. buf.append((char) LOG_CHILDSTATS); // A special log entry for the stats
  664. buf.append(subGraphId);
  665. buf.append(actId);
  666. if (stats.serialize(buf))
  667. {
  668. unsigned len = buf.length();
  669. void *ret = output->getBuffer(len, true);
  670. memcpy(ret, buf.toByteArray(), len);
  671. output->putBuffer(ret, len, true);
  672. anyOutput = true;
  673. }
  674. }
  675. }
  676. void AgentContextLogger::flush()
  677. {
  678. if (output)
  679. {
  680. CriticalBlock b(crit);
  681. if (mergeAgentStatistics)
  682. {
  683. MemoryBuffer buf;
  684. buf.append((char) LOG_STATVALUES); // A special log entry for the stats
  685. if (stats.serialize(buf))
  686. {
  687. unsigned len = buf.length();
  688. void *ret = output->getBuffer(len, true);
  689. memcpy(ret, buf.toByteArray(), len);
  690. output->putBuffer(ret, len, true);
  691. anyOutput = true;
  692. }
  693. }
  694. ForEachItemIn(idx, log)
  695. {
  696. MemoryBuffer buf;
  697. LogItem &logItem = log.item(idx);
  698. logItem.serialize(buf);
  699. unsigned len = buf.length();
  700. void *ret = output->getBuffer(len, true);
  701. memcpy(ret, buf.toByteArray(), len);
  702. output->putBuffer(ret, len, true);
  703. anyOutput = true;
  704. }
  705. log.kill();
  706. if (anyOutput)
  707. output->flush();
  708. output.clear();
  709. }
  710. }
  711. //=================================================================================
  712. static SpinLock onDemandQueriesCrit;
  713. static MapXToMyClass<hash64_t, hash64_t, IQueryFactory> onDemandQueryCache;
  714. void sendUnloadMessage(hash64_t hash, const char *id, const IRoxieContextLogger &logctx)
  715. {
  716. unsigned packetSize = sizeof(RoxiePacketHeader) + sizeof(char) + strlen(id) + 1;
  717. void *packetData = malloc(packetSize);
  718. RoxiePacketHeader *header = (RoxiePacketHeader *) packetData;
  719. RemoteActivityId unloadId(ROXIE_UNLOAD, hash);
  720. header->init(unloadId, 0, 0, 0);
  721. char *finger = (char *) (header + 1);
  722. *finger++ = (char) LOGGING_FLAGSPRESENT;
  723. strcpy(finger, id);
  724. finger += strlen(id)+1;
  725. if (traceLevel > 1)
  726. DBGLOG("UNLOAD sent for query %s", id);
  727. Owned<IRoxieQueryPacket> packet = createRoxiePacket(packetData, packetSize);
  728. ROQ->sendPacket(packet, logctx);
  729. }
  730. void doUnload(IRoxieQueryPacket *packet, const IRoxieContextLogger &logctx)
  731. {
  732. const RoxiePacketHeader &header = packet->queryHeader();
  733. unsigned channelNo = header.channel;
  734. if (logctx.queryTraceLevel())
  735. logctx.CTXLOG("Unload received for channel %d", channelNo);
  736. hash64_t hashValue = header.queryHash;
  737. hashValue = rtlHash64Data(sizeof(channelNo), &channelNo, hashValue);
  738. SpinBlock b(onDemandQueriesCrit);
  739. onDemandQueryCache.remove(hashValue);
  740. }
  741. void cacheOnDemandQuery(hash64_t hashValue, unsigned channelNo, IQueryFactory *query)
  742. {
  743. hashValue = rtlHash64Data(sizeof(channelNo), &channelNo, hashValue);
  744. SpinBlock b(onDemandQueriesCrit);
  745. onDemandQueryCache.setValue(hashValue, query);
  746. }
  747. //=================================================================================
  748. struct PingRecord
  749. {
  750. unsigned tick;
  751. IpAddress senderIP;
  752. };
  753. void doPing(IRoxieQueryPacket *packet, const IRoxieContextLogger &logctx)
  754. {
  755. const RoxiePacketHeader &header = packet->queryHeader();
  756. const IpAddress serverIP = header.serverId.getIpAddress();
  757. unsigned contextLength = packet->getContextLength();
  758. if (contextLength != sizeof(PingRecord))
  759. {
  760. StringBuffer s;
  761. throw MakeStringException(ROXIE_UNKNOWN_SERVER, "Unexpected data size %d (expected %d) in PING: %s", contextLength, (unsigned) sizeof(PingRecord), header.toString(s).str());
  762. }
  763. const PingRecord *data = (const PingRecord *) packet->queryContextData();
  764. if (!serverIP.ipequals(data->senderIP))
  765. {
  766. StringBuffer s;
  767. throw MakeStringException(ROXIE_UNKNOWN_SERVER, "Message received from unknown Roxie server %s", header.toString(s).str());
  768. }
  769. RoxiePacketHeader newHeader(header, ROXIE_PING, 0); // subchannel not relevant
  770. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  771. void *ret = output->getBuffer(contextLength, false);
  772. memcpy(ret, data, contextLength);
  773. output->putBuffer(ret, contextLength, false);
  774. output->flush();
  775. }
  776. //=================================================================================
  777. static ThreadId roxiePacketReaderThread = 0;
  778. class IBYTIbuffer
  779. {
  780. // This class is used to track a finite set of recently-received IBYTI messages, that may have arrived before the messages they refer to
  781. // It is accessed ONLY from the main reader thread and as such does not need to be threadsafe (but does need to be fast).
  782. // 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
  783. // discarding the oldest tracked orphaned IBYTI - but that's ok, no worse than if we hadn't tracked them at all.
  784. public:
  785. IBYTIbuffer(unsigned _numOrphans) : numOrphans(_numOrphans)
  786. {
  787. assertex(numOrphans);
  788. orphans = new RoxiePacketHeader[numOrphans];
  789. tail = 0;
  790. }
  791. void noteOrphan(const RoxiePacketHeader &hdr)
  792. {
  793. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  794. unsigned now = msTick();
  795. // We could trace that the buffer may be too small, if (orphans[tail].activityId >= now)
  796. orphans[tail].copy(hdr);
  797. orphans[tail].activityId = now + IBYTIbufferLifetime;
  798. tail++;
  799. if (tail == numOrphans)
  800. tail = 0;
  801. }
  802. bool lookup(const RoxiePacketHeader &hdr) const
  803. {
  804. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  805. unsigned now = msTick();
  806. unsigned lookat = tail;
  807. do
  808. {
  809. if (!lookat)
  810. lookat = numOrphans;
  811. lookat--;
  812. if ((int) (orphans[lookat].activityId - now) < 0) // Watch out for wrapping
  813. break; // expired;
  814. if (orphans[lookat].matchPacket(hdr))
  815. return true;
  816. } while (lookat != tail);
  817. return false;
  818. }
  819. private:
  820. RoxiePacketHeader *orphans = nullptr;
  821. unsigned tail = 0;
  822. unsigned numOrphans = 0;
  823. };
  824. //=================================================================================
  825. //
  826. // RoxieQueue - holds pending transactions on a roxie agent
  827. class RoxieQueue : public CInterface, implements IThreadFactory
  828. {
  829. Owned <IThreadPool> workers;
  830. QueueOf<IRoxieQueryPacket, true> waiting;
  831. Semaphore available;
  832. CriticalSection qcrit;
  833. unsigned headRegionSize;
  834. unsigned numWorkers;
  835. RelaxedAtomic<unsigned> started;
  836. std::atomic<unsigned> idle;
  837. IBYTIbuffer *myIBYTIbuffer = nullptr;
  838. void noteQueued()
  839. {
  840. maxQueueLength.store_max(++queueLength);
  841. // NOTE - there is a small race condition here - if idle is 1 but two enqueue's happen
  842. // close enough together that the signal has not yet caused idle to come back down to zero, then the
  843. // desired new thread may not be created. It's unlikely, and it's benign in that the query is still
  844. // processed and the thread will be created next time the HWM is reached.
  845. if (started < numWorkers && idle==0)
  846. {
  847. workers->start(this);
  848. started++;
  849. }
  850. }
  851. public:
  852. IMPLEMENT_IINTERFACE;
  853. RoxieQueue(unsigned _headRegionSize, unsigned _numWorkers)
  854. {
  855. headRegionSize = _headRegionSize;
  856. numWorkers = _numWorkers;
  857. workers.setown(createThreadPool("RoxieWorkers", this, NULL, numWorkers));
  858. started = 0;
  859. idle = 0;
  860. if (IBYTIbufferSize)
  861. myIBYTIbuffer = new IBYTIbuffer(IBYTIbufferSize);
  862. }
  863. ~RoxieQueue()
  864. {
  865. delete myIBYTIbuffer;
  866. }
  867. virtual IPooledThread *createNew();
  868. void abortChannel(unsigned channel);
  869. void start()
  870. {
  871. if (prestartAgentThreads)
  872. {
  873. while (started < numWorkers)
  874. {
  875. workers->start(this);
  876. started++;
  877. }
  878. }
  879. }
  880. IPooledThreadIterator *running()
  881. {
  882. return workers->running();
  883. }
  884. void stopAll()
  885. {
  886. workers->stopAll(true);
  887. signal(workers->runningCount());
  888. }
  889. void join()
  890. {
  891. workers->joinAll(true);
  892. workers.clear(); // Breaks a cyclic reference count that would stop us from releasing RoxieReceiverThread otherwise
  893. }
  894. void enqueue(IRoxieQueryPacket *x)
  895. {
  896. {
  897. #ifdef TIME_PACKETS
  898. x->queryHeader().tick = msTick();
  899. #endif
  900. CriticalBlock qc(qcrit);
  901. waiting.enqueue(x);
  902. noteQueued();
  903. }
  904. available.signal();
  905. }
  906. void enqueueUnique(IRoxieQueryPacket *x, unsigned subChannel)
  907. {
  908. RoxiePacketHeader &header = x->queryHeader();
  909. #ifdef TIME_PACKETS
  910. header.tick = msTick();
  911. #endif
  912. bool found = false;
  913. {
  914. CriticalBlock qc(qcrit);
  915. unsigned len = waiting.ordinality();
  916. unsigned i;
  917. for (i = 0; i < len; i++)
  918. {
  919. IRoxieQueryPacket *queued = waiting.item(i);
  920. if (queued && queued->queryHeader().matchPacket(header))
  921. {
  922. found = true;
  923. break;
  924. }
  925. }
  926. if (!found)
  927. waiting.enqueue(x);
  928. }
  929. if (found)
  930. {
  931. if (traceLevel > 0)
  932. {
  933. StringBuffer xx;
  934. AgentContextLogger l(x);
  935. l.CTXLOG("Ignored retry on subchannel %u for queued activity %s", subChannel, header.toString(xx).str());
  936. }
  937. if (!subChannel)
  938. retriesIgnoredPrm++;
  939. else
  940. retriesIgnoredSec++;
  941. x->Release();
  942. }
  943. else
  944. {
  945. available.signal();
  946. noteQueued();
  947. if (traceLevel > 10)
  948. {
  949. AgentContextLogger l(x);
  950. StringBuffer xx;
  951. l.CTXLOG("enqueued %s", header.toString(xx).str());
  952. }
  953. }
  954. }
  955. bool remove(RoxiePacketHeader &x)
  956. {
  957. unsigned scanLength = 0;
  958. IRoxieQueryPacket *found = nullptr;
  959. {
  960. CriticalBlock qc(qcrit);
  961. unsigned len = waiting.ordinality();
  962. unsigned i;
  963. for (i = 0; i < len; i++)
  964. {
  965. IRoxieQueryPacket *queued = waiting.item(i);
  966. if (queued)
  967. {
  968. scanLength++;
  969. if (queued->queryHeader().matchPacket(x))
  970. {
  971. waiting.set(i, NULL);
  972. found = queued;
  973. break;
  974. }
  975. }
  976. }
  977. }
  978. if (found)
  979. {
  980. #ifdef _DEBUG
  981. RoxiePacketHeader &header = found->queryHeader();
  982. AgentContextLogger l(found);
  983. StringBuffer xx;
  984. l.CTXLOG("discarded %s", header.toString(xx).str());
  985. #endif
  986. found->Release();
  987. queueLength--;
  988. if (scanLength > maxScanLength)
  989. maxScanLength = scanLength;
  990. totScanLength += scanLength;
  991. totScans++;
  992. return true;
  993. }
  994. else
  995. return false;
  996. }
  997. void wait()
  998. {
  999. idle++;
  1000. available.wait();
  1001. idle--;
  1002. }
  1003. void signal(unsigned num)
  1004. {
  1005. available.signal(num);
  1006. }
  1007. IRoxieQueryPacket *dequeue()
  1008. {
  1009. CriticalBlock qc(qcrit);
  1010. unsigned lim = waiting.ordinality();
  1011. if (lim)
  1012. {
  1013. if (headRegionSize)
  1014. {
  1015. if (lim > headRegionSize)
  1016. lim = headRegionSize;
  1017. return waiting.dequeue(fastRand() % lim);
  1018. }
  1019. return waiting.dequeue();
  1020. }
  1021. else
  1022. return NULL;
  1023. }
  1024. unsigned getHeadRegionSize() const
  1025. {
  1026. return headRegionSize;
  1027. }
  1028. unsigned setHeadRegionSize(unsigned newsize)
  1029. {
  1030. unsigned ret = headRegionSize;
  1031. headRegionSize = newsize;
  1032. return ret;
  1033. }
  1034. void noteOrphanIBYTI(const RoxiePacketHeader &hdr)
  1035. {
  1036. if (myIBYTIbuffer)
  1037. myIBYTIbuffer->noteOrphan(hdr);
  1038. }
  1039. bool lookupOrphanIBYTI(const RoxiePacketHeader &hdr) const
  1040. {
  1041. if (myIBYTIbuffer)
  1042. return myIBYTIbuffer->lookup(hdr);
  1043. else
  1044. return false;
  1045. }
  1046. };
  1047. class CRoxieWorker : public CInterface, implements IPooledThread
  1048. {
  1049. RoxieQueue *queue;
  1050. CriticalSection actCrit;
  1051. #ifndef NEW_IBYTI
  1052. Semaphore ibytiSem;
  1053. #endif
  1054. bool stopped;
  1055. bool abortJob;
  1056. bool busy;
  1057. Owned<IRoxieAgentActivity> activity;
  1058. Owned<IRoxieQueryPacket> packet;
  1059. Owned<const ITopologyServer> topology;
  1060. AgentContextLogger logctx;
  1061. public:
  1062. IMPLEMENT_IINTERFACE;
  1063. CRoxieWorker()
  1064. {
  1065. queue = NULL;
  1066. stopped = false;
  1067. busy = false;
  1068. abortJob = false;
  1069. }
  1070. virtual void init(void *_r) override
  1071. {
  1072. queue = (RoxieQueue *) _r;
  1073. stopped = false;
  1074. busy = false;
  1075. abortJob = false;
  1076. }
  1077. virtual bool canReuse() const override
  1078. {
  1079. return true;
  1080. }
  1081. virtual bool stop() override
  1082. {
  1083. stopped = true;
  1084. return true;
  1085. }
  1086. inline void setActivity(IRoxieAgentActivity *act)
  1087. {
  1088. CriticalBlock b(actCrit);
  1089. activity.setown(act);
  1090. }
  1091. inline bool match(RoxiePacketHeader &h)
  1092. {
  1093. // There is a window between getting packet from queue and being able to match it.
  1094. // This could cause some deduping to fail, but it does not matter if it does (so long as it is rare!)
  1095. CriticalBlock b(actCrit);
  1096. return packet && packet->queryHeader().matchPacket(h);
  1097. }
  1098. void abortChannel(unsigned channel)
  1099. {
  1100. CriticalBlock b(actCrit);
  1101. if (packet && packet->queryHeader().channel==channel)
  1102. {
  1103. abortJob = true;
  1104. #ifndef NEW_IBYTI
  1105. if (doIbytiDelay)
  1106. ibytiSem.signal();
  1107. #endif
  1108. if (activity)
  1109. activity->abort();
  1110. }
  1111. }
  1112. bool checkAbort(RoxiePacketHeader &h, bool checkRank, bool &queryFound, bool &preActivity)
  1113. {
  1114. CriticalBlock b(actCrit);
  1115. if (packet && packet->queryHeader().matchPacket(h))
  1116. {
  1117. queryFound = true;
  1118. abortJob = true;
  1119. #ifndef NEW_IBYTI
  1120. if (doIbytiDelay)
  1121. ibytiSem.signal();
  1122. #endif
  1123. if (activity)
  1124. {
  1125. // Try to stop/abort a job after it starts only if IBYTI comes from a higher priority agent
  1126. // (more primary in the rank). The agents with higher rank will hold the lower bits of the retries field in IBYTI packet).
  1127. #ifdef SUBCHANNELS_IN_HEADER
  1128. if (!checkRank || h.getRespondingSubChannel() < h.mySubChannel())
  1129. #else
  1130. if (!checkRank || topology->queryChannelInfo(h.channel).otherAgentHasPriority(h.priorityHash(), h.getRespondingSubChannel()))
  1131. #endif
  1132. {
  1133. activity->abort();
  1134. return true;
  1135. }
  1136. else
  1137. {
  1138. return false;
  1139. }
  1140. }
  1141. if (busy)
  1142. {
  1143. preActivity = true;
  1144. return true;
  1145. }
  1146. }
  1147. return false;
  1148. }
  1149. void throwRemoteException(IException *E, IRoxieAgentActivity *activity, IRoxieQueryPacket *packet, bool isUser)
  1150. {
  1151. try
  1152. {
  1153. if (activity && (logctx.queryTraceLevel() > 1))
  1154. {
  1155. StringBuffer act;
  1156. activity->toString(act);
  1157. logctx.CTXLOG("throwRemoteException, activity %s, isUser=%d", act.str(), (int) isUser);
  1158. if (!isUser)
  1159. EXCLOG(E, "throwRemoteException");
  1160. }
  1161. RoxiePacketHeader &header = packet->queryHeader();
  1162. #ifdef SUBCHANNELS_IN_HEADER
  1163. unsigned mySubChannel = header.mySubChannel();
  1164. #else
  1165. unsigned mySubChannel = topology->queryChannelInfo(header.channel).subChannel();
  1166. #endif
  1167. // I failed to do the query, but already sent out IBYTI - resend it so someone else can try
  1168. if (!isUser)
  1169. {
  1170. StringBuffer s;
  1171. s.append("Exception in agent for packet ");
  1172. header.toString(s);
  1173. logctx.logOperatorException(E, NULL, 0, "%s", s.str());
  1174. header.setException(mySubChannel);
  1175. if (!header.allChannelsFailed() && !localAgent)
  1176. {
  1177. if (logctx.queryTraceLevel() > 1)
  1178. logctx.CTXLOG("resending packet from agent in case others want to try it");
  1179. ROQ->sendPacket(packet, logctx);
  1180. }
  1181. }
  1182. RoxiePacketHeader newHeader(header, ROXIE_EXCEPTION, mySubChannel);
  1183. if (isUser)
  1184. newHeader.retries = (unsigned short) -1;
  1185. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  1186. StringBuffer message("<Exception>");
  1187. message.appendf("<Code>%d</Code><Message>", E->errorCode());
  1188. StringBuffer err;
  1189. E->errorMessage(err);
  1190. encodeXML(err.str(), message);
  1191. message.append("</Message></Exception>");
  1192. unsigned len = message.length();
  1193. void *ret = output->getBuffer(len+1, true);
  1194. memcpy(ret, message.str(), len+1);
  1195. output->putBuffer(ret, len+1, true);
  1196. output->flush();
  1197. E->Release();
  1198. }
  1199. catch (IException *EInE)
  1200. {
  1201. EXCLOG(EInE, "Exception during throwRemoteException");
  1202. E->Release();
  1203. EInE->Release();
  1204. }
  1205. catch (...)
  1206. {
  1207. logctx.CTXLOG("Unknown Exception during throwRemoteException");
  1208. E->Release();
  1209. }
  1210. }
  1211. void doActivity()
  1212. {
  1213. RoxiePacketHeader &header = packet->queryHeader();
  1214. unsigned channel = header.channel;
  1215. hash64_t queryHash = packet->queryHeader().queryHash;
  1216. unsigned activityId = packet->queryHeader().activityId & ~ROXIE_PRIORITY_MASK;
  1217. Owned<IQueryFactory> queryFactory = getQueryFactory(queryHash, channel);
  1218. #ifdef SUBCHANNELS_IN_HEADER
  1219. unsigned mySubChannel = header.mySubChannel();
  1220. #else
  1221. unsigned numAgents = topology->queryAgents(channel).ordinality();
  1222. unsigned mySubChannel = topology->queryChannelInfo(channel).subChannel();
  1223. #endif
  1224. if (!queryFactory && logctx.queryWuid())
  1225. {
  1226. Owned <IRoxieDaliHelper> daliHelper = connectToDali();
  1227. Owned<IConstWorkUnit> wu = daliHelper->attachWorkunit(logctx.queryWuid(), NULL);
  1228. queryFactory.setown(createAgentQueryFactoryFromWu(wu, channel));
  1229. if (queryFactory)
  1230. cacheOnDemandQuery(queryHash, channel, queryFactory);
  1231. }
  1232. if (!queryFactory)
  1233. {
  1234. StringBuffer hdr;
  1235. IException *E = MakeStringException(MSGAUD_operator, ROXIE_UNKNOWN_QUERY, "Roxie agent received request for unregistered query: %s", packet->queryHeader().toString(hdr).str());
  1236. EXCLOG(E, "doActivity");
  1237. throwRemoteException(E, activity, packet, false);
  1238. return;
  1239. }
  1240. try
  1241. {
  1242. bool debugging = logctx.queryDebuggerActive();
  1243. if (debugging)
  1244. {
  1245. if (mySubChannel)
  1246. abortJob = true; // when debugging, we always run on primary only...
  1247. }
  1248. #ifndef NEW_IBYTI
  1249. #ifdef SUBCHANNELS_IN_HEADER
  1250. else if (doIbytiDelay && mySubChannel)
  1251. {
  1252. unsigned delay = 0;
  1253. for (unsigned subChannel = 0; subChannel < mySubChannel; subChannel++)
  1254. delay += getIbytiDelay(header.subChannels[subChannel].getIpAddress());
  1255. unsigned start = 0;
  1256. if (traceRoxiePackets)
  1257. {
  1258. StringBuffer x;
  1259. DBGLOG("YES myTurnToDelay subchannel=%u delay=%u %s", mySubChannel, delay, header.toString(x).str());
  1260. start = msTick();
  1261. }
  1262. if (delay)
  1263. ibytiSem.wait(delay);
  1264. if (traceRoxiePackets)
  1265. {
  1266. StringBuffer x;
  1267. DBGLOG("Delay done, abortJob=%d, elapsed=%d", (int) abortJob, msTick()-start);
  1268. }
  1269. if (!abortJob)
  1270. {
  1271. for (unsigned subChannel = 0; subChannel < mySubChannel; subChannel++)
  1272. noteNodeSick(header.subChannels[subChannel]);
  1273. }
  1274. }
  1275. #else
  1276. else if (doIbytiDelay && (numAgents > 1))
  1277. {
  1278. unsigned hdrHashVal = header.priorityHash();
  1279. unsigned primarySubChannel = (hdrHashVal % numAgents);
  1280. if (primarySubChannel != mySubChannel)
  1281. {
  1282. unsigned delay = topology->queryChannelInfo(channel).getIbytiDelay(primarySubChannel);
  1283. if (logctx.queryTraceLevel() > 6)
  1284. {
  1285. StringBuffer x;
  1286. logctx.CTXLOG("YES myTurnToDelayIBYTI subchannel=%u delay=%u hash=%u %s", mySubChannel, delay, hdrHashVal, header.toString(x).str());
  1287. }
  1288. // MORE: if we are dealing with a query that was on channel 0, we may want a longer delay
  1289. // (since the theory about duplicated work not mattering when cluster is idle does not hold up)
  1290. if (delay)
  1291. {
  1292. ibytiSem.wait(delay);
  1293. if (!abortJob)
  1294. topology->queryChannelInfo(channel).noteChannelsSick(primarySubChannel);
  1295. if (logctx.queryTraceLevel() > 8)
  1296. {
  1297. StringBuffer x;
  1298. logctx.CTXLOG("Buddy did%s send IBYTI, updated delay : %s",
  1299. abortJob ? "" : " NOT", header.toString(x).str());
  1300. }
  1301. }
  1302. }
  1303. else
  1304. {
  1305. #ifndef NO_IBYTI_DELAYS_COUNT
  1306. if (!mySubChannel)
  1307. ibytiNoDelaysPrm++;
  1308. else
  1309. ibytiNoDelaysSec++;
  1310. #endif
  1311. if (logctx.queryTraceLevel() > 6)
  1312. {
  1313. StringBuffer x;
  1314. logctx.CTXLOG("NOT myTurnToDelayIBYTI subchannel=%u hash=%u %s", mySubChannel, hdrHashVal, header.toString(x).str());
  1315. }
  1316. }
  1317. }
  1318. #endif
  1319. #endif
  1320. if (abortJob)
  1321. {
  1322. CriticalBlock b(actCrit);
  1323. busy = false; // Keep order - before setActivity below
  1324. if (logctx.queryTraceLevel() > 5)
  1325. {
  1326. StringBuffer x;
  1327. logctx.CTXLOG("Stop before processing - activity aborted %s", header.toString(x).str());
  1328. }
  1329. return;
  1330. }
  1331. if (!debugging)
  1332. ROQ->sendIbyti(header, logctx, mySubChannel);
  1333. activitiesStarted++;
  1334. Owned <IAgentActivityFactory> factory = queryFactory->getAgentActivityFactory(activityId);
  1335. assertex(factory);
  1336. setActivity(factory->createActivity(logctx, packet));
  1337. Owned<IMessagePacker> output = activity->process();
  1338. if (logctx.queryTraceLevel() > 5)
  1339. {
  1340. StringBuffer x;
  1341. logctx.CTXLOG("done processing %s", header.toString(x).str());
  1342. }
  1343. if (output)
  1344. {
  1345. activitiesCompleted++;
  1346. busy = false; // Keep order - before setActivity below
  1347. setActivity(NULL); // Ensures all stats are merged from child queries etc
  1348. logctx.flush();
  1349. output->flush();
  1350. }
  1351. }
  1352. catch (IUserException *E)
  1353. {
  1354. throwRemoteException(E, activity, packet, true);
  1355. }
  1356. catch (IException *E)
  1357. {
  1358. if (E->errorCode()!=ROXIE_ABORT_ERROR)
  1359. throwRemoteException(E, activity, packet, false);
  1360. else
  1361. E->Release();
  1362. }
  1363. catch (...)
  1364. {
  1365. throwRemoteException(MakeStringException(ROXIE_MULTICAST_ERROR, "Unknown exception"), activity, packet, false);
  1366. }
  1367. busy = false; // Keep order - before setActivity below
  1368. setActivity(NULL);
  1369. }
  1370. virtual void threadmain() override
  1371. {
  1372. while (!stopped)
  1373. {
  1374. try
  1375. {
  1376. for (;;)
  1377. {
  1378. queue->wait();
  1379. if (stopped)
  1380. break;
  1381. agentsActive++;
  1382. maxAgentsActive.store_max(agentsActive);
  1383. abortJob = false;
  1384. busy = true;
  1385. #ifndef NEW_IBYTI
  1386. if (doIbytiDelay)
  1387. ibytiSem.reinit(0U); // Make sure sem is is in no-signaled state
  1388. #endif
  1389. packet.setown(queue->dequeue());
  1390. if (packet)
  1391. {
  1392. queueLength--;
  1393. RoxiePacketHeader &header = packet->queryHeader();
  1394. logctx.set(packet);
  1395. #ifdef TIME_PACKETS
  1396. {
  1397. unsigned now = msTick();
  1398. unsigned packetWait = now-header.tick;
  1399. header.tick = now;
  1400. packetWaitMax.store_max(packetWait);
  1401. packetWaitElapsed += packetWait;
  1402. packetWaitCount++;
  1403. }
  1404. #endif
  1405. topology.setown(getTopology());
  1406. if (logctx.queryTraceLevel() > 10)
  1407. {
  1408. StringBuffer x;
  1409. logctx.CTXLOG("dequeued %s", header.toString(x).str());
  1410. }
  1411. if ((header.activityId & ~ROXIE_PRIORITY_MASK) == ROXIE_UNLOAD)
  1412. {
  1413. doUnload(packet, logctx);
  1414. }
  1415. else if ((header.activityId & ~ROXIE_PRIORITY_MASK) == ROXIE_PING)
  1416. {
  1417. doPing(packet, logctx);
  1418. }
  1419. else if ((header.activityId & ~ROXIE_PRIORITY_MASK) == ROXIE_DEBUGREQUEST)
  1420. {
  1421. // MORE - we need to make sure only executed on primary, and that the proxyId (== pointer to DebugGraphManager) is still valid.
  1422. // 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
  1423. doDebugRequest(packet, logctx);
  1424. }
  1425. else if (header.channel)
  1426. doActivity();
  1427. else
  1428. throwUnexpected(); // channel 0 requests translated earlier now
  1429. #ifdef TIME_PACKETS
  1430. {
  1431. unsigned now = msTick();
  1432. unsigned packetRun = now-header.tick;
  1433. packetRunMax.store_max(packetRun);
  1434. packetRunElapsed += packetRun;
  1435. packetRunCount++;
  1436. }
  1437. #endif
  1438. }
  1439. busy = false;
  1440. {
  1441. CriticalBlock b(actCrit);
  1442. packet.clear();
  1443. topology.clear();
  1444. logctx.set(NULL);
  1445. }
  1446. agentsActive--;
  1447. }
  1448. }
  1449. catch(IException *E)
  1450. {
  1451. CriticalBlock b(actCrit);
  1452. EXCLOG(E);
  1453. if (packet)
  1454. {
  1455. throwRemoteException(E, NULL, packet, false);
  1456. packet.clear();
  1457. }
  1458. else
  1459. E->Release();
  1460. topology.clear();
  1461. }
  1462. catch(...)
  1463. {
  1464. CriticalBlock b(actCrit);
  1465. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception in Roxie worker thread");
  1466. EXCLOG(E);
  1467. if (packet)
  1468. {
  1469. throwRemoteException(E.getClear(), NULL, packet, false);
  1470. packet.clear();
  1471. }
  1472. topology.clear();
  1473. }
  1474. }
  1475. }
  1476. };
  1477. IPooledThread *RoxieQueue::createNew()
  1478. {
  1479. return new CRoxieWorker;
  1480. }
  1481. void RoxieQueue::abortChannel(unsigned channel)
  1482. {
  1483. Owned<IPooledThreadIterator> wi = workers->running();
  1484. ForEach(*wi)
  1485. {
  1486. CRoxieWorker &w = (CRoxieWorker &) wi->query();
  1487. w.abortChannel(channel);
  1488. }
  1489. }
  1490. //=================================================================================
  1491. class CallbackEntry : implements IPendingCallback, public CInterface
  1492. {
  1493. const RoxiePacketHeader &header;
  1494. StringAttr lfn;
  1495. InterruptableSemaphore ready;
  1496. MemoryBuffer data;
  1497. bool gotData;
  1498. public:
  1499. IMPLEMENT_IINTERFACE;
  1500. CallbackEntry(const RoxiePacketHeader &_header, const char *_lfn) : header(_header), lfn(_lfn)
  1501. {
  1502. gotData = false;
  1503. }
  1504. virtual bool wait(unsigned msecs)
  1505. {
  1506. return ready.wait(msecs);
  1507. }
  1508. virtual MemoryBuffer &queryData()
  1509. {
  1510. return data;
  1511. }
  1512. bool matches(RoxiePacketHeader &cand, const char *_lfn)
  1513. {
  1514. return (cand.matchPacket(header) && (!_lfn|| stricmp(_lfn, lfn)==0));
  1515. }
  1516. void doFileCallback(unsigned _len, const void *_data, bool aborted)
  1517. {
  1518. // MORE - make sure we call this for whole query abort as well as for callback abort
  1519. if (aborted)
  1520. ready.interrupt(MakeStringException(0, "Interrupted"));
  1521. else if (!gotData)
  1522. {
  1523. gotData = true;
  1524. data.append(_len, _data);
  1525. ready.signal();
  1526. }
  1527. }
  1528. };
  1529. class RoxieReceiverBase : implements IRoxieOutputQueueManager, public CInterface
  1530. {
  1531. protected:
  1532. RoxieQueue slaQueue;
  1533. RoxieQueue hiQueue;
  1534. RoxieQueue loQueue;
  1535. unsigned numWorkers;
  1536. public:
  1537. IMPLEMENT_IINTERFACE;
  1538. RoxieReceiverBase(unsigned _numWorkers) : slaQueue(headRegionSize, _numWorkers), hiQueue(headRegionSize, _numWorkers), loQueue(headRegionSize, _numWorkers), numWorkers(_numWorkers)
  1539. {
  1540. }
  1541. virtual unsigned getHeadRegionSize() const
  1542. {
  1543. return loQueue.getHeadRegionSize();
  1544. }
  1545. virtual void setHeadRegionSize(unsigned newSize)
  1546. {
  1547. slaQueue.setHeadRegionSize(newSize);
  1548. hiQueue.setHeadRegionSize(newSize);
  1549. loQueue.setHeadRegionSize(newSize);
  1550. }
  1551. virtual void start()
  1552. {
  1553. loQueue.start();
  1554. hiQueue.start();
  1555. slaQueue.start();
  1556. }
  1557. virtual void stop()
  1558. {
  1559. loQueue.stopAll();
  1560. hiQueue.stopAll();
  1561. slaQueue.stopAll();
  1562. }
  1563. virtual void join()
  1564. {
  1565. loQueue.join();
  1566. hiQueue.join();
  1567. slaQueue.join();
  1568. }
  1569. IArrayOf<CallbackEntry> callbacks;
  1570. CriticalSection callbacksCrit;
  1571. virtual IPendingCallback *notePendingCallback(const RoxiePacketHeader &header, const char *lfn)
  1572. {
  1573. CriticalBlock b(callbacksCrit);
  1574. CallbackEntry *callback = new CallbackEntry(header, lfn);
  1575. callbacks.append(*callback);
  1576. return callback;
  1577. }
  1578. virtual void removePendingCallback(IPendingCallback *goer)
  1579. {
  1580. if (goer)
  1581. {
  1582. CriticalBlock b(callbacksCrit);
  1583. callbacks.zap(static_cast<CallbackEntry &>(*goer));
  1584. }
  1585. }
  1586. protected:
  1587. void doFileCallback(IRoxieQueryPacket *packet)
  1588. {
  1589. // This is called on the main agent reader thread so needs to be as fast as possible to avoid lost packets
  1590. const char *lfn;
  1591. const char *data;
  1592. unsigned len;
  1593. RoxiePacketHeader &header = packet->queryHeader();
  1594. if (header.activityId == ROXIE_FILECALLBACK || header.activityId == ROXIE_DEBUGCALLBACK)
  1595. {
  1596. lfn = (const char *) packet->queryContextData();
  1597. unsigned namelen = strlen(lfn) + 1;
  1598. data = lfn + namelen;
  1599. len = packet->getContextLength() - namelen;
  1600. }
  1601. else
  1602. {
  1603. lfn = data = NULL; // used when query aborted
  1604. len = 0;
  1605. }
  1606. CriticalBlock b(callbacksCrit);
  1607. ForEachItemIn(idx, callbacks)
  1608. {
  1609. CallbackEntry &c = callbacks.item(idx);
  1610. if (c.matches(header, lfn))
  1611. {
  1612. if (traceLevel > 10)
  1613. DBGLOG("callback return matched a waiting query");
  1614. c.doFileCallback(len, data, header.retries==QUERY_ABORTED);
  1615. }
  1616. }
  1617. }
  1618. };
  1619. #ifdef _MSC_VER
  1620. #pragma warning ( push )
  1621. #pragma warning ( disable: 4355 )
  1622. #endif
  1623. class RoxieThrottledPacketSender : public Thread
  1624. {
  1625. TokenBucket &bucket;
  1626. InterruptableSemaphore queued;
  1627. Semaphore started;
  1628. unsigned maxPacketSize;
  1629. SafeQueueOf<IRoxieQueryPacket, false> queue;
  1630. class DECL_EXCEPTION StoppedException: public IException, public CInterface
  1631. {
  1632. public:
  1633. IMPLEMENT_IINTERFACE;
  1634. int errorCode() const { return 0; }
  1635. StringBuffer & errorMessage(StringBuffer &str) const { return str.append("Stopped"); }
  1636. MessageAudience errorAudience() const { return MSGAUD_user; }
  1637. };
  1638. void enqueue(IRoxieQueryPacket *packet)
  1639. {
  1640. packet->Link();
  1641. queue.enqueue(packet);
  1642. queued.signal();
  1643. }
  1644. IRoxieQueryPacket *dequeue()
  1645. {
  1646. queued.wait();
  1647. return queue.dequeue();
  1648. }
  1649. public:
  1650. RoxieThrottledPacketSender(TokenBucket &_bucket, unsigned _maxPacketSize)
  1651. : Thread("RoxieThrottledPacketSender"), bucket(_bucket), maxPacketSize(_maxPacketSize)
  1652. {
  1653. start();
  1654. started.wait();
  1655. }
  1656. ~RoxieThrottledPacketSender()
  1657. {
  1658. stop();
  1659. join();
  1660. }
  1661. virtual int run()
  1662. {
  1663. started.signal();
  1664. for (;;)
  1665. {
  1666. try
  1667. {
  1668. Owned<IRoxieQueryPacket> packet = dequeue();
  1669. RoxiePacketHeader &header = packet->queryHeader();
  1670. unsigned length = packet->queryHeader().packetlength;
  1671. {
  1672. MTIME_SECTION(queryActiveTimer(), "bucket_wait");
  1673. bucket.wait((length / 1024) + 1);
  1674. }
  1675. if (!channelWrite(header, true))
  1676. DBGLOG("Roxie packet write wrote too little");
  1677. packetsSent++;
  1678. }
  1679. catch (StoppedException *E)
  1680. {
  1681. E->Release();
  1682. break;
  1683. }
  1684. catch (IException *E)
  1685. {
  1686. EXCLOG(E);
  1687. E->Release();
  1688. }
  1689. catch (...)
  1690. {
  1691. }
  1692. }
  1693. return 0;
  1694. }
  1695. virtual void sendPacket(IRoxieQueryPacket *x, const IRoxieContextLogger &logctx)
  1696. {
  1697. RoxiePacketHeader &header = x->queryHeader();
  1698. unsigned length = x->queryHeader().packetlength;
  1699. assertex (header.activityId & ~ROXIE_PRIORITY_MASK);
  1700. switch (header.retries & ROXIE_RETRIES_MASK)
  1701. {
  1702. case (QUERY_ABORTED & ROXIE_RETRIES_MASK):
  1703. {
  1704. StringBuffer s;
  1705. logctx.CTXLOG("Aborting packet size=%d: %s", length, header.toString(s).str());
  1706. }
  1707. break;
  1708. default:
  1709. {
  1710. StringBuffer s;
  1711. logctx.CTXLOG("Resending packet size=%d: %s", length, header.toString(s).str());
  1712. }
  1713. break;
  1714. case 0:
  1715. if (logctx.queryTraceLevel() > 8)
  1716. {
  1717. StringBuffer s;
  1718. logctx.CTXLOG("Sending packet size=%d: %s", length, header.toString(s).str());
  1719. }
  1720. break;
  1721. }
  1722. if (length > maxPacketSize)
  1723. {
  1724. StringBuffer s;
  1725. throw MakeStringException(ROXIE_PACKET_ERROR, "Maximum packet length %d exceeded sending packet %s", maxPacketSize, header.toString(s).str());
  1726. }
  1727. enqueue(x);
  1728. }
  1729. void stop()
  1730. {
  1731. // bucket.stop();
  1732. queued.interrupt(new StoppedException);
  1733. }
  1734. };
  1735. //------------------------------------------------------------------------------------------------------------
  1736. #ifdef NEW_IBYTI
  1737. class DelayedPacketQueue
  1738. {
  1739. // Used to keep a list of all recently-received packets where we are not primary subchannel. There is one queue per subchannel level
  1740. // It is accessed ONLY from the main reader thread and does not need to be threadsafe (but does need to be fast)
  1741. // We use a doubly-linked list (not std::list as not quite flexible enough).
  1742. class DelayedPacketEntry
  1743. {
  1744. DelayedPacketEntry() = delete;
  1745. DelayedPacketEntry(const DelayedPacketEntry&) = delete;
  1746. public:
  1747. DelayedPacketEntry(IRoxieQueryPacket *_packet, unsigned _waitExpires)
  1748. : packet(_packet), waitExpires(_waitExpires)
  1749. {
  1750. }
  1751. ~DelayedPacketEntry()
  1752. {
  1753. if (prev)
  1754. prev->next = next;
  1755. if (next)
  1756. next->prev = prev;
  1757. }
  1758. bool matches(const RoxiePacketHeader &ibyti) const
  1759. {
  1760. return packet->queryHeader().matchPacket(ibyti);
  1761. }
  1762. IRoxieQueryPacket *getClear()
  1763. {
  1764. return packet.getClear();
  1765. }
  1766. StringBuffer & describe(StringBuffer &ret) const
  1767. {
  1768. return packet->queryHeader().toString(ret);
  1769. }
  1770. Owned<IRoxieQueryPacket> packet;
  1771. DelayedPacketEntry *next = nullptr;
  1772. DelayedPacketEntry *prev = nullptr;
  1773. unsigned waitExpires = 0;
  1774. };
  1775. public:
  1776. DelayedPacketQueue() = default;
  1777. DelayedPacketQueue(const DelayedPacketQueue&) = delete;
  1778. ~DelayedPacketQueue()
  1779. {
  1780. while (head)
  1781. removeEntry(head);
  1782. }
  1783. bool doIBYTI(const RoxiePacketHeader &ibyti)
  1784. {
  1785. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  1786. DelayedPacketEntry *finger = head;
  1787. while (finger)
  1788. {
  1789. if (finger->matches(ibyti))
  1790. {
  1791. if (traceRoxiePackets)
  1792. {
  1793. StringBuffer s;
  1794. DBGLOG("IBYTI removing delayed packet %s", finger->describe(s).str());
  1795. }
  1796. removeEntry(finger);
  1797. return true;
  1798. }
  1799. finger = finger->next;
  1800. }
  1801. return false;
  1802. }
  1803. void append(IRoxieQueryPacket *packet, unsigned expires)
  1804. {
  1805. // Goes on the end. But percolate the expiry time backwards
  1806. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  1807. DelayedPacketEntry *newEntry = new DelayedPacketEntry(packet, expires);
  1808. if (traceRoxiePackets)
  1809. {
  1810. StringBuffer s;
  1811. DBGLOG("Adding delayed packet %s", packet->queryHeader().toString(s).str());
  1812. }
  1813. newEntry->prev = tail;
  1814. if (tail)
  1815. {
  1816. tail->next = newEntry;
  1817. for (DelayedPacketEntry *finger = tail; finger != nullptr; finger = finger->prev)
  1818. {
  1819. if ((int) (finger->waitExpires - expires) <= 0)
  1820. break;
  1821. finger->waitExpires = expires;
  1822. finger = finger->prev;
  1823. }
  1824. }
  1825. else
  1826. head = newEntry;
  1827. tail = newEntry;
  1828. }
  1829. // Move any that we are done waiting for our buddy onto the active queue
  1830. void checkExpired(unsigned now, RoxieQueue &slaQueue, RoxieQueue &hiQueue, RoxieQueue &loQueue)
  1831. {
  1832. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  1833. DelayedPacketEntry *finger = head;
  1834. while (finger)
  1835. {
  1836. if (((int) (finger->waitExpires - now)) <= 0) // Oddly coded to handle wrapping
  1837. {
  1838. IRoxieQueryPacket *packet = finger->getClear();
  1839. const RoxiePacketHeader &header = packet->queryHeader();
  1840. if (traceRoxiePackets)
  1841. {
  1842. StringBuffer s;
  1843. DBGLOG("No IBYTI received yet for delayed packet %s", header.toString(s).str());
  1844. }
  1845. if (header.activityId & ROXIE_SLA_PRIORITY)
  1846. slaQueue.enqueue(packet);
  1847. else if (header.activityId & ROXIE_HIGH_PRIORITY)
  1848. hiQueue.enqueue(packet);
  1849. else
  1850. loQueue.enqueue(packet);
  1851. for (unsigned subChannel = 0; subChannel < MAX_SUBCHANNEL; subChannel++)
  1852. {
  1853. if (header.subChannels[subChannel].isMe() || header.subChannels[subChannel].isNull())
  1854. break;
  1855. noteNodeSick(header.subChannels[subChannel]);
  1856. }
  1857. DelayedPacketEntry *goer = finger;
  1858. finger = finger->next;
  1859. removeEntry(goer);
  1860. }
  1861. else
  1862. break;
  1863. }
  1864. }
  1865. // How long until the next time we want to call checkExpires() ?
  1866. unsigned timeout(unsigned now) const
  1867. {
  1868. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  1869. if (head)
  1870. {
  1871. int delay = (int) (head->waitExpires - now);
  1872. if (delay <= 0)
  1873. return 0;
  1874. else
  1875. return (unsigned) delay;
  1876. }
  1877. else
  1878. return (unsigned) -1;
  1879. }
  1880. private:
  1881. void removeEntry(DelayedPacketEntry *goer)
  1882. {
  1883. if (goer==head)
  1884. head = goer->next;
  1885. if (goer==tail)
  1886. tail = goer->prev;
  1887. delete goer;
  1888. }
  1889. DelayedPacketEntry *head = nullptr;
  1890. DelayedPacketEntry *tail = nullptr;
  1891. };
  1892. //------------------------------------------------------------------------------------------------------------
  1893. class DelayedPacketQueueChannel : public CInterface
  1894. {
  1895. // Manages a set of DelayedPacketQueues, one for each supported subchannel level.
  1896. DelayedPacketQueueChannel() = delete;
  1897. DelayedPacketQueueChannel(const DelayedPacketQueueChannel&) = delete;
  1898. public:
  1899. DelayedPacketQueueChannel(unsigned _channel) : channel(_channel)
  1900. {
  1901. }
  1902. inline unsigned queryChannel() const { return channel; }
  1903. inline DelayedPacketQueue &queryQueue(unsigned subchannel)
  1904. {
  1905. assertex(subchannel); // Subchannel 0 means primary and is never delayed
  1906. subchannel -= 1;
  1907. if (subchannel > maxSeen)
  1908. maxSeen = subchannel;
  1909. return queues[subchannel];
  1910. }
  1911. unsigned timeout(unsigned now) const
  1912. {
  1913. unsigned min = (unsigned) -1;
  1914. for (unsigned queue = 0; queue <= maxSeen; queue++)
  1915. {
  1916. unsigned t = queues[queue].timeout(now);
  1917. if (t < min)
  1918. min = t;
  1919. }
  1920. return min;
  1921. }
  1922. void checkExpired(unsigned now, RoxieQueue &slaQueue, RoxieQueue &hiQueue, RoxieQueue &loQueue)
  1923. {
  1924. for (unsigned queue = 0; queue <= maxSeen; queue++)
  1925. {
  1926. queues[queue].checkExpired(now, slaQueue, hiQueue, loQueue);
  1927. }
  1928. }
  1929. private:
  1930. DelayedPacketQueue queues[MAX_SUBCHANNEL-1]; // Note - primary subchannel is not included
  1931. unsigned channel = 0;
  1932. unsigned maxSeen = 0;
  1933. };
  1934. class DelayedPacketQueueManager
  1935. {
  1936. public:
  1937. DelayedPacketQueueManager() = default;
  1938. DelayedPacketQueueManager(const DelayedPacketQueueManager&) = delete;
  1939. inline DelayedPacketQueue &queryQueue(unsigned channel, unsigned subchannel)
  1940. {
  1941. // Note - there are normally no more than a couple of channels on a single agent.
  1942. // If that were to change we could make this a fixed size array
  1943. assert(GetCurrentThreadId()==roxiePacketReaderThread);
  1944. ForEachItemIn(idx, channels)
  1945. {
  1946. DelayedPacketQueueChannel &i = channels.item(idx);
  1947. if (i.queryChannel() == channel)
  1948. return i.queryQueue(subchannel);
  1949. }
  1950. channels.append(*new DelayedPacketQueueChannel(channel));
  1951. return channels.tos().queryQueue(subchannel);
  1952. }
  1953. unsigned timeout(unsigned now) const
  1954. {
  1955. unsigned ret = (unsigned) -1;
  1956. ForEachItemIn(idx, channels)
  1957. {
  1958. unsigned t = channels.item(idx).timeout(now);
  1959. if (t < ret)
  1960. ret = t;
  1961. }
  1962. return ret;
  1963. }
  1964. void checkExpired(unsigned now, RoxieQueue &slaQueue, RoxieQueue &hiQueue, RoxieQueue &loQueue)
  1965. {
  1966. ForEachItemIn(idx, channels)
  1967. {
  1968. channels.item(idx).checkExpired(now, slaQueue, hiQueue, loQueue);
  1969. }
  1970. }
  1971. private:
  1972. CIArrayOf<DelayedPacketQueueChannel> channels;
  1973. };
  1974. #endif
  1975. //------------------------------------------------------------------------------------------------------------
  1976. class RoxieSocketQueueManager : public RoxieReceiverBase
  1977. {
  1978. protected:
  1979. Linked<ISendManager> sendManager;
  1980. Linked<IReceiveManager> receiveManager;
  1981. Owned<RoxieThrottledPacketSender> throttledPacketSendManager;
  1982. Owned<TokenBucket> bucket;
  1983. unsigned maxPacketSize = 0;
  1984. std::atomic<bool> running = { false };
  1985. #ifdef NEW_IBYTI
  1986. DelayedPacketQueueManager delayed;
  1987. #endif
  1988. class ReceiverThread : public Thread
  1989. {
  1990. RoxieSocketQueueManager &parent;
  1991. public:
  1992. ReceiverThread(RoxieSocketQueueManager &_parent) : Thread("RoxieSocketQueueManager"), parent(_parent) {}
  1993. int run()
  1994. {
  1995. // Raise the priority so ibyti's get through in a timely fashion
  1996. #if defined( __linux__) || defined(__APPLE__)
  1997. setLinuxThreadPriority(3);
  1998. #else
  1999. adjustPriority(1);
  2000. #endif
  2001. roxiePacketReaderThread = GetCurrentThreadId();
  2002. return parent.run();
  2003. }
  2004. } readThread;
  2005. public:
  2006. RoxieSocketQueueManager(unsigned _numWorkers) : RoxieReceiverBase(_numWorkers), readThread(*this)
  2007. {
  2008. maxPacketSize = multicastSocket->get_max_send_size();
  2009. if ((maxPacketSize==0)||(maxPacketSize>65535))
  2010. maxPacketSize = 65535;
  2011. }
  2012. virtual void sendPacket(IRoxieQueryPacket *x, const IRoxieContextLogger &logctx)
  2013. {
  2014. if (throttledPacketSendManager)
  2015. throttledPacketSendManager->sendPacket(x, logctx);
  2016. else
  2017. {
  2018. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendPacket");
  2019. RoxiePacketHeader &header = x->queryHeader();
  2020. unsigned length = x->queryHeader().packetlength;
  2021. assertex (header.activityId & ~ROXIE_PRIORITY_MASK);
  2022. StringBuffer s;
  2023. switch (header.retries & ROXIE_RETRIES_MASK)
  2024. {
  2025. case (QUERY_ABORTED & ROXIE_RETRIES_MASK):
  2026. logctx.CTXLOG("Aborting packet size=%d: %s", length, header.toString(s).str());
  2027. break;
  2028. default:
  2029. logctx.CTXLOG("Resending packet size=%d: %s", length, header.toString(s).str());
  2030. break;
  2031. case 0:
  2032. if (logctx.queryTraceLevel() > 8)
  2033. logctx.CTXLOG("Sending packet size=%d: %s", length, header.toString(s).str());
  2034. break;
  2035. }
  2036. if (length > maxPacketSize)
  2037. {
  2038. StringBuffer s;
  2039. throw MakeStringException(ROXIE_PACKET_ERROR, "Maximum packet length %d exceeded sending packet %s", maxPacketSize, header.toString(s).str());
  2040. }
  2041. if (!channelWrite(header, true))
  2042. logctx.CTXLOG("Roxie packet write wrote too little");
  2043. packetsSent++;
  2044. }
  2045. }
  2046. virtual void sendIbyti(RoxiePacketHeader &header, const IRoxieContextLogger &logctx, unsigned subChannel) override
  2047. {
  2048. #ifdef SUBCHANNELS_IN_HEADER
  2049. if (!header.hasBuddies())
  2050. return;
  2051. #endif
  2052. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendIbyti");
  2053. RoxiePacketHeader ibytiHeader(header, header.activityId & ROXIE_PRIORITY_MASK, subChannel);
  2054. if (logctx.queryTraceLevel() > 8)
  2055. {
  2056. StringBuffer s; logctx.CTXLOG("Sending IBYTI packet %s", ibytiHeader.toString(s).str());
  2057. }
  2058. channelWrite(ibytiHeader, false); // don't send to self
  2059. ibytiPacketsSent++;
  2060. }
  2061. virtual void sendAbort(RoxiePacketHeader &header, const IRoxieContextLogger &logctx) override
  2062. {
  2063. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendAbort");
  2064. RoxiePacketHeader abortHeader(header, header.activityId & ROXIE_PRIORITY_MASK, 0); // subChannel irrelevant - we are about to overwrite retries anyway
  2065. abortHeader.retries = QUERY_ABORTED;
  2066. if (logctx.queryTraceLevel() > 8)
  2067. {
  2068. StringBuffer s; logctx.CTXLOG("Sending ABORT packet %s", abortHeader.toString(s).str());
  2069. }
  2070. if (!channelWrite(abortHeader, true))
  2071. logctx.CTXLOG("sendAbort wrote too little");
  2072. abortsSent++;
  2073. }
  2074. virtual void sendAbortCallback(const RoxiePacketHeader &header, const char *lfn, const IRoxieContextLogger &logctx) override
  2075. {
  2076. MTIME_SECTION(queryActiveTimer(), "RoxieSocketQueueManager::sendAbortCallback");
  2077. RoxiePacketHeader abortHeader(header, ROXIE_FILECALLBACK, 0); // subChannel irrelevant - we are about to overwrite retries anyway
  2078. abortHeader.retries = QUERY_ABORTED;
  2079. abortHeader.packetlength += strlen(lfn)+1;
  2080. MemoryBuffer data;
  2081. data.append(sizeof(abortHeader), &abortHeader).append(lfn);
  2082. if (logctx.queryTraceLevel() > 5)
  2083. {
  2084. StringBuffer s; logctx.CTXLOG("Sending ABORT FILECALLBACK packet %s for file %s", abortHeader.toString(s).str(), lfn);
  2085. }
  2086. if (!channelWrite(*(RoxiePacketHeader *) data.toByteArray(), true))
  2087. logctx.CTXLOG("sendAbortCallback wrote too little");
  2088. abortsSent++;
  2089. }
  2090. virtual IMessagePacker *createOutputStream(RoxiePacketHeader &header, bool outOfBand, const IRoxieContextLogger &logctx)
  2091. {
  2092. unsigned qnum = outOfBand ? 0 : ((header.retries & ROXIE_FASTLANE) || !fastLaneQueue) ? 1 : 2;
  2093. if (logctx.queryTraceLevel() > 8)
  2094. {
  2095. StringBuffer s; logctx.CTXLOG("Creating Output Stream for reply packet on Q=%d - %s", qnum, header.toString(s).str());
  2096. }
  2097. return sendManager->createMessagePacker(header.uid, header.getSequenceId(), &header, sizeof(RoxiePacketHeader), header.serverId, qnum);
  2098. }
  2099. virtual bool replyPending(RoxiePacketHeader &header)
  2100. {
  2101. return sendManager->dataQueued(header.uid, header.getSequenceId(), header.serverId);
  2102. }
  2103. virtual bool abortCompleted(RoxiePacketHeader &header)
  2104. {
  2105. return sendManager->abortData(header.uid, header.getSequenceId(), header.serverId);
  2106. }
  2107. bool abortRunning(RoxiePacketHeader &header, RoxieQueue &queue, bool checkRank, bool &preActivity)
  2108. {
  2109. bool queryFound = false;
  2110. bool ret = false;
  2111. Owned<IPooledThreadIterator> wi = queue.running();
  2112. ForEach(*wi)
  2113. {
  2114. CRoxieWorker &w = (CRoxieWorker &) wi->query();
  2115. if (w.checkAbort(header, checkRank, queryFound, preActivity))
  2116. {
  2117. ret = true;
  2118. break;
  2119. }
  2120. else if (queryFound)
  2121. {
  2122. ret = false;
  2123. break;
  2124. }
  2125. }
  2126. if (!checkRank)
  2127. {
  2128. if (traceLevel > 8)
  2129. DBGLOG("discarding data for aborted query");
  2130. ROQ->abortCompleted(header);
  2131. }
  2132. return ret;
  2133. }
  2134. void doIbyti(RoxiePacketHeader &header, RoxieQueue &queue)
  2135. {
  2136. assert(!localAgent);
  2137. bool preActivity = false;
  2138. #ifdef SUBCHANNELS_IN_HEADER
  2139. unsigned mySubChannel = header.mySubChannel();
  2140. #else
  2141. Owned<const ITopologyServer> topology = getTopology();
  2142. const ChannelInfo &channelInfo = topology->queryChannelInfo(header.channel);
  2143. unsigned mySubChannel = channelInfo.subChannel();
  2144. #endif
  2145. if (header.retries == QUERY_ABORTED)
  2146. {
  2147. bool foundInQ = false;
  2148. #ifdef NEW_IBYTI
  2149. foundInQ = mySubChannel != 0 && delayed.queryQueue(header.channel, mySubChannel).doIBYTI(header);
  2150. #endif
  2151. if (!foundInQ)
  2152. foundInQ = queue.remove(header);
  2153. if (!foundInQ)
  2154. abortRunning(header, queue, false, preActivity);
  2155. if (traceRoxiePackets || traceLevel > 10)
  2156. {
  2157. StringBuffer s;
  2158. DBGLOG("Abort activity %s", header.toString(s).str());
  2159. }
  2160. }
  2161. else
  2162. {
  2163. ibytiPacketsReceived++;
  2164. unsigned subChannel = header.getRespondingSubChannel();
  2165. if (subChannel == mySubChannel)
  2166. {
  2167. if (traceRoxiePackets || traceLevel > 10)
  2168. DBGLOG("doIBYTI packet was from self");
  2169. ibytiPacketsFromSelf++;
  2170. }
  2171. else
  2172. {
  2173. #ifndef SUBCHANNELS_IN_HEADER
  2174. channelInfo.noteChannelHealthy(subChannel);
  2175. #else
  2176. noteNodeHealthy(header.subChannels[subChannel]);
  2177. #endif
  2178. bool foundInQ = false;
  2179. #ifdef NEW_IBYTI
  2180. foundInQ = mySubChannel != 0 && delayed.queryQueue(header.channel, mySubChannel).doIBYTI(header);
  2181. #endif
  2182. if (!foundInQ)
  2183. foundInQ = queue.remove(header);
  2184. if (foundInQ)
  2185. {
  2186. if (traceRoxiePackets || traceLevel > 10)
  2187. {
  2188. StringBuffer s;
  2189. DBGLOG("Removed activity from Q : %s", header.toString(s).str());
  2190. }
  2191. ibytiPacketsWorked++;
  2192. return;
  2193. }
  2194. if (abortRunning(header, queue, true, preActivity))
  2195. {
  2196. if (traceRoxiePackets || traceLevel > 10)
  2197. {
  2198. StringBuffer s;
  2199. DBGLOG("Aborted running activity : %s", header.toString(s).str());
  2200. }
  2201. if (preActivity)
  2202. ibytiPacketsWorked++;
  2203. else
  2204. ibytiPacketsHalfWorked++;
  2205. return;
  2206. }
  2207. if (traceRoxiePackets || traceLevel > 10)
  2208. {
  2209. StringBuffer s;
  2210. DBGLOG("doIBYTI packet was too late (or too early) : %s", header.toString(s).str());
  2211. }
  2212. ibytiPacketsTooLate++; // meaning either I started and reserve the right to finish, or I finished already
  2213. if (IBYTIbufferSize)
  2214. queue.noteOrphanIBYTI(header);
  2215. }
  2216. }
  2217. }
  2218. void processMessage(MemoryBuffer &mb, RoxiePacketHeader &header, RoxieQueue &queue)
  2219. {
  2220. // 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
  2221. // DO NOT put tracing on this thread except at very high tracelevels!
  2222. if ((header.activityId & ~ROXIE_PRIORITY_MASK) == 0)
  2223. doIbyti(header, queue);
  2224. else
  2225. {
  2226. if (!header.channel)
  2227. {
  2228. // Turn broadcast packet (channel 0), as early as possible, into non-0 channel packets.
  2229. // So retries and other communication with Roxie server (which uses non-0 channel numbers) will not cause double work or confusion.
  2230. // Unfortunately this is bad news for dropping packets
  2231. // In SUBCHANNELS_IN_HEADER mode this translation has been done on server before sending, except for some control messages like PING or UNLOAD
  2232. Owned<const ITopologyServer> topology = getTopology();
  2233. const std::vector<unsigned> channels = topology->queryChannels();
  2234. Owned<IRoxieQueryPacket> packet = createRoxiePacket(mb);
  2235. for (unsigned i = 1; i < channels.size(); i++)
  2236. queue.enqueue(packet->clonePacket(channels[i]));
  2237. header.channel = channels[0];
  2238. queue.enqueue(packet.getClear());
  2239. return;
  2240. }
  2241. #ifdef SUBCHANNELS_IN_HEADER
  2242. unsigned mySubchannel = header.mySubChannel();
  2243. #else
  2244. Owned<const ITopologyServer> topology = getTopology();
  2245. unsigned mySubchannel = topology->queryChannelInfo(header.channel).subChannel();
  2246. #endif
  2247. if (header.activityId == ROXIE_FILECALLBACK || header.activityId == ROXIE_DEBUGCALLBACK )
  2248. {
  2249. Owned<IRoxieQueryPacket> packet = createRoxiePacket(mb);
  2250. if (traceLevel > 10)
  2251. {
  2252. StringBuffer s;
  2253. DBGLOG("ROXIE_CALLBACK %s", header.toString(s).str());
  2254. }
  2255. doFileCallback(packet);
  2256. }
  2257. else if (IBYTIbufferSize && queue.lookupOrphanIBYTI(header))
  2258. {
  2259. if (traceRoxiePackets || traceLevel > 10)
  2260. {
  2261. StringBuffer s;
  2262. DBGLOG("doIBYTI packet was too early : %s", header.toString(s).str());
  2263. }
  2264. ibytiPacketsTooLate--;
  2265. ibytiPacketsTooEarly++;
  2266. }
  2267. else
  2268. {
  2269. Owned<IRoxieQueryPacket> packet = createRoxiePacket(mb);
  2270. AgentContextLogger logctx(packet);
  2271. unsigned retries = header.thisChannelRetries(mySubchannel);
  2272. if (retries)
  2273. {
  2274. // MORE - is this fast enough? By the time I am seeing retries I may already be under load. Could move onto a separate thread
  2275. assertex(header.channel); // should never see a retry on channel 0
  2276. if (retries >= SUBCHANNEL_MASK)
  2277. return; // someone sent a failure or something - ignore it
  2278. // Send back an out-of-band immediately, to let Roxie server know that channel is still active
  2279. if (!(testAgentFailure & 0x800))
  2280. {
  2281. RoxiePacketHeader newHeader(header, ROXIE_ALIVE, mySubchannel);
  2282. Owned<IMessagePacker> output = ROQ->createOutputStream(newHeader, true, logctx);
  2283. output->flush();
  2284. }
  2285. // If it's a retry, look it up against already running, or output stream, or input queue
  2286. // if found, send an IBYTI and discard retry request
  2287. if (!mySubchannel)
  2288. retriesReceivedPrm++;
  2289. else
  2290. retriesReceivedSec++;
  2291. bool alreadyRunning = false;
  2292. Owned<IPooledThreadIterator> wi = queue.running();
  2293. ForEach(*wi)
  2294. {
  2295. CRoxieWorker &w = (CRoxieWorker &) wi->query();
  2296. if (w.match(header))
  2297. {
  2298. alreadyRunning = true;
  2299. if (!mySubchannel)
  2300. retriesIgnoredPrm++;
  2301. else
  2302. retriesIgnoredSec++;
  2303. ROQ->sendIbyti(header, logctx, mySubchannel);
  2304. if (logctx.queryTraceLevel() > 10)
  2305. {
  2306. StringBuffer xx; logctx.CTXLOG("Ignored retry on subchannel %u for running activity %s", mySubchannel, header.toString(xx).str());
  2307. }
  2308. break;
  2309. }
  2310. }
  2311. if (!alreadyRunning && checkCompleted && ROQ->replyPending(header))
  2312. {
  2313. alreadyRunning = true;
  2314. if (!mySubchannel)
  2315. retriesIgnoredPrm++;
  2316. else
  2317. retriesIgnoredSec++;
  2318. ROQ->sendIbyti(header, logctx, mySubchannel);
  2319. if (logctx.queryTraceLevel() > 10)
  2320. {
  2321. StringBuffer xx; logctx.CTXLOG("Ignored retry on subchannel %u for completed activity %s", mySubchannel, header.toString(xx).str());
  2322. }
  2323. }
  2324. if (!alreadyRunning)
  2325. {
  2326. if (logctx.queryTraceLevel() > 10)
  2327. {
  2328. StringBuffer xx; logctx.CTXLOG("Retry %d received on subchannel %u for %s", retries+1, mySubchannel, header.toString(xx).str());
  2329. }
  2330. queue.enqueueUnique(packet.getClear(), mySubchannel);
  2331. }
  2332. }
  2333. else // first time (not a retry).
  2334. {
  2335. #ifdef NEW_IBYTI
  2336. if (mySubchannel != 0) // i.e. I am not the primary here
  2337. {
  2338. unsigned delay = 0;
  2339. for (unsigned subChannel = 0; subChannel < mySubchannel; subChannel++)
  2340. delay += getIbytiDelay(header.subChannels[subChannel]);
  2341. delayed.queryQueue(header.channel, mySubchannel).append(packet.getClear(), msTick()+delay);
  2342. }
  2343. else
  2344. #endif
  2345. queue.enqueue(packet.getClear());
  2346. }
  2347. }
  2348. }
  2349. }
  2350. int run()
  2351. {
  2352. if (traceLevel)
  2353. DBGLOG("RoxieSocketQueueManager::run() starting: doIbytiDelay=%s minIbytiDelay=%u initIbytiDelay=%u",
  2354. doIbytiDelay?"YES":"NO", minIbytiDelay, initIbytiDelay);
  2355. for (;;)
  2356. {
  2357. MemoryBuffer mb;
  2358. try
  2359. {
  2360. // 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
  2361. // DO NOT put tracing on this thread except at very high tracelevels!
  2362. #ifdef NEW_IBYTI
  2363. unsigned timeout = delayed.timeout(msTick());
  2364. if (timeout>5000)
  2365. timeout = 5000;
  2366. #else
  2367. unsigned timeout = 5000;
  2368. #endif
  2369. unsigned l;
  2370. multicastSocket->readtms(mb.reserve(maxPacketSize), sizeof(RoxiePacketHeader), maxPacketSize, l, timeout);
  2371. mb.setLength(l);
  2372. packetsReceived++;
  2373. RoxiePacketHeader &header = *(RoxiePacketHeader *) mb.toByteArray();
  2374. if (l != header.packetlength)
  2375. DBGLOG("sock->read returned %d but packetlength was %d", l, header.packetlength);
  2376. if (traceRoxiePackets || traceLevel > 10)
  2377. {
  2378. StringBuffer s;
  2379. DBGLOG("Read roxie packet: %s", header.toString(s).str());
  2380. }
  2381. if (header.activityId & ROXIE_SLA_PRIORITY)
  2382. processMessage(mb, header, slaQueue);
  2383. else if (header.activityId & ROXIE_HIGH_PRIORITY)
  2384. processMessage(mb, header, hiQueue);
  2385. else
  2386. processMessage(mb, header, loQueue);
  2387. }
  2388. catch (IException *E)
  2389. {
  2390. if (running)
  2391. {
  2392. // MORE: Maybe we should utilize IException::errorCode - not just text ??
  2393. if (E->errorCode()==JSOCKERR_timeout_expired)
  2394. E->Release();
  2395. else if (roxiemem::memPoolExhausted())
  2396. {
  2397. //MORE: I think this should probably be based on the error code instead.
  2398. EXCLOG(E, "Exception reading or processing roxie packet");
  2399. E->Release();
  2400. MilliSleep(1000); // Give a chance for mem free
  2401. }
  2402. else
  2403. {
  2404. EXCLOG(E, "Exception reading or processing roxie packet");
  2405. E->Release();
  2406. // MORE: Protect with try logic, in case udp_create throws exception ?
  2407. // What to do if create fails (ie exception is caught) ?
  2408. if (multicastSocket)
  2409. {
  2410. multicastSocket->close();
  2411. multicastSocket.clear();
  2412. openMulticastSocket();
  2413. }
  2414. }
  2415. }
  2416. else
  2417. {
  2418. E->Release();
  2419. break;
  2420. }
  2421. }
  2422. #ifdef NEW_IBYTI
  2423. delayed.checkExpired(msTick(), slaQueue, hiQueue, loQueue);
  2424. #endif
  2425. }
  2426. return 0;
  2427. }
  2428. void start()
  2429. {
  2430. RoxieReceiverBase::start();
  2431. running = true;
  2432. readThread.start();
  2433. }
  2434. void stop()
  2435. {
  2436. if (running)
  2437. {
  2438. running = false;
  2439. multicastSocket->close();
  2440. }
  2441. RoxieReceiverBase::stop();
  2442. }
  2443. void join()
  2444. {
  2445. readThread.join();
  2446. RoxieReceiverBase::join();
  2447. }
  2448. virtual IReceiveManager *queryReceiveManager()
  2449. {
  2450. return receiveManager;
  2451. }
  2452. };
  2453. class RoxieUdpSocketQueueManager : public RoxieSocketQueueManager
  2454. {
  2455. public:
  2456. RoxieUdpSocketQueueManager(unsigned snifferChannel, unsigned _numWorkers) : RoxieSocketQueueManager(_numWorkers)
  2457. {
  2458. int udpQueueSize = topology->getPropInt("@udpQueueSize", UDP_QUEUE_SIZE);
  2459. int udpSendQueueSize = topology->getPropInt("@udpSendQueueSize", UDP_SEND_QUEUE_SIZE);
  2460. int udpMaxSlotsPerClient = topology->getPropInt("@udpMaxSlotsPerClient", 0x7fffffff);
  2461. if (topology->getPropInt("@sendMaxRate", 0))
  2462. {
  2463. unsigned sendMaxRate = topology->getPropInt("@sendMaxRate");
  2464. unsigned sendMaxRatePeriod = topology->getPropInt("@sendMaxRatePeriod", 1);
  2465. bucket.setown(new TokenBucket(sendMaxRate, sendMaxRatePeriod, sendMaxRate));
  2466. throttledPacketSendManager.setown(new RoxieThrottledPacketSender(*bucket, maxPacketSize));
  2467. }
  2468. IpAddress snifferIp;
  2469. getChannelIp(snifferIp, snifferChannel);
  2470. if (udpMaxSlotsPerClient > udpQueueSize)
  2471. udpMaxSlotsPerClient = udpQueueSize;
  2472. unsigned serverFlowPort = topology->getPropInt("@serverFlowPort", CCD_SERVER_FLOW_PORT);
  2473. unsigned dataPort = topology->getPropInt("@dataPort", CCD_DATA_PORT);
  2474. unsigned clientFlowPort = topology->getPropInt("@clientFlowPort", CCD_CLIENT_FLOW_PORT);
  2475. unsigned snifferPort = topology->getPropInt("@snifferPort", CCD_SNIFFER_PORT);
  2476. receiveManager.setown(createReceiveManager(serverFlowPort, dataPort, clientFlowPort, snifferPort, snifferIp, udpQueueSize, udpMaxSlotsPerClient));
  2477. sendManager.setown(createSendManager(serverFlowPort, dataPort, clientFlowPort, snifferPort, snifferIp, udpSendQueueSize, fastLaneQueue ? 3 : 2, bucket));
  2478. }
  2479. };
  2480. class RoxieAeronSocketQueueManager : public RoxieSocketQueueManager
  2481. {
  2482. public:
  2483. RoxieAeronSocketQueueManager(unsigned _numWorkers) : RoxieSocketQueueManager(_numWorkers)
  2484. {
  2485. unsigned dataPort = topology->getPropInt("@dataPort", CCD_DATA_PORT);
  2486. SocketEndpoint ep(dataPort, myNode.getIpAddress());
  2487. receiveManager.setown(createAeronReceiveManager(ep));
  2488. assertex(!myNode.getIpAddress().isNull());
  2489. sendManager.setown(createAeronSendManager(dataPort, fastLaneQueue ? 3 : 2, myNode.getIpAddress()));
  2490. }
  2491. };
  2492. #ifdef _MSC_VER
  2493. #pragma warning( pop )
  2494. #endif
  2495. //==================================================================================================
  2496. interface ILocalMessageCollator : extends IMessageCollator
  2497. {
  2498. virtual void enqueueMessage(bool outOfBand, void *data, unsigned datalen, void *meta, unsigned metalen, void *header, unsigned headerlen) = 0;
  2499. };
  2500. interface ILocalReceiveManager : extends IReceiveManager
  2501. {
  2502. virtual ILocalMessageCollator *lookupCollator(ruid_t id) = 0;
  2503. };
  2504. class LocalMessagePacker : public CDummyMessagePacker
  2505. {
  2506. MemoryBuffer meta;
  2507. MemoryBuffer header;
  2508. Linked<ILocalReceiveManager> rm;
  2509. ruid_t id;
  2510. bool outOfBand;
  2511. public:
  2512. IMPLEMENT_IINTERFACE;
  2513. LocalMessagePacker(RoxiePacketHeader &_header, bool _outOfBand, ILocalReceiveManager *_rm) : rm(_rm), outOfBand(_outOfBand)
  2514. {
  2515. id = _header.uid;
  2516. header.append(sizeof(RoxiePacketHeader), &_header);
  2517. }
  2518. virtual void flush() override;
  2519. virtual void sendMetaInfo(const void *buf, unsigned len) override
  2520. {
  2521. meta.append(len, buf);
  2522. }
  2523. };
  2524. class CLocalMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2525. {
  2526. void *data;
  2527. unsigned datalen;
  2528. unsigned pos;
  2529. Linked<IRowManager> rowManager;
  2530. public:
  2531. IMPLEMENT_IINTERFACE;
  2532. CLocalMessageUnpackCursor(IRowManager *_rowManager, void *_data, unsigned _datalen)
  2533. : rowManager(_rowManager)
  2534. {
  2535. datalen = _datalen;
  2536. data = _data;
  2537. pos = 0;
  2538. }
  2539. ~CLocalMessageUnpackCursor()
  2540. {
  2541. }
  2542. virtual bool atEOF() const
  2543. {
  2544. return datalen==pos;
  2545. }
  2546. virtual bool isSerialized() const
  2547. {
  2548. // NOTE: tempting to think that we could avoid serializing in localAgent case, but have to be careful about the lifespan of the rowManager...
  2549. return true;
  2550. }
  2551. virtual const void * getNext(int length)
  2552. {
  2553. if (pos==datalen)
  2554. return NULL;
  2555. assertex(pos + length <= datalen);
  2556. void * cur = ((char *) data) + pos;
  2557. pos += length;
  2558. void * ret = rowManager->allocate(length, 0);
  2559. memcpy(ret, cur, length);
  2560. //No need for finalize since only contains plain data.
  2561. return ret;
  2562. }
  2563. };
  2564. class CLocalMessageResult : implements IMessageResult, public CInterface
  2565. {
  2566. void *data;
  2567. void *meta;
  2568. void *header;
  2569. unsigned datalen, metalen, headerlen;
  2570. unsigned pos;
  2571. public:
  2572. IMPLEMENT_IINTERFACE;
  2573. CLocalMessageResult(void *_data, unsigned _datalen, void *_meta, unsigned _metalen, void *_header, unsigned _headerlen)
  2574. {
  2575. datalen = _datalen;
  2576. metalen = _metalen;
  2577. headerlen = _headerlen;
  2578. data = _data;
  2579. meta = _meta;
  2580. header = _header;
  2581. pos = 0;
  2582. }
  2583. ~CLocalMessageResult()
  2584. {
  2585. free(data);
  2586. free(meta);
  2587. free(header);
  2588. }
  2589. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2590. {
  2591. return new CLocalMessageUnpackCursor(rowMgr, data, datalen);
  2592. }
  2593. virtual const void *getMessageHeader(unsigned &length) const
  2594. {
  2595. length = headerlen;
  2596. return header;
  2597. }
  2598. virtual const void *getMessageMetadata(unsigned &length) const
  2599. {
  2600. length = metalen;
  2601. return meta;
  2602. }
  2603. virtual void discard() const
  2604. {
  2605. }
  2606. };
  2607. class CLocalMessageCollator : implements ILocalMessageCollator, public CInterface
  2608. {
  2609. InterruptableSemaphore sem;
  2610. QueueOf<IMessageResult, false> pending;
  2611. CriticalSection crit;
  2612. Linked<IRowManager> rowManager; // Linked to ensure it lives longer than me
  2613. Linked<ILocalReceiveManager> receiveManager;
  2614. ruid_t id;
  2615. unsigned totalBytesReceived;
  2616. public:
  2617. IMPLEMENT_IINTERFACE;
  2618. CLocalMessageCollator(IRowManager *_rowManager, ruid_t _ruid);
  2619. ~CLocalMessageCollator();
  2620. virtual ruid_t queryRUID() const
  2621. {
  2622. return id;
  2623. }
  2624. virtual IMessageResult* getNextResult(unsigned time_out, bool &anyActivity)
  2625. {
  2626. anyActivity = false;
  2627. if (!sem.wait(time_out))
  2628. return NULL;
  2629. anyActivity = true;
  2630. CriticalBlock c(crit);
  2631. return pending.dequeue();
  2632. }
  2633. virtual void interrupt(IException *E)
  2634. {
  2635. sem.interrupt(E);
  2636. }
  2637. virtual void enqueueMessage(bool outOfBand, void *data, unsigned datalen, void *meta, unsigned metalen, void *header, unsigned headerlen)
  2638. {
  2639. CriticalBlock c(crit);
  2640. if (outOfBand)
  2641. pending.enqueueHead(new CLocalMessageResult(data, datalen, meta, metalen, header, headerlen));
  2642. else
  2643. pending.enqueue(new CLocalMessageResult(data, datalen, meta, metalen, header, headerlen));
  2644. sem.signal();
  2645. totalBytesReceived += datalen + metalen + headerlen;
  2646. }
  2647. virtual unsigned queryBytesReceived() const
  2648. {
  2649. return totalBytesReceived;
  2650. }
  2651. };
  2652. class RoxieLocalReceiveManager : implements ILocalReceiveManager, public CInterface
  2653. {
  2654. MapXToMyClass<ruid_t, ruid_t, ILocalMessageCollator> collators;
  2655. CriticalSection crit;
  2656. Owned<StringContextLogger> logctx;
  2657. public:
  2658. IMPLEMENT_IINTERFACE;
  2659. RoxieLocalReceiveManager() : logctx(new StringContextLogger("RoxieLocalReceiveManager"))
  2660. {
  2661. }
  2662. virtual IMessageCollator *createMessageCollator(IRowManager *manager, ruid_t ruid)
  2663. {
  2664. ILocalMessageCollator *collator = new CLocalMessageCollator(manager, ruid);
  2665. CriticalBlock b(crit);
  2666. collators.setValue(ruid, collator);
  2667. return collator;
  2668. }
  2669. virtual void detachCollator(const IMessageCollator *collator)
  2670. {
  2671. ruid_t id = collator->queryRUID();
  2672. CriticalBlock b(crit);
  2673. collators.setValue(id, NULL);
  2674. }
  2675. virtual ILocalMessageCollator *lookupCollator(ruid_t id)
  2676. {
  2677. CriticalBlock b(crit);
  2678. ILocalMessageCollator *ret = collators.getValue(id);
  2679. if (!ret)
  2680. ret = collators.getValue(RUID_DISCARD);
  2681. return LINK(ret);
  2682. }
  2683. };
  2684. void LocalMessagePacker::flush()
  2685. {
  2686. // MORE - I think this means we don't send anything until whole message available in localAgent mode, which
  2687. // may not be optimal.
  2688. data.setLength(lastput);
  2689. Owned<ILocalMessageCollator> collator = rm->lookupCollator(id);
  2690. if (collator)
  2691. {
  2692. unsigned datalen = data.length();
  2693. unsigned metalen = meta.length();
  2694. unsigned headerlen = header.length();
  2695. collator->enqueueMessage(outOfBand, data.detach(), datalen, meta.detach(), metalen, header.detach(), headerlen);
  2696. }
  2697. // otherwise Roxie server is no longer interested and we can simply discard
  2698. }
  2699. CLocalMessageCollator::CLocalMessageCollator(IRowManager *_rowManager, ruid_t _ruid)
  2700. : rowManager(_rowManager), id(_ruid)
  2701. {
  2702. totalBytesReceived = 0;
  2703. }
  2704. CLocalMessageCollator::~CLocalMessageCollator()
  2705. {
  2706. IMessageResult *goer;
  2707. for (;;)
  2708. {
  2709. goer = pending.dequeue();
  2710. if (!goer)
  2711. break;
  2712. goer->Release();
  2713. }
  2714. }
  2715. class RoxieLocalQueueManager : public RoxieReceiverBase
  2716. {
  2717. Linked<RoxieLocalReceiveManager> receiveManager;
  2718. public:
  2719. RoxieLocalQueueManager(unsigned _numWorkers) : RoxieReceiverBase(_numWorkers)
  2720. {
  2721. receiveManager.setown(new RoxieLocalReceiveManager);
  2722. }
  2723. virtual void sendPacket(IRoxieQueryPacket *packet, const IRoxieContextLogger &logctx) override
  2724. {
  2725. RoxiePacketHeader &header = packet->queryHeader();
  2726. unsigned retries = header.thisChannelRetries(0);
  2727. if (header.activityId == ROXIE_FILECALLBACK || header.activityId == ROXIE_DEBUGCALLBACK )
  2728. {
  2729. if (traceLevel > 5)
  2730. {
  2731. StringBuffer s;
  2732. DBGLOG("ROXIE_CALLBACK %s", header.toString(s).str());
  2733. }
  2734. doFileCallback(packet);
  2735. }
  2736. else if (retries < SUBCHANNEL_MASK)
  2737. {
  2738. if (retries)
  2739. {
  2740. // Send back an out-of-band immediately, to let Roxie server know that channel is still active
  2741. RoxiePacketHeader newHeader(header, ROXIE_ALIVE, 0);
  2742. Owned<IMessagePacker> output = createOutputStream(newHeader, true, logctx);
  2743. output->flush();
  2744. return; // No point sending the retry in localAgent mode
  2745. }
  2746. RoxieQueue *targetQueue;
  2747. if (header.activityId & ROXIE_SLA_PRIORITY)
  2748. targetQueue = &slaQueue;
  2749. else if (header.activityId & ROXIE_HIGH_PRIORITY)
  2750. targetQueue = &hiQueue;
  2751. else
  2752. targetQueue = &loQueue;
  2753. if (header.channel)
  2754. {
  2755. targetQueue->enqueue(LINK(packet));
  2756. }
  2757. else
  2758. {
  2759. // Turn broadcast packet (channel 0), as early as possible, into non-0 channel packets.
  2760. // So retries and other communication with Roxie server (which uses non-0 channel numbers) will not cause double work or confusion.
  2761. // In SUBCHANNELS_IN_HEADER mode this translation has been done on server before sending, except for some control messages like PING or UNLOAD
  2762. for (unsigned i = 0; i < numChannels; i++)
  2763. {
  2764. targetQueue->enqueue(packet->clonePacket(i+1));
  2765. }
  2766. }
  2767. }
  2768. }
  2769. virtual void sendIbyti(RoxiePacketHeader &header, const IRoxieContextLogger &logctx, unsigned subChannel) override
  2770. {
  2771. // Don't do IBYTI's when local agent - no buddy to talk to anyway
  2772. }
  2773. virtual void sendAbort(RoxiePacketHeader &header, const IRoxieContextLogger &logctx) override
  2774. {
  2775. MTIME_SECTION(queryActiveTimer(), "RoxieLocalQueueManager::sendAbort");
  2776. RoxiePacketHeader abortHeader(header, header.activityId & ROXIE_PRIORITY_MASK, 0);
  2777. abortHeader.retries = QUERY_ABORTED;
  2778. if (logctx.queryTraceLevel() > 8)
  2779. {
  2780. StringBuffer s; logctx.CTXLOG("Sending ABORT packet %s", abortHeader.toString(s).str());
  2781. }
  2782. MemoryBuffer data;
  2783. data.append(sizeof(abortHeader), &abortHeader);
  2784. Owned<IRoxieQueryPacket> packet = createRoxiePacket(data);
  2785. sendPacket(packet, logctx);
  2786. abortsSent++;
  2787. }
  2788. virtual void sendAbortCallback(const RoxiePacketHeader &header, const char *lfn, const IRoxieContextLogger &logctx) override
  2789. {
  2790. MTIME_SECTION(queryActiveTimer(), "RoxieLocalQueueManager::sendAbortCallback");
  2791. RoxiePacketHeader abortHeader(header, ROXIE_FILECALLBACK, 0);
  2792. abortHeader.retries = QUERY_ABORTED;
  2793. MemoryBuffer data;
  2794. data.append(sizeof(abortHeader), &abortHeader).append(lfn);
  2795. if (logctx.queryTraceLevel() > 5)
  2796. {
  2797. StringBuffer s; logctx.CTXLOG("Sending ABORT FILECALLBACK packet %s for file %s", abortHeader.toString(s).str(), lfn);
  2798. }
  2799. Owned<IRoxieQueryPacket> packet = createRoxiePacket(data);
  2800. sendPacket(packet, logctx);
  2801. abortsSent++;
  2802. }
  2803. virtual IMessagePacker *createOutputStream(RoxiePacketHeader &header, bool outOfBand, const IRoxieContextLogger &logctx) override
  2804. {
  2805. return new LocalMessagePacker(header, outOfBand, receiveManager);
  2806. }
  2807. virtual IReceiveManager *queryReceiveManager() override
  2808. {
  2809. return receiveManager;
  2810. }
  2811. virtual bool replyPending(RoxiePacketHeader &header) override
  2812. {
  2813. // MORE - should really have some code here! But returning true is a reasonable approximation.
  2814. return true;
  2815. }
  2816. virtual bool abortCompleted(RoxiePacketHeader &header) override
  2817. {
  2818. // MORE - should really have some code here!
  2819. return false;
  2820. }
  2821. };
  2822. IRoxieOutputQueueManager *ROQ;
  2823. extern IRoxieOutputQueueManager *createOutputQueueManager(unsigned snifferChannel, unsigned numWorkers)
  2824. {
  2825. if (localAgent)
  2826. return new RoxieLocalQueueManager(numWorkers);
  2827. else if (useAeron)
  2828. return new RoxieAeronSocketQueueManager(numWorkers);
  2829. else
  2830. return new RoxieUdpSocketQueueManager(snifferChannel, numWorkers);
  2831. }
  2832. //================================================================================================================================
  2833. class PacketDiscarder : public Thread, implements IPacketDiscarder
  2834. {
  2835. bool aborted;
  2836. Owned<IRowManager> rowManager; // not completely sure I need one... maybe I do
  2837. Owned<IMessageCollator> mc;
  2838. public:
  2839. IMPLEMENT_IINTERFACE;
  2840. PacketDiscarder()
  2841. {
  2842. aborted = false;
  2843. };
  2844. ~PacketDiscarder()
  2845. {
  2846. if (mc)
  2847. ROQ->queryReceiveManager()->detachCollator(mc);
  2848. mc.clear();
  2849. }
  2850. virtual int run()
  2851. {
  2852. Owned<StringContextLogger> logctx = new StringContextLogger("PacketDiscarder");
  2853. rowManager.setown(roxiemem::createRowManager(0, NULL, *logctx, NULL, false));
  2854. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, RUID_DISCARD));
  2855. try
  2856. {
  2857. while (!aborted)
  2858. {
  2859. bool anyActivity = false;
  2860. Owned<IMessageResult> mr = mc->getNextResult(5000, anyActivity);
  2861. if (mr)
  2862. {
  2863. if (traceLevel > 4)
  2864. DBGLOG("Discarding unwanted message");
  2865. unsigned headerLen;
  2866. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(headerLen);
  2867. if (headerLen)
  2868. {
  2869. switch (header.activityId)
  2870. {
  2871. case ROXIE_FILECALLBACK:
  2872. {
  2873. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  2874. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  2875. if (len)
  2876. {
  2877. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  2878. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  2879. const char *rowdata = (const char *) row.get();
  2880. // bool isOpt = * (bool *) rowdata;
  2881. // bool isLocal = * (bool *) (rowdata+1);
  2882. ROQ->sendAbortCallback(header, rowdata+2, *logctx);
  2883. }
  2884. else
  2885. DBGLOG("Unrecognized format in discarded file callback");
  2886. break;
  2887. }
  2888. // 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)
  2889. }
  2890. }
  2891. else
  2892. DBGLOG("Unwanted message had no header?!");
  2893. }
  2894. else if (!anyActivity)
  2895. {
  2896. // to avoid leaking partial unwanted packets, we clear out mc periodically...
  2897. ROQ->queryReceiveManager()->detachCollator(mc);
  2898. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, RUID_DISCARD));
  2899. }
  2900. }
  2901. }
  2902. catch (IException * E)
  2903. {
  2904. if (!aborted || QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  2905. EXCLOG(E);
  2906. ::Release(E);
  2907. }
  2908. return 0;
  2909. }
  2910. virtual void start()
  2911. {
  2912. Thread::start();
  2913. }
  2914. virtual void stop()
  2915. {
  2916. if (mc)
  2917. mc->interrupt();
  2918. aborted = true;
  2919. join();
  2920. }
  2921. };
  2922. IPacketDiscarder *createPacketDiscarder()
  2923. {
  2924. IPacketDiscarder *packetDiscarder = new PacketDiscarder;
  2925. packetDiscarder->start();
  2926. return packetDiscarder;
  2927. }
  2928. //================================================================================================================================
  2929. // There are various possibly interesting ways to reply to a ping:
  2930. // Reply as soon as receive, or put it on the queue like other messages?
  2931. // Reply for every channel, or just once for every agent?
  2932. // Should I send on channel 0 or round-robin the channels?
  2933. // My gut feeling is that knowing what channels are responding is useful so should reply on every unsuspended channel,
  2934. // 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)
  2935. unsigned pingInterval = 60;
  2936. class PingTimer : public Thread
  2937. {
  2938. bool aborted;
  2939. Owned<IRowManager> rowManager;
  2940. Owned<IMessageCollator> mc;
  2941. StringContextLogger logctx;
  2942. void sendPing(unsigned priorityMask)
  2943. {
  2944. try
  2945. {
  2946. unsigned packetSize = sizeof(RoxiePacketHeader) + sizeof(char) + strlen("PING") + 1 + sizeof(PingRecord);
  2947. void *packetData = malloc(packetSize);
  2948. RoxiePacketHeader *header = (RoxiePacketHeader *) packetData;
  2949. RemoteActivityId pingId(ROXIE_PING | priorityMask, 0);
  2950. header->init(pingId, 0, 0, 0);
  2951. char *finger = (char *) (header + 1);
  2952. *finger++ = (char) LOGGING_FLAGSPRESENT;
  2953. strcpy(finger, "PING");
  2954. finger += strlen("PING")+1;
  2955. if (traceLevel > 1)
  2956. DBGLOG("PING sent");
  2957. PingRecord data;
  2958. data.senderIP.ipset(myNode.getIpAddress());
  2959. data.tick = usTick();
  2960. memcpy(finger, &data, sizeof(PingRecord));
  2961. Owned<IRoxieQueryPacket> packet = createRoxiePacket(packetData, packetSize);
  2962. ROQ->sendPacket(packet, logctx);
  2963. }
  2964. catch (IException *E)
  2965. {
  2966. EXCLOG(E);
  2967. E->Release();
  2968. }
  2969. }
  2970. public:
  2971. PingTimer() : logctx("PingTimer")
  2972. {
  2973. aborted = false;
  2974. };
  2975. ~PingTimer()
  2976. {
  2977. if (mc)
  2978. ROQ->queryReceiveManager()->detachCollator(mc);
  2979. mc.clear();
  2980. }
  2981. virtual int run()
  2982. {
  2983. rowManager.setown(roxiemem::createRowManager(1, NULL, queryDummyContextLogger(), NULL, false));
  2984. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, RUID_PING));
  2985. unsigned pingsReceived = 0;
  2986. unsigned pingsElapsed = 0;
  2987. sendPing(ROXIE_HIGH_PRIORITY);
  2988. while (!aborted)
  2989. {
  2990. bool anyActivity = false;
  2991. Owned<IMessageResult> mr = mc->getNextResult(pingInterval*1000, anyActivity);
  2992. if (mr)
  2993. {
  2994. unsigned headerLen;
  2995. const RoxiePacketHeader *header = (const RoxiePacketHeader *) mr->getMessageHeader(headerLen);
  2996. Owned<IMessageUnpackCursor> mu = mr->getCursor(rowManager);
  2997. PingRecord *answer = (PingRecord *) mu->getNext(sizeof(PingRecord));
  2998. if (answer && mu->atEOF() && headerLen==sizeof(RoxiePacketHeader))
  2999. {
  3000. unsigned elapsed = usTick() - answer->tick;
  3001. pingsReceived++;
  3002. pingsElapsed += elapsed;
  3003. if (traceLevel > 10)
  3004. DBGLOG("PING reply channel=%d, time %d", header->channel, elapsed); // DBGLOG is slower than the pings so be careful!
  3005. }
  3006. else
  3007. DBGLOG("PING reply, garbled result");
  3008. ReleaseRoxieRow(answer);
  3009. }
  3010. else if (!anyActivity)
  3011. {
  3012. if (!pingsReceived && roxieMulticastEnabled)
  3013. DBGLOG("PING: NO replies received! Please check multicast settings, and that your network supports multicast.");
  3014. else if (traceLevel)
  3015. DBGLOG("PING: %d replies received, average delay %uus", pingsReceived, pingsReceived ? pingsElapsed / pingsReceived : 0);
  3016. pingsReceived = 0;
  3017. pingsElapsed = 0;
  3018. sendPing(ROXIE_HIGH_PRIORITY); // MORE - we could think about alternating the priority or sending pings on high and low at the same time...
  3019. }
  3020. }
  3021. return 0;
  3022. }
  3023. void stop()
  3024. {
  3025. if (mc)
  3026. mc->interrupt();
  3027. aborted = true;
  3028. }
  3029. static CriticalSection crit;
  3030. } *pingTimer;
  3031. CriticalSection PingTimer::crit;
  3032. extern void startPingTimer()
  3033. {
  3034. CriticalBlock b(PingTimer::crit);
  3035. if (!pingTimer)
  3036. {
  3037. pingTimer = new PingTimer();
  3038. pingTimer->start();
  3039. }
  3040. }
  3041. extern void stopPingTimer()
  3042. {
  3043. CriticalBlock b(PingTimer::crit);
  3044. if (pingTimer)
  3045. {
  3046. pingTimer->stop();
  3047. pingTimer->join();
  3048. delete pingTimer;
  3049. pingTimer = NULL;
  3050. }
  3051. }