ccdqueue.cpp 100 KB

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