ccdqueue.cpp 96 KB

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