jstats.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440
  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 "jiface.hpp"
  14. #include "jstats.h"
  15. #include "jexcept.hpp"
  16. #include "jiter.ipp"
  17. #include "jlog.hpp"
  18. #include "jregexp.hpp"
  19. #include "jfile.hpp"
  20. #include "jerror.hpp"
  21. #include <math.h>
  22. #ifdef _WIN32
  23. #include <sys/timeb.h>
  24. #endif
  25. static CriticalSection statsNameCs;
  26. static StringBuffer statisticsComponentName;
  27. static StatisticCreatorType statisticsComponentType = SCTunknown;
  28. const static unsigned currentStatisticsVersion = 1;
  29. StatisticCreatorType queryStatisticsComponentType()
  30. {
  31. return statisticsComponentType;
  32. }
  33. const char * queryStatisticsComponentName()
  34. {
  35. CriticalBlock c(statsNameCs);
  36. if (statisticsComponentName.length() == 0)
  37. {
  38. statisticsComponentName.append("unknown").append(GetCachedHostName());
  39. DBGLOG("getProcessUniqueName hasn't been configured correctly");
  40. }
  41. return statisticsComponentName.str();
  42. }
  43. void setStatisticsComponentName(StatisticCreatorType processType, const char * processName, bool appendIP)
  44. {
  45. if (!processName)
  46. return;
  47. CriticalBlock c(statsNameCs);
  48. statisticsComponentType = processType;
  49. statisticsComponentName.clear().append(processName);
  50. if (appendIP)
  51. statisticsComponentName.append("@").append(GetCachedHostName()); // should I use _ instead?
  52. }
  53. //--------------------------------------------------------------------------------------------------------------------
  54. // Textual forms of the different enumerations, first items are for none and all.
  55. static constexpr const char * const measureNames[] = { "", "all", "ns", "ts", "cnt", "sz", "cpu", "skw", "node", "ppm", "ip", "cy", "en", "txt", "bool", "id", "fname", NULL };
  56. static constexpr const char * const creatorTypeNames[]= { "", "all", "unknown", "hthor", "roxie", "roxie:s", "thor", "thor:m", "thor:s", "eclcc", "esp", "summary", NULL };
  57. static constexpr const char * const scopeTypeNames[] = { "", "all", "global", "graph", "subgraph", "activity", "allocator", "section", "compile", "dfu", "edge", "function", "workflow", "child", "unknown", nullptr };
  58. static unsigned matchString(const char * const * names, const char * search, unsigned dft)
  59. {
  60. if (!search)
  61. return dft;
  62. if (streq(search, "*"))
  63. search = "all";
  64. unsigned i=0;
  65. for (;;)
  66. {
  67. const char * next = names[i];
  68. if (!next)
  69. return dft;
  70. if (strieq(next, search))
  71. return i;
  72. i++;
  73. }
  74. }
  75. //--------------------------------------------------------------------------------------------------------------------
  76. static const StatisticScopeType scoreOrder[] = {
  77. SSTedge,
  78. SSTactivity,
  79. SSTnone,
  80. SSTall,
  81. SSTglobal,
  82. SSTgraph,
  83. SSTsubgraph,
  84. SSTallocator,
  85. SSTsection,
  86. SSTcompilestage,
  87. SSTdfuworkunit,
  88. SSTfunction,
  89. SSTworkflow,
  90. SSTchildgraph,
  91. SSTunknown
  92. };
  93. static int scopePriority[SSTmax];
  94. MODULE_INIT(INIT_PRIORITY_STANDARD)
  95. {
  96. static_assert(_elements_in(scoreOrder) == SSTmax, "Elements missing from scoreOrder[]");
  97. for (unsigned i=0; i < _elements_in(scoreOrder); i++)
  98. scopePriority[scoreOrder[i]] = i;
  99. return true;
  100. }
  101. extern jlib_decl int compareScopeName(const char * left, const char * right)
  102. {
  103. if (!*left)
  104. {
  105. if (!*right)
  106. return 0;
  107. else
  108. return -1;
  109. }
  110. else
  111. {
  112. if (!*right)
  113. return +1;
  114. }
  115. StatsScopeId leftId;
  116. StatsScopeId rightId;
  117. for(;;)
  118. {
  119. leftId.extractScopeText(left, &left);
  120. rightId.extractScopeText(right, &right);
  121. int result = leftId.compare(rightId);
  122. if (result != 0)
  123. return result;
  124. left = strchr(left, ':');
  125. right = strchr(right, ':');
  126. if (!left || !right)
  127. {
  128. if (left)
  129. return +1;
  130. if (right)
  131. return -1;
  132. return 0;
  133. }
  134. left++;
  135. right++;
  136. }
  137. }
  138. //--------------------------------------------------------------------------------------------------------------------
  139. extern jlib_decl unsigned __int64 getTimeStampNowValue()
  140. {
  141. #ifdef _WIN32
  142. struct _timeb now;
  143. _ftime(&now);
  144. return (unsigned __int64)now.time * I64C(1000000) + now.millitm * 1000;
  145. #else
  146. struct timeval tm;
  147. gettimeofday(&tm,NULL);
  148. return (unsigned __int64)tm.tv_sec * I64C(1000000) + tm.tv_usec;
  149. #endif
  150. }
  151. const static unsigned __int64 msUntilResync = 1000; // resync every second ~= 1ms accuracy
  152. static cycle_t cyclesUntilResync;
  153. MODULE_INIT(INIT_PRIORITY_STANDARD)
  154. {
  155. cyclesUntilResync = nanosec_to_cycle(msUntilResync * 1000000);
  156. return true;
  157. }
  158. OptimizedTimestamp::OptimizedTimestamp()
  159. {
  160. lastCycles = get_cycles_now();
  161. lastTimestamp = ::getTimeStampNowValue();
  162. }
  163. #if 0
  164. //This version almost certainly has problems if the computer is suspended and cycles->nanoseconds is only accurate to
  165. //about 0.1% - so should only be used for relatively short periods
  166. unsigned __int64 OptimizedTimestamp::getTimeStampNowValue()
  167. {
  168. cycle_t nowCycles = get_cycles_now();
  169. return lastTimestamp + cycle_to_microsec(nowCycles - lastCycles);
  170. }
  171. #else
  172. //This version will resync every minute, but is not thread safe. Adding a critical section makes it less efficient than recalculating
  173. unsigned __int64 OptimizedTimestamp::getTimeStampNowValue()
  174. {
  175. cycle_t nowCycles = get_cycles_now();
  176. if (nowCycles - lastCycles > cyclesUntilResync)
  177. {
  178. lastCycles = nowCycles;
  179. lastTimestamp = ::getTimeStampNowValue();
  180. }
  181. return lastTimestamp + cycle_to_microsec(nowCycles - lastCycles);
  182. }
  183. #endif
  184. unsigned __int64 getIPV4StatsValue(const IpAddress & ip)
  185. {
  186. unsigned ipValue;
  187. if (ip.getNetAddress(sizeof(ipValue),&ipValue))
  188. return ipValue;
  189. return 0;
  190. }
  191. //--------------------------------------------------------------------------------------------------------------------
  192. const static unsigned __int64 oneMilliSecond = I64C(1000000);
  193. const static unsigned __int64 oneSecond = I64C(1000000000);
  194. const static unsigned __int64 oneMinute = I64C(60000000000);
  195. const static unsigned __int64 oneHour = I64C(3600000000000);
  196. const static unsigned __int64 oneDay = 24 * I64C(3600000000000);
  197. static void formatTime(StringBuffer & out, unsigned __int64 value)
  198. {
  199. //Aim to display at least 3 significant digits in the result string
  200. if (value < oneMilliSecond)
  201. out.appendf("%uns", (unsigned)value);
  202. else if (value < oneSecond)
  203. {
  204. unsigned uvalue = (unsigned)value;
  205. out.appendf("%u.%03ums", uvalue / 1000000, (uvalue / 1000) % 1000);
  206. }
  207. else
  208. {
  209. unsigned days = (unsigned)(value / oneDay);
  210. value = value % oneDay;
  211. unsigned hours = (unsigned)(value / oneHour);
  212. value = value % oneHour;
  213. unsigned mins = (unsigned)(value / oneMinute);
  214. value = value % oneMinute;
  215. unsigned secs = (unsigned)(value / oneSecond);
  216. unsigned ns = (unsigned)(value % oneSecond);
  217. if (days > 0)
  218. out.appendf("%u days ", days);
  219. if (hours > 0 || days)
  220. out.appendf("%u:%02u:%02u", hours, mins, secs);
  221. else if (mins >= 10)
  222. out.appendf("%u:%02u", mins, secs);
  223. else if (mins >= 1)
  224. out.appendf("%u:%02u.%03u", mins, secs, ns / 1000000);
  225. else
  226. out.appendf("%u.%03us", secs, ns / 1000000);
  227. }
  228. }
  229. extern void formatTimeCollatable(StringBuffer & out, unsigned __int64 value, bool nano)
  230. {
  231. unsigned days = (unsigned)(value / oneDay);
  232. value = value % oneDay;
  233. unsigned hours = (unsigned)(value / oneHour);
  234. value = value % oneHour;
  235. unsigned mins = (unsigned)(value / oneMinute);
  236. value = value % oneMinute;
  237. unsigned secs = (unsigned)(value / oneSecond);
  238. unsigned ns = (unsigned)(value % oneSecond);
  239. if (days)
  240. out.appendf(" %3ud ", days); // Two leading spaces helps the cassandra driver force to a single partition
  241. else
  242. out.appendf(" ");
  243. if (nano)
  244. out.appendf("%2u:%02u:%02u.%09u", hours, mins, secs, ns);
  245. else
  246. out.appendf("%2u:%02u:%02u.%03u", hours, mins, secs, ns/1000000);
  247. // More than 999 days, I don't care that it goes wrong.
  248. }
  249. extern unsigned __int64 extractTimeCollatable(const char *s, bool nano)
  250. {
  251. if (!s)
  252. return 0;
  253. unsigned days,hours,mins,secs,fracs;
  254. if (sscanf(s, " %ud %u:%u:%u.%u", &days, &hours, &mins, &secs, &fracs)!=5)
  255. {
  256. days = 0;
  257. if (sscanf(s, " %u:%u:%u.%u", &hours, &mins, &secs, &fracs) != 4)
  258. return 0;
  259. }
  260. unsigned __int64 ret = days*oneDay + hours*oneHour + mins*oneMinute + secs*oneSecond;
  261. if (nano)
  262. ret += fracs;
  263. else
  264. ret += milliToNano(fracs);
  265. return ret;
  266. }
  267. static void formatTimeStamp(StringBuffer & out, unsigned __int64 value)
  268. {
  269. time_t seconds = value / 1000000;
  270. unsigned us = value % 1000000;
  271. char timeStamp[64];
  272. time_t tNow = seconds;
  273. #ifdef _WIN32
  274. struct tm *gmtNow;
  275. gmtNow = gmtime(&tNow);
  276. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%S", gmtNow);
  277. #else
  278. struct tm gmtNow;
  279. gmtime_r(&tNow, &gmtNow);
  280. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%S", &gmtNow);
  281. #endif //_WIN32
  282. out.append(timeStamp).appendf(".%03uZ", us / 1000);
  283. }
  284. void formatTimeStampAsLocalTime(StringBuffer & out, unsigned __int64 value)
  285. {
  286. time_t seconds = value / 1000000;
  287. unsigned us = value % 1000000;
  288. char timeStamp[64];
  289. time_t tNow = seconds;
  290. #ifdef _WIN32
  291. struct tm *gmtNow;
  292. gmtNow = localtime(&tNow);
  293. strftime(timeStamp, 64, "%H:%M:%S", gmtNow);
  294. #else
  295. struct tm gmtNow;
  296. localtime_r(&tNow, &gmtNow);
  297. strftime(timeStamp, 64, "%H:%M:%S", &gmtNow);
  298. #endif //_WIN32
  299. out.append(timeStamp).appendf(".%03u", us / 1000);
  300. }
  301. static const unsigned oneKb = 1024;
  302. static const unsigned oneMb = 1024 * 1024;
  303. static const unsigned oneGb = 1024 * 1024 * 1024;
  304. static unsigned toPermille(unsigned x) { return (x * 1000) / 1024; }
  305. static StringBuffer & formatSize(StringBuffer & out, unsigned __int64 value)
  306. {
  307. unsigned Gb = (unsigned)(value / oneGb);
  308. unsigned Mb = (unsigned)((value % oneGb) / oneMb);
  309. unsigned Kb = (unsigned)((value % oneMb) / oneKb);
  310. unsigned b = (unsigned)(value % oneKb);
  311. if (Gb)
  312. return out.appendf("%u.%03uGb", Gb, toPermille(Mb));
  313. else if (Mb)
  314. return out.appendf("%u.%03uMb", Mb, toPermille(Kb));
  315. else if (Kb)
  316. return out.appendf("%u.%03uKb", Kb, toPermille(b));
  317. else
  318. return out.appendf("%ub", b);
  319. }
  320. static StringBuffer & formatLoad(StringBuffer & out, unsigned __int64 value)
  321. {
  322. //Stored as millionth of a core. Display as a percentage => scale by 10,000
  323. return out.appendf("%u.%03u%%", (unsigned)(value / 10000), (unsigned)(value % 10000) / 10);
  324. }
  325. static StringBuffer & formatSkew(StringBuffer & out, unsigned __int64 value)
  326. {
  327. //Skew stored as 10000 = perfect, display as percentage
  328. return out.appendf("%.2f%%", ((double)(__int64)value) / 100.0);
  329. }
  330. static StringBuffer & formatIPV4(StringBuffer & out, unsigned __int64 value)
  331. {
  332. byte ip1 = (value & 255);
  333. byte ip2 = ((value >> 8) & 255);
  334. byte ip3 = ((value >> 16) & 255);
  335. byte ip4 = ((value >> 24) & 255);
  336. return out.appendf("%d.%d.%d.%d", ip1, ip2, ip3, ip4);
  337. }
  338. StringBuffer & formatStatistic(StringBuffer & out, unsigned __int64 value, StatisticMeasure measure)
  339. {
  340. switch (measure)
  341. {
  342. case SMeasureNone: // Unknown stat - e.g, on old esp accessing a new workunit
  343. return out.append(value);
  344. case SMeasureTimeNs:
  345. formatTime(out, value);
  346. return out;
  347. case SMeasureTimestampUs:
  348. formatTimeStamp(out, value);
  349. return out;
  350. case SMeasureCount:
  351. return out.append(value);
  352. case SMeasureSize:
  353. return formatSize(out, value);
  354. case SMeasureLoad:
  355. return formatLoad(out, value);
  356. case SMeasureSkew:
  357. return formatSkew(out, value);
  358. case SMeasureNode:
  359. return out.append(value);
  360. case SMeasurePercent:
  361. return out.appendf("%.2f%%", (double)value / 10000.0); // stored as ppm
  362. case SMeasureIPV4:
  363. return formatIPV4(out, value);
  364. case SMeasureCycle:
  365. return out.append(value);
  366. case SMeasureBool:
  367. return out.append(boolToStr(value != 0));
  368. case SMeasureText:
  369. case SMeasureId:
  370. case SMeasureFilename:
  371. return out.append(value);
  372. case SMeasureEnum:
  373. return out.append("Enum{").append(value).append("}"); // JCS->GH for now, should map to known enum text somehow
  374. default:
  375. return out.append(value).append('?');
  376. }
  377. }
  378. StringBuffer & formatStatistic(StringBuffer & out, unsigned __int64 value, StatisticKind kind)
  379. {
  380. return formatStatistic(out, value, queryMeasure(kind));
  381. }
  382. //--------------------------------------------------------------------------------------------------------------------
  383. stat_type readStatisticValue(const char * cur, const char * * end, StatisticMeasure measure)
  384. {
  385. char * next;
  386. stat_type value = strtoll(cur, &next, 10);
  387. switch (measure)
  388. {
  389. case SMeasureTimeNs:
  390. //Allow s, ms and us as scaling suffixes
  391. if (next[0] == 's')
  392. {
  393. value *= 1000000000;
  394. next++;
  395. }
  396. else if ((next[0] == 'm') && (next[1] == 's'))
  397. {
  398. value *= 1000000;
  399. next += 2;
  400. }
  401. else if ((next[0] == 'u') && (next[1] == 's'))
  402. {
  403. value *= 1000;
  404. next += 2;
  405. }
  406. break;
  407. case SMeasureCount:
  408. case SMeasureSize:
  409. //Allow K, M, G as scaling suffixes
  410. if (next[0] == 'K')
  411. {
  412. value *= 0x400;
  413. next++;
  414. }
  415. else if (next[0] == 'M')
  416. {
  417. value *= 0x100000;
  418. next++;
  419. }
  420. else if (next[0] == 'G')
  421. {
  422. value *= 0x40000000;
  423. next++;
  424. }
  425. //Skip bytes marker
  426. if ((*next == 'b') || (*next == 'B'))
  427. next++;
  428. break;
  429. case SMeasurePercent:
  430. //MORE: Extend to allow fractional percentages
  431. //Allow % to mean a percentage - instead of ppm
  432. if (next[0] == '%')
  433. {
  434. value *= 10000;
  435. next++;
  436. }
  437. break;
  438. }
  439. if (end)
  440. *end = next;
  441. return value;
  442. }
  443. void validateScopeId(const char * idText)
  444. {
  445. StatsScopeId id;
  446. if (!id.setScopeText(idText))
  447. throw makeStringExceptionV(JLIBERR_UnexpectedValue, "'%s' does not appear to be a valid scope id", idText);
  448. }
  449. void validateScope(const char * scopeText)
  450. {
  451. StatsScopeId id;
  452. const char * cur = scopeText;
  453. for(;;)
  454. {
  455. if (!id.setScopeText(cur, &cur))
  456. throw makeStringExceptionV(JLIBERR_UnexpectedValue, "'%s' does not appear to be a valid scope id", cur);
  457. cur = strchr(cur, ':');
  458. if (!cur)
  459. return;
  460. cur++;
  461. }
  462. }
  463. //--------------------------------------------------------------------------------------------------------------------
  464. unsigned queryScopeDepth(const char * text)
  465. {
  466. if (!*text)
  467. return 0;
  468. unsigned depth = 1;
  469. for (;;)
  470. {
  471. switch (*text)
  472. {
  473. case 0:
  474. return depth;
  475. case ':':
  476. depth++;
  477. break;
  478. }
  479. text++;
  480. }
  481. }
  482. const char * queryScopeTail(const char * scope)
  483. {
  484. const char * colon = strrchr(scope, ':');
  485. if (colon)
  486. return colon+1;
  487. else
  488. return scope;
  489. }
  490. bool getParentScope(StringBuffer & parent, const char * scope)
  491. {
  492. const char * colon = strrchr(scope, ':');
  493. if (colon)
  494. {
  495. parent.append(colon-scope, scope);
  496. return true;
  497. }
  498. else
  499. return false;
  500. }
  501. void describeScope(StringBuffer & description, const char * scope)
  502. {
  503. if (!*scope)
  504. return;
  505. StatsScopeId id;
  506. for(;;)
  507. {
  508. id.extractScopeText(scope, &scope);
  509. id.describe(description);
  510. if (!*scope)
  511. return;
  512. description.append(": ");
  513. scope++;
  514. }
  515. }
  516. const char * queryMeasurePrefix(StatisticMeasure measure)
  517. {
  518. switch (measure)
  519. {
  520. case SMeasureAll: return nullptr;
  521. case SMeasureTimeNs: return "Time";
  522. case SMeasureTimestampUs: return "When";
  523. case SMeasureCount: return "Num";
  524. case SMeasureSize: return "Size";
  525. case SMeasureLoad: return "Load";
  526. case SMeasureSkew: return "Skew";
  527. case SMeasureNode: return "Node";
  528. case SMeasurePercent: return "Per";
  529. case SMeasureIPV4: return "Ip";
  530. case SMeasureCycle: return "Cycle";
  531. case SMeasureEnum: return "";
  532. case SMeasureText: return "";
  533. case SMeasureBool: return "Is";
  534. case SMeasureId: return "Id";
  535. case SMeasureFilename: return "";
  536. case SMeasureNone: return nullptr;
  537. default:
  538. return "Unknown";
  539. }
  540. }
  541. const char * queryMeasureName(StatisticMeasure measure)
  542. {
  543. return measureNames[measure];
  544. }
  545. StatisticMeasure queryMeasure(const char * measure, StatisticMeasure dft)
  546. {
  547. //MORE: Use a hash table??
  548. StatisticMeasure ret = (StatisticMeasure)matchString(measureNames, measure, SMeasureMax);
  549. if (ret != SMeasureMax)
  550. return ret;
  551. //Legacy support for an unusual statistic - pretend the sizes are in bytes instead of kb.
  552. if (streq(measure, "kb"))
  553. return SMeasureSize;
  554. for (unsigned i1=SMeasureAll+1; i1 < SMeasureMax; i1++)
  555. {
  556. const char * prefix = queryMeasurePrefix((StatisticMeasure)i1);
  557. if (strieq(measure, prefix))
  558. return (StatisticMeasure)i1;
  559. }
  560. return dft;
  561. }
  562. StatsMergeAction queryMergeMode(StatisticMeasure measure)
  563. {
  564. switch (measure)
  565. {
  566. case SMeasureTimeNs: return StatsMergeSum;
  567. case SMeasureTimestampUs: return StatsMergeKeepNonZero;
  568. case SMeasureCount: return StatsMergeSum;
  569. case SMeasureSize: return StatsMergeSum;
  570. case SMeasureLoad: return StatsMergeMax;
  571. case SMeasureSkew: return StatsMergeMax;
  572. case SMeasureNode: return StatsMergeKeepNonZero;
  573. case SMeasurePercent: return StatsMergeReplace;
  574. case SMeasureIPV4: return StatsMergeKeepNonZero;
  575. case SMeasureCycle: return StatsMergeSum;
  576. case SMeasureEnum: return StatsMergeKeepNonZero;
  577. case SMeasureText: return StatsMergeKeepNonZero;
  578. case SMeasureBool: return StatsMergeKeepNonZero;
  579. case SMeasureId: return StatsMergeKeepNonZero;
  580. case SMeasureFilename: return StatsMergeKeepNonZero;
  581. default:
  582. #ifdef _DEBUG
  583. throwUnexpected();
  584. #else
  585. return StatsMergeSum;
  586. #endif
  587. }
  588. }
  589. extern jlib_decl StatsMergeAction queryMergeMode(StatisticKind kind)
  590. {
  591. //MORE: Optimize by looking up in the meta
  592. return queryMergeMode(queryMeasure(kind));
  593. }
  594. //--------------------------------------------------------------------------------------------------------------------
  595. #define BASE_NAMES(x, y) \
  596. #x #y, \
  597. #x "Min" # y, \
  598. #x "Max" # y, \
  599. #x "Avg" # y, \
  600. "Skew" # y, \
  601. "SkewMin" # y, \
  602. "SkewMax" # y, \
  603. "NodeMin" # y, \
  604. "NodeMax" # y,
  605. #define NAMES(x, y) \
  606. BASE_NAMES(x, y) \
  607. #x "Delta" # y, \
  608. #x "StdDev" #y,
  609. #define WHENNAMES(x, y) \
  610. BASE_NAMES(x, y) \
  611. "TimeDelta" # y, \
  612. "TimeStdDev" # y,
  613. #define BASE_TAGS(x, y) \
  614. "@" #x "Min" # y, \
  615. "@" #x "Max" # y, \
  616. "@" #x "Avg" # y, \
  617. "@Skew" # y, \
  618. "@SkewMin" # y, \
  619. "@SkewMax" # y, \
  620. "@NodeMin" # y, \
  621. "@NodeMax" # y,
  622. //Default tags nothing special overriden
  623. #define TAGS(x, y) \
  624. "@" #x #y, \
  625. BASE_TAGS(x, y) \
  626. "@" #x "Delta" # y, \
  627. "@" #x "StdDev" # y,
  628. //Define the tags for time items.
  629. #define WHENTAGS(x, y) \
  630. "@" #x #y, \
  631. BASE_TAGS(x, y) \
  632. "@TimeDelta" # y, \
  633. "@TimeStdDev" # y,
  634. #define CORESTAT(x, y, m) St##x##y, m, St##x##y, St##x##y, { NAMES(x, y) }, { TAGS(x, y) }
  635. #define STAT(x, y, m) CORESTAT(x, y, m)
  636. //--------------------------------------------------------------------------------------------------------------------
  637. //These are the macros to use to define the different entries in the stats meta table
  638. //#define TIMESTAT(y) STAT(Time, y, SMeasureTimeNs)
  639. #define TIMESTAT(y) St##Time##y, SMeasureTimeNs, St##Time##y, St##Cycle##y##Cycles, { NAMES(Time, y) }, { TAGS(Time, y) }
  640. #define WHENSTAT(y) St##When##y, SMeasureTimestampUs, St##When##y, St##When##y, { WHENNAMES(When, y) }, { WHENTAGS(When, y) }
  641. #define NUMSTAT(y) STAT(Num, y, SMeasureCount)
  642. #define SIZESTAT(y) STAT(Size, y, SMeasureSize)
  643. #define LOADSTAT(y) STAT(Load, y, SMeasureLoad)
  644. #define SKEWSTAT(y) STAT(Skew, y, SMeasureSkew)
  645. #define NODESTAT(y) STAT(Node, y, SMeasureNode)
  646. #define PERSTAT(y) STAT(Per, y, SMeasurePercent)
  647. #define IPV4STAT(y) STAT(IPV4, y, SMeasureIPV4)
  648. #define CYCLESTAT(y) St##Cycle##y##Cycles, SMeasureCycle, St##Time##y, St##Cycle##y##Cycles, { NAMES(Cycle, y##Cycles) }, { TAGS(Cycle, y##Cycles) }
  649. #define ENUMSTAT(y) STAT(Enum, y, SMeasureEnum)
  650. //--------------------------------------------------------------------------------------------------------------------
  651. class StatisticMeta
  652. {
  653. public:
  654. StatisticKind kind;
  655. StatisticMeasure measure;
  656. StatisticKind serializeKind;
  657. StatisticKind rawKind;
  658. const char * names[StNextModifier/StVariantScale];
  659. const char * tags[StNextModifier/StVariantScale];
  660. };
  661. //The order of entries in this table must match the order in the enumeration
  662. static const StatisticMeta statsMetaData[StMax] = {
  663. { StKindNone, SMeasureNone, StKindNone, StKindNone, { "none" }, { "@none" } },
  664. { StKindAll, SMeasureAll, StKindAll, StKindAll, { "all" }, { "@all" } },
  665. { WHENSTAT(GraphStarted) }, // Deprecated - use WhenStart
  666. { WHENSTAT(GraphFinished) }, // Deprecated - use WhenFinished
  667. { WHENSTAT(FirstRow) },
  668. { WHENSTAT(QueryStarted) }, // Deprecated - use WhenStart
  669. { WHENSTAT(QueryFinished) }, // Deprecated - use WhenFinished
  670. { WHENSTAT(Created) },
  671. { WHENSTAT(Compiled) },
  672. { WHENSTAT(WorkunitModified) },
  673. { TIMESTAT(Elapsed) },
  674. { TIMESTAT(LocalExecute) },
  675. { TIMESTAT(TotalExecute) },
  676. { TIMESTAT(Remaining) },
  677. { SIZESTAT(GeneratedCpp) },
  678. { SIZESTAT(PeakMemory) },
  679. { SIZESTAT(MaxRowSize) },
  680. { NUMSTAT(RowsProcessed) },
  681. { NUMSTAT(Slaves) },
  682. { NUMSTAT(Starts) },
  683. { NUMSTAT(Stops) },
  684. { NUMSTAT(IndexSeeks) },
  685. { NUMSTAT(IndexScans) },
  686. { NUMSTAT(IndexWildSeeks) },
  687. { NUMSTAT(IndexSkips) },
  688. { NUMSTAT(IndexNullSkips) },
  689. { NUMSTAT(IndexMerges) },
  690. { NUMSTAT(IndexMergeCompares) },
  691. { NUMSTAT(PreFiltered) },
  692. { NUMSTAT(PostFiltered) },
  693. { NUMSTAT(BlobCacheHits) },
  694. { NUMSTAT(LeafCacheHits) },
  695. { NUMSTAT(NodeCacheHits) },
  696. { NUMSTAT(BlobCacheAdds) },
  697. { NUMSTAT(LeafCacheAdds) },
  698. { NUMSTAT(NodeCacheAdds) },
  699. { NUMSTAT(PreloadCacheHits) },
  700. { NUMSTAT(PreloadCacheAdds) },
  701. { NUMSTAT(ServerCacheHits) },
  702. { NUMSTAT(IndexAccepted) },
  703. { NUMSTAT(IndexRejected) },
  704. { NUMSTAT(AtmostTriggered) },
  705. { NUMSTAT(DiskSeeks) },
  706. { NUMSTAT(Iterations) },
  707. { LOADSTAT(WhileSorting) },
  708. { NUMSTAT(LeftRows) },
  709. { NUMSTAT(RightRows) },
  710. { PERSTAT(Replicated) },
  711. { NUMSTAT(DiskRowsRead) },
  712. { NUMSTAT(IndexRowsRead) },
  713. { NUMSTAT(DiskAccepted) },
  714. { NUMSTAT(DiskRejected) },
  715. { TIMESTAT(Soapcall) },
  716. { TIMESTAT(FirstExecute) },
  717. { TIMESTAT(DiskReadIO) },
  718. { TIMESTAT(DiskWriteIO) },
  719. { SIZESTAT(DiskRead) },
  720. { SIZESTAT(DiskWrite) },
  721. { CYCLESTAT(DiskReadIO) },
  722. { CYCLESTAT(DiskWriteIO) },
  723. { NUMSTAT(DiskReads) },
  724. { NUMSTAT(DiskWrites) },
  725. { NUMSTAT(Spills) },
  726. { TIMESTAT(SpillElapsed) },
  727. { TIMESTAT(SortElapsed) },
  728. { NUMSTAT(Groups) },
  729. { NUMSTAT(GroupMax) },
  730. { SIZESTAT(SpillFile) },
  731. { CYCLESTAT(SpillElapsed) },
  732. { CYCLESTAT(SortElapsed) },
  733. { NUMSTAT(Strands) },
  734. { CYCLESTAT(TotalExecute) },
  735. { NUMSTAT(Executions) },
  736. { TIMESTAT(TotalNested) },
  737. { CYCLESTAT(LocalExecute) },
  738. { NUMSTAT(Compares) },
  739. { NUMSTAT(ScansPerRow) },
  740. { NUMSTAT(Allocations) },
  741. { NUMSTAT(AllocationScans) },
  742. { NUMSTAT(DiskRetries) },
  743. { CYCLESTAT(Elapsed) },
  744. { CYCLESTAT(Remaining) },
  745. { CYCLESTAT(Soapcall) },
  746. { CYCLESTAT(FirstExecute) },
  747. { CYCLESTAT(TotalNested) },
  748. { TIMESTAT(Generate) },
  749. { CYCLESTAT(Generate) },
  750. { WHENSTAT(Started) },
  751. { WHENSTAT(Finished) },
  752. { NUMSTAT(AnalyseExprs) },
  753. { NUMSTAT(TransformExprs) },
  754. { NUMSTAT(UniqueAnalyseExprs) },
  755. { NUMSTAT(UniqueTransformExprs) },
  756. { NUMSTAT(DuplicateKeys) },
  757. { NUMSTAT(AttribsProcessed) },
  758. { NUMSTAT(AttribsSimplified) },
  759. { NUMSTAT(AttribsFromCache) },
  760. { NUMSTAT(SmartJoinDegradedToLocal) },
  761. { NUMSTAT(SmartJoinSlavesDegradedToStd) },
  762. };
  763. //--------------------------------------------------------------------------------------------------------------------
  764. StatisticMeasure queryMeasure(StatisticKind kind)
  765. {
  766. unsigned variant = queryStatsVariant(kind);
  767. switch (variant)
  768. {
  769. case StSkew:
  770. case StSkewMin:
  771. case StSkewMax:
  772. return SMeasureSkew;
  773. case StNodeMin:
  774. case StNodeMax:
  775. return SMeasureNode;
  776. case StDeltaX:
  777. case StStdDevX:
  778. {
  779. StatisticMeasure measure = queryMeasure((StatisticKind)(kind & StKindMask));
  780. switch (measure)
  781. {
  782. case SMeasureTimestampUs:
  783. return SMeasureTimeNs;
  784. default:
  785. return measure;
  786. }
  787. break;
  788. }
  789. }
  790. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  791. if (rawkind >= StKindNone && rawkind < StMax)
  792. return statsMetaData[rawkind].measure;
  793. return SMeasureNone;
  794. }
  795. const char * queryStatisticName(StatisticKind kind)
  796. {
  797. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  798. unsigned variant = (kind / StVariantScale);
  799. dbgassertex(variant < (StNextModifier/StVariantScale));
  800. if (rawkind >= StKindNone && rawkind < StMax)
  801. return statsMetaData[rawkind].names[variant];
  802. return "Unknown";
  803. }
  804. unsigned __int64 convertMeasure(StatisticMeasure from, StatisticMeasure to, unsigned __int64 value)
  805. {
  806. if (from == to)
  807. return value;
  808. if ((from == SMeasureCycle) && (to == SMeasureTimeNs))
  809. return cycle_to_nanosec(value);
  810. if ((from == SMeasureTimeNs) && (to == SMeasureCycle))
  811. return nanosec_to_cycle(value);
  812. #ifdef _DEBUG
  813. throwUnexpected();
  814. #else
  815. return value;
  816. #endif
  817. }
  818. unsigned __int64 convertMeasure(StatisticKind from, StatisticKind to, unsigned __int64 value)
  819. {
  820. return convertMeasure(queryMeasure(from), queryMeasure(to), value);
  821. }
  822. static double convertSquareMeasure(StatisticMeasure from, StatisticMeasure to, double value)
  823. {
  824. if (from == to)
  825. return value;
  826. const unsigned __int64 largeValue = 1000000000;
  827. double scale;
  828. if ((from == SMeasureCycle) && (to == SMeasureTimeNs))
  829. scale = (double)cycle_to_nanosec(largeValue) / (double)largeValue;
  830. else if ((from == SMeasureTimeNs) && (to == SMeasureCycle))
  831. scale = (double)nanosec_to_cycle(largeValue) / (double)largeValue;
  832. else
  833. {
  834. #ifdef _DEBUG
  835. throwUnexpected();
  836. #else
  837. scale = 1.0;
  838. #endif
  839. }
  840. return value * scale * scale;
  841. }
  842. static double convertSquareMeasure(StatisticKind from, StatisticKind to, double value)
  843. {
  844. return convertSquareMeasure(queryMeasure(from), queryMeasure(to), value);
  845. }
  846. static StatisticKind querySerializedKind(StatisticKind kind)
  847. {
  848. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  849. if (rawkind >= StMax)
  850. return kind;
  851. StatisticKind serialKind = statsMetaData[rawkind].serializeKind;
  852. return (StatisticKind)(serialKind | (kind & ~StKindMask));
  853. }
  854. static StatisticKind queryRawKind(StatisticKind kind)
  855. {
  856. StatisticKind basekind = (StatisticKind)(kind & StKindMask);
  857. if (basekind >= StMax)
  858. return kind;
  859. StatisticKind rawKind = statsMetaData[basekind].rawKind;
  860. return (StatisticKind)(rawKind | (kind & ~StKindMask));
  861. }
  862. //--------------------------------------------------------------------------------------------------------------------
  863. void queryLongStatisticName(StringBuffer & out, StatisticKind kind)
  864. {
  865. out.append(queryStatisticName(kind));
  866. }
  867. //--------------------------------------------------------------------------------------------------------------------
  868. const char * queryTreeTag(StatisticKind kind)
  869. {
  870. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  871. unsigned variant = (kind / StVariantScale);
  872. dbgassertex(variant < (StNextModifier/StVariantScale));
  873. if (rawkind >= StKindNone && rawkind < StMax)
  874. return statsMetaData[rawkind].tags[variant];
  875. return "@Unknown";
  876. }
  877. //--------------------------------------------------------------------------------------------------------------------
  878. StatisticKind queryStatisticKind(const char * search, StatisticKind dft)
  879. {
  880. if (!search)
  881. return dft;
  882. if (streq(search, "*"))
  883. return StKindAll;
  884. //Slow - should use a hash table....
  885. for (unsigned variant=0; variant < StNextModifier; variant += StVariantScale)
  886. {
  887. for (unsigned i=0; i < StMax; i++)
  888. {
  889. StatisticKind kind = (StatisticKind)(i+variant);
  890. const char * shortName = queryStatisticName(kind);
  891. if (shortName && strieq(shortName, search))
  892. return kind;
  893. }
  894. }
  895. return dft;
  896. }
  897. //--------------------------------------------------------------------------------------------------------------------
  898. const char * queryCreatorTypeName(StatisticCreatorType sct)
  899. {
  900. return creatorTypeNames[sct];
  901. }
  902. StatisticCreatorType queryCreatorType(const char * sct, StatisticCreatorType dft)
  903. {
  904. //MORE: Use a hash table??
  905. return (StatisticCreatorType)matchString(creatorTypeNames, sct, dft);
  906. }
  907. //--------------------------------------------------------------------------------------------------------------------
  908. const char * queryScopeTypeName(StatisticScopeType sst)
  909. {
  910. return scopeTypeNames[sst];
  911. }
  912. extern jlib_decl StatisticScopeType queryScopeType(const char * sst, StatisticScopeType dft)
  913. {
  914. //MORE: Use a hash table??
  915. return (StatisticScopeType)matchString(scopeTypeNames, sst, dft);
  916. }
  917. //--------------------------------------------------------------------------------------------------------------------
  918. inline void mergeUpdate(StatisticMeasure measure, unsigned __int64 & value, const unsigned __int64 otherValue)
  919. {
  920. switch (measure)
  921. {
  922. case SMeasureTimeNs:
  923. case SMeasureCount:
  924. case SMeasureSize:
  925. case SMeasureLoad:
  926. case SMeasureSkew:
  927. case SMeasureCycle:
  928. value += otherValue;
  929. break;
  930. case SMeasureTimestampUs:
  931. if (otherValue && otherValue < value)
  932. value = otherValue;
  933. break;
  934. }
  935. }
  936. unsigned __int64 mergeStatistic(StatisticMeasure measure, unsigned __int64 value, unsigned __int64 otherValue)
  937. {
  938. mergeUpdate(measure, value, otherValue);
  939. return value;
  940. }
  941. unsigned __int64 mergeStatisticValue(unsigned __int64 prevValue, unsigned __int64 newValue, StatsMergeAction mergeAction)
  942. {
  943. switch (mergeAction)
  944. {
  945. case StatsMergeKeepNonZero:
  946. if (prevValue)
  947. return prevValue;
  948. return newValue;
  949. case StatsMergeAppend:
  950. case StatsMergeReplace:
  951. return newValue;
  952. case StatsMergeSum:
  953. return prevValue + newValue;
  954. case StatsMergeMin:
  955. if (prevValue > newValue)
  956. return newValue;
  957. else
  958. return prevValue;
  959. case StatsMergeMax:
  960. if (prevValue < newValue)
  961. return newValue;
  962. else
  963. return prevValue;
  964. default:
  965. #ifdef _DEBUG
  966. throwUnexpected();
  967. #else
  968. return newValue;
  969. #endif
  970. }
  971. }
  972. //--------------------------------------------------------------------------------------------------------------------
  973. class CComponentStatistics
  974. {
  975. protected:
  976. StringAttr creator;
  977. byte creatorDepth;
  978. byte scopeDepth;
  979. // StatisticArray stats;
  980. };
  981. //--------------------------------------------------------------------------------------------------------------------
  982. static int compareUnsigned(unsigned const * left, unsigned const * right)
  983. {
  984. return (*left < *right) ? -1 : (*left > *right) ? +1 : 0;
  985. }
  986. StatisticsMapping::StatisticsMapping(const std::initializer_list<StatisticKind> &kinds)
  987. {
  988. for (auto kind : kinds)
  989. {
  990. assert(kind != StKindNone);
  991. assert(!indexToKind.contains(kind));
  992. indexToKind.append(kind);
  993. }
  994. createMappings();
  995. }
  996. StatisticsMapping::StatisticsMapping(const StatisticsMapping * from, const std::initializer_list<StatisticKind> &kinds)
  997. {
  998. ForEachItemIn(idx, from->indexToKind)
  999. indexToKind.append(from->indexToKind.item(idx));
  1000. for (auto kind : kinds)
  1001. {
  1002. assert(kind != StKindNone);
  1003. assert(!indexToKind.contains(kind));
  1004. indexToKind.append(kind);
  1005. }
  1006. createMappings();
  1007. }
  1008. StatisticsMapping::StatisticsMapping()
  1009. {
  1010. for (int i = StKindAll+1; i < StMax; i++)
  1011. indexToKind.append(i);
  1012. createMappings();
  1013. }
  1014. void StatisticsMapping::createMappings()
  1015. {
  1016. //Possibly not needed, but sort the kinds, so that it is easy to merge/stream the results out in the correct order.
  1017. indexToKind.sort(compareUnsigned);
  1018. //Provide mappings to all statistics to map them to the "unknown" bin by default
  1019. for (unsigned i=0; i < StMax; i++)
  1020. kindToIndex.append(numStatistics());
  1021. ForEachItemIn(i2, indexToKind)
  1022. {
  1023. unsigned kind = indexToKind.item(i2);
  1024. kindToIndex.replace(i2, kind);
  1025. }
  1026. }
  1027. const StatisticsMapping allStatistics;
  1028. const StatisticsMapping heapStatistics({StNumAllocations, StNumAllocationScans});
  1029. const StatisticsMapping diskLocalStatistics({StCycleDiskReadIOCycles, StSizeDiskRead, StNumDiskReads, StCycleDiskWriteIOCycles, StSizeDiskWrite, StNumDiskWrites, StNumDiskRetries});
  1030. const StatisticsMapping diskRemoteStatistics({StTimeDiskReadIO, StSizeDiskRead, StNumDiskReads, StTimeDiskWriteIO, StSizeDiskWrite, StNumDiskWrites, StNumDiskRetries});
  1031. const StatisticsMapping diskReadRemoteStatistics({StTimeDiskReadIO, StSizeDiskRead, StNumDiskReads, StNumDiskRetries});
  1032. const StatisticsMapping diskWriteRemoteStatistics({StTimeDiskWriteIO, StSizeDiskWrite, StNumDiskWrites, StNumDiskRetries});
  1033. //--------------------------------------------------------------------------------------------------------------------
  1034. class Statistic
  1035. {
  1036. public:
  1037. Statistic(StatisticKind _kind, unsigned __int64 _value) : kind(_kind), value(_value)
  1038. {
  1039. }
  1040. Statistic(MemoryBuffer & in, unsigned version)
  1041. {
  1042. unsigned _kind;
  1043. in.read(_kind);
  1044. kind = (StatisticKind)_kind;
  1045. in.read(value);
  1046. }
  1047. StatisticKind queryKind() const
  1048. {
  1049. return kind;
  1050. }
  1051. unsigned __int64 queryValue() const
  1052. {
  1053. return value;
  1054. }
  1055. void merge(unsigned __int64 otherValue)
  1056. {
  1057. mergeUpdate(queryMeasure(kind), value, otherValue);
  1058. }
  1059. void serialize(MemoryBuffer & out) const
  1060. {
  1061. //MORE: Could compress - e.g., store as a packed integers
  1062. out.append((unsigned)kind);
  1063. out.append(value);
  1064. }
  1065. void mergeInto(IStatisticGatherer & target) const
  1066. {
  1067. StatsMergeAction mergeAction = queryMergeMode(kind);
  1068. target.updateStatistic(kind, value, mergeAction);
  1069. }
  1070. StringBuffer & toXML(StringBuffer &out) const
  1071. {
  1072. return out.append(" <Stat name=\"").append(queryStatisticName(kind)).append("\" value=\"").append(value).append("\"/>\n");
  1073. }
  1074. public:
  1075. StatisticKind kind;
  1076. unsigned __int64 value;
  1077. };
  1078. //--------------------------------------------------------------------------------------------------------------------
  1079. StringBuffer & StatsScopeId::getScopeText(StringBuffer & out) const
  1080. {
  1081. switch (scopeType)
  1082. {
  1083. case SSTgraph:
  1084. return out.append(GraphScopePrefix).append(id);
  1085. case SSTsubgraph:
  1086. return out.append(SubGraphScopePrefix).append(id);
  1087. case SSTactivity:
  1088. return out.append(ActivityScopePrefix).append(id);
  1089. case SSTedge:
  1090. return out.append(EdgeScopePrefix).append(id).append("_").append(extra);
  1091. case SSTfunction:
  1092. return out.append(FunctionScopePrefix).append(name);
  1093. case SSTworkflow:
  1094. return out.append(WorkflowScopePrefix).append(id);
  1095. case SSTchildgraph:
  1096. return out.append(ChildGraphScopePrefix).append(id);
  1097. case SSTunknown:
  1098. return out.append(name);
  1099. default:
  1100. #ifdef _DEBUG
  1101. throwUnexpected();
  1102. #endif
  1103. return out.append("????").append(id);
  1104. }
  1105. }
  1106. unsigned StatsScopeId::getHash() const
  1107. {
  1108. switch (scopeType)
  1109. {
  1110. case SSTfunction:
  1111. case SSTunknown:
  1112. return hashc((const byte *)name.get(), strlen(name), (unsigned)scopeType);
  1113. default:
  1114. return hashc((const byte *)&id, sizeof(id), (unsigned)scopeType);
  1115. }
  1116. }
  1117. bool StatsScopeId::isWildcard() const
  1118. {
  1119. return (id == 0) && (extra == 0) && !name;
  1120. }
  1121. int StatsScopeId::compare(const StatsScopeId & other) const
  1122. {
  1123. if (scopeType != other.scopeType)
  1124. return scopePriority[scopeType] - scopePriority[other.scopeType];
  1125. if (id != other.id)
  1126. return (int)(id - other.id);
  1127. if (extra != other.extra)
  1128. return (int)(extra - other.extra);
  1129. if (name && other.name)
  1130. return strcmp(name, other.name);
  1131. if (name)
  1132. return +1;
  1133. if (other.name)
  1134. return -1;
  1135. return 0;
  1136. }
  1137. void StatsScopeId::describe(StringBuffer & description) const
  1138. {
  1139. const char * name = queryScopeTypeName(scopeType);
  1140. description.append((char)toupper(*name)).append(name+1);
  1141. switch (scopeType)
  1142. {
  1143. case SSTgraph:
  1144. description.append(" graph").append(id);
  1145. break;
  1146. case SSTsubgraph:
  1147. case SSTactivity:
  1148. case SSTworkflow:
  1149. case SSTchildgraph:
  1150. description.append(' ').append(id);
  1151. break;
  1152. case SSTedge:
  1153. description.append(' ').append(id).append(',').append(extra);
  1154. break;
  1155. case SSTfunction:
  1156. description.append(' ').append(name);
  1157. break;
  1158. default:
  1159. throwUnexpected();
  1160. break;
  1161. }
  1162. }
  1163. bool StatsScopeId::matches(const StatsScopeId & other) const
  1164. {
  1165. return (scopeType == other.scopeType) && (id == other.id) && (extra == other.extra) && strsame(name, other.name);
  1166. }
  1167. unsigned StatsScopeId::queryActivity() const
  1168. {
  1169. switch (scopeType)
  1170. {
  1171. case SSTactivity:
  1172. case SSTedge:
  1173. return id;
  1174. default:
  1175. return 0;
  1176. }
  1177. }
  1178. void StatsScopeId::deserialize(MemoryBuffer & in, unsigned version)
  1179. {
  1180. byte scopeTypeByte;
  1181. in.read(scopeTypeByte);
  1182. scopeType = (StatisticScopeType)scopeTypeByte;
  1183. switch (scopeType)
  1184. {
  1185. case SSTgraph:
  1186. case SSTsubgraph:
  1187. case SSTactivity:
  1188. case SSTworkflow:
  1189. case SSTchildgraph:
  1190. in.read(id);
  1191. break;
  1192. case SSTedge:
  1193. in.read(id);
  1194. in.read(extra);
  1195. break;
  1196. case SSTfunction:
  1197. in.read(name);
  1198. break;
  1199. default:
  1200. throwUnexpected();
  1201. break;
  1202. }
  1203. }
  1204. void StatsScopeId::serialize(MemoryBuffer & out) const
  1205. {
  1206. out.append((byte)scopeType);
  1207. switch (scopeType)
  1208. {
  1209. case SSTgraph:
  1210. case SSTsubgraph:
  1211. case SSTactivity:
  1212. case SSTworkflow:
  1213. case SSTchildgraph:
  1214. out.append(id);
  1215. break;
  1216. case SSTedge:
  1217. out.append(id);
  1218. out.append(extra);
  1219. break;
  1220. case SSTfunction:
  1221. out.append(name);
  1222. break;
  1223. default:
  1224. throwUnexpected();
  1225. break;
  1226. }
  1227. }
  1228. void StatsScopeId::setId(StatisticScopeType _scopeType, unsigned _id, unsigned _extra)
  1229. {
  1230. scopeType = _scopeType;
  1231. id = _id;
  1232. extra = _extra;
  1233. }
  1234. bool StatsScopeId::setScopeText(const char * text, const char * * _next)
  1235. {
  1236. char * * next = (char * *)_next;
  1237. switch (*text)
  1238. {
  1239. case ActivityScopePrefix[0]:
  1240. if (MATCHES_CONST_PREFIX(text, ActivityScopePrefix))
  1241. {
  1242. if (isdigit(text[strlen(ActivityScopePrefix)]))
  1243. {
  1244. unsigned id = strtoul(text + strlen(ActivityScopePrefix), next, 10);
  1245. setActivityId(id);
  1246. return true;
  1247. }
  1248. }
  1249. break;
  1250. case GraphScopePrefix[0]:
  1251. if (MATCHES_CONST_PREFIX(text, GraphScopePrefix))
  1252. {
  1253. if (isdigit(text[strlen(GraphScopePrefix)]))
  1254. {
  1255. unsigned id = strtoul(text + strlen(GraphScopePrefix), next, 10);
  1256. setId(SSTgraph, id);
  1257. return true;
  1258. }
  1259. }
  1260. break;
  1261. case SubGraphScopePrefix[0]:
  1262. if (MATCHES_CONST_PREFIX(text, SubGraphScopePrefix))
  1263. {
  1264. if (isdigit(text[strlen(SubGraphScopePrefix)]))
  1265. {
  1266. unsigned id = strtoul(text + strlen(SubGraphScopePrefix), next, 10);
  1267. setSubgraphId(id);
  1268. return true;
  1269. }
  1270. }
  1271. break;
  1272. case EdgeScopePrefix[0]:
  1273. if (MATCHES_CONST_PREFIX(text, EdgeScopePrefix))
  1274. {
  1275. const char * underscore = strchr(text, '_');
  1276. if (!underscore || !isdigit(underscore[1]))
  1277. return false;
  1278. unsigned id1 = atoi(text + strlen(EdgeScopePrefix));
  1279. unsigned id2 = strtoul(underscore+1, next, 10);
  1280. setEdgeId(id1, id2);
  1281. return true;
  1282. }
  1283. break;
  1284. case FunctionScopePrefix[0]:
  1285. if (MATCHES_CONST_PREFIX(text, FunctionScopePrefix))
  1286. {
  1287. setFunctionId(text+ strlen(FunctionScopePrefix));
  1288. return true;
  1289. }
  1290. break;
  1291. case WorkflowScopePrefix[0]:
  1292. if (MATCHES_CONST_PREFIX(text, WorkflowScopePrefix) && isdigit(text[strlen(WorkflowScopePrefix)]))
  1293. {
  1294. setWorkflowId(atoi(text+ strlen(WorkflowScopePrefix)));
  1295. return true;
  1296. }
  1297. break;
  1298. case ChildGraphScopePrefix[0]:
  1299. if (MATCHES_CONST_PREFIX(text, ChildGraphScopePrefix))
  1300. {
  1301. setChildGraphId(atoi(text+ strlen(ChildGraphScopePrefix)));
  1302. return true;
  1303. }
  1304. break;
  1305. case '\0':
  1306. setId(SSTglobal, 0);
  1307. return true;
  1308. }
  1309. return false;
  1310. }
  1311. bool StatsScopeId::extractScopeText(const char * text, const char * * next)
  1312. {
  1313. if (setScopeText(text, next))
  1314. return true;
  1315. scopeType = SSTunknown;
  1316. const char * end = strchr(text, ':');
  1317. if (end)
  1318. {
  1319. name.set(text, end-text);
  1320. if (next)
  1321. *next = end;
  1322. }
  1323. else
  1324. {
  1325. name.set(text);
  1326. if (next)
  1327. *next = text + strlen(text);
  1328. }
  1329. return false;
  1330. }
  1331. void StatsScopeId::setActivityId(unsigned _id)
  1332. {
  1333. setId(SSTactivity, _id);
  1334. }
  1335. void StatsScopeId::setEdgeId(unsigned _id, unsigned _output)
  1336. {
  1337. setId(SSTedge, _id, _output);
  1338. }
  1339. void StatsScopeId::setSubgraphId(unsigned _id)
  1340. {
  1341. setId(SSTsubgraph, _id);
  1342. }
  1343. void StatsScopeId::setFunctionId(const char * _name)
  1344. {
  1345. scopeType = SSTfunction;
  1346. name.set(_name);
  1347. }
  1348. void StatsScopeId::setWorkflowId(unsigned _id)
  1349. {
  1350. setId(SSTworkflow, _id);
  1351. }
  1352. void StatsScopeId::setChildGraphId(unsigned _id)
  1353. {
  1354. setId(SSTchildgraph, _id);
  1355. }
  1356. //--------------------------------------------------------------------------------------------------------------------
  1357. enum
  1358. {
  1359. SCroot,
  1360. SCintermediate,
  1361. SCleaf,
  1362. };
  1363. class CStatisticCollection;
  1364. static CStatisticCollection * deserializeCollection(CStatisticCollection * parent, MemoryBuffer & in, unsigned version);
  1365. //MORE: Create an implementation with no children
  1366. typedef StructArrayOf<Statistic> StatsArray;
  1367. class CollectionHashTable : public SuperHashTableOf<CStatisticCollection, StatsScopeId>
  1368. {
  1369. public:
  1370. ~CollectionHashTable() { _releaseAll(); }
  1371. virtual void onAdd(void *et);
  1372. virtual void onRemove(void *et);
  1373. virtual unsigned getHashFromElement(const void *et) const;
  1374. virtual unsigned getHashFromFindParam(const void *fp) const;
  1375. virtual const void * getFindParam(const void *et) const;
  1376. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const;
  1377. virtual bool matchesElement(const void *et, const void *searchET) const;
  1378. };
  1379. typedef IArrayOf<CStatisticCollection> CollectionArray;
  1380. static int compareCollection(IInterface * const * pl, IInterface * const *pr);
  1381. class SortedCollectionIterator : public ArrayIIteratorOf<IArrayOf<IStatisticCollection>, IStatisticCollection, IStatisticCollectionIterator>
  1382. {
  1383. IArrayOf<IStatisticCollection> elems;
  1384. public:
  1385. SortedCollectionIterator(IStatisticCollectionIterator &iter) : ArrayIIteratorOf<IArrayOf<IStatisticCollection>, IStatisticCollection, IStatisticCollectionIterator>(elems)
  1386. {
  1387. ForEach(iter)
  1388. elems.append(iter.get());
  1389. elems.sort(compareCollection);
  1390. }
  1391. };
  1392. class CStatisticCollection : public CInterfaceOf<IStatisticCollection>
  1393. {
  1394. friend class CollectionHashTable;
  1395. public:
  1396. CStatisticCollection(CStatisticCollection * _parent, const StatsScopeId & _id) : id(_id), parent(_parent)
  1397. {
  1398. }
  1399. CStatisticCollection(CStatisticCollection * _parent, MemoryBuffer & in, unsigned version) : parent(_parent)
  1400. {
  1401. id.deserialize(in, version);
  1402. unsigned numStats;
  1403. in.read(numStats);
  1404. stats.ensure(numStats);
  1405. while (numStats-- > 0)
  1406. {
  1407. Statistic next (in, version);
  1408. stats.append(next);
  1409. }
  1410. unsigned numChildren;
  1411. in.read(numChildren);
  1412. children.ensure(numChildren);
  1413. while (numChildren-- > 0)
  1414. {
  1415. CStatisticCollection * next = deserializeCollection(this, in, version);
  1416. children.add(*next);
  1417. }
  1418. }
  1419. virtual byte getCollectionType() const { return SCintermediate; }
  1420. StringBuffer &toXML(StringBuffer &out) const;
  1421. //interface IStatisticCollection:
  1422. virtual StatisticScopeType queryScopeType() const override
  1423. {
  1424. return id.queryScopeType();
  1425. }
  1426. virtual unsigned __int64 queryWhenCreated() const override
  1427. {
  1428. if (parent)
  1429. return parent->queryWhenCreated();
  1430. return 0;
  1431. }
  1432. virtual StringBuffer & getScope(StringBuffer & str) const override
  1433. {
  1434. return id.getScopeText(str);
  1435. }
  1436. virtual StringBuffer & getFullScope(StringBuffer & str) const override
  1437. {
  1438. if (parent)
  1439. {
  1440. parent->getFullScope(str);
  1441. str.append(':');
  1442. }
  1443. id.getScopeText(str);
  1444. return str;
  1445. }
  1446. virtual unsigned __int64 queryStatistic(StatisticKind kind) const override
  1447. {
  1448. ForEachItemIn(i, stats)
  1449. {
  1450. const Statistic & cur = stats.item(i);
  1451. if (cur.kind == kind)
  1452. return cur.value;
  1453. }
  1454. return 0;
  1455. }
  1456. virtual bool getStatistic(StatisticKind kind, unsigned __int64 & value) const override
  1457. {
  1458. ForEachItemIn(i, stats)
  1459. {
  1460. const Statistic & cur = stats.item(i);
  1461. if (cur.kind == kind)
  1462. {
  1463. value = cur.value;
  1464. return true;
  1465. }
  1466. }
  1467. return false;
  1468. }
  1469. virtual unsigned getNumStatistics() const override
  1470. {
  1471. return stats.ordinality();
  1472. }
  1473. virtual void getStatistic(StatisticKind & kind, unsigned __int64 & value, unsigned idx) const override
  1474. {
  1475. const Statistic & cur = stats.item(idx);
  1476. kind = cur.kind;
  1477. value = cur.value;
  1478. }
  1479. virtual IStatisticCollectionIterator & getScopes(const char * filter, bool sorted) override
  1480. {
  1481. assertex(!filter);
  1482. Owned<IStatisticCollectionIterator> hashIter = new SuperHashIIteratorOf<IStatisticCollection, IStatisticCollectionIterator, false>(children);
  1483. if (!sorted)
  1484. return *hashIter.getClear();
  1485. return * new SortedCollectionIterator(*hashIter);
  1486. }
  1487. virtual void getMinMaxScope(IStringVal & minValue, IStringVal & maxValue, StatisticScopeType searchScopeType) const override
  1488. {
  1489. if (id.queryScopeType() == searchScopeType)
  1490. {
  1491. const char * curMin = minValue.str();
  1492. const char * curMax = maxValue.str();
  1493. StringBuffer name;
  1494. id.getScopeText(name);
  1495. if (!curMin || !*curMin || strcmp(name.str(), curMin) < 0)
  1496. minValue.set(name.str());
  1497. if (!curMax || strcmp(name.str(), curMax) > 0)
  1498. maxValue.set(name.str());
  1499. }
  1500. for (auto & curChild : children)
  1501. curChild.getMinMaxScope(minValue, maxValue, searchScopeType);
  1502. }
  1503. virtual void getMinMaxActivity(unsigned & minValue, unsigned & maxValue) const override
  1504. {
  1505. unsigned activityId = id.queryActivity();
  1506. if (activityId)
  1507. {
  1508. if ((minValue == 0) || (activityId < minValue))
  1509. minValue = activityId;
  1510. if (activityId > maxValue)
  1511. maxValue = activityId;
  1512. }
  1513. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1514. for (iter.first(); iter.isValid(); iter.next())
  1515. iter.query().getMinMaxActivity(minValue, maxValue);
  1516. }
  1517. //other public interface functions
  1518. void addStatistic(StatisticKind kind, unsigned __int64 value)
  1519. {
  1520. Statistic s(kind, value);
  1521. stats.append(s);
  1522. }
  1523. void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  1524. {
  1525. if (mergeAction != StatsMergeAppend)
  1526. {
  1527. ForEachItemIn(i, stats)
  1528. {
  1529. Statistic & cur = stats.element(i);
  1530. if (cur.kind == kind)
  1531. {
  1532. cur.value = mergeStatisticValue(cur.value, value, mergeAction);
  1533. return;
  1534. }
  1535. }
  1536. }
  1537. Statistic s(kind, value);
  1538. stats.append(s);
  1539. }
  1540. CStatisticCollection * ensureSubScope(const StatsScopeId & search, bool hasChildren)
  1541. {
  1542. //MORE: Implement hasChildren
  1543. return resolveSubScope(search, true, false);
  1544. }
  1545. CStatisticCollection * resolveSubScope(const StatsScopeId & search, bool create, bool replace)
  1546. {
  1547. if (!replace)
  1548. {
  1549. CStatisticCollection * match = children.find(&search);
  1550. if (match)
  1551. return LINK(match);
  1552. }
  1553. if (create)
  1554. {
  1555. CStatisticCollection * ret = new CStatisticCollection(this, search);
  1556. children.add(*ret);
  1557. return LINK(ret);
  1558. }
  1559. return NULL;
  1560. }
  1561. virtual void serialize(MemoryBuffer & out) const
  1562. {
  1563. out.append(getCollectionType());
  1564. id.serialize(out);
  1565. out.append(stats.ordinality());
  1566. ForEachItemIn(iStat, stats)
  1567. stats.item(iStat).serialize(out);
  1568. out.append(children.ordinality());
  1569. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1570. for (iter.first(); iter.isValid(); iter.next())
  1571. iter.query().serialize(out);
  1572. }
  1573. inline const StatsScopeId & queryScopeId() const { return id; }
  1574. virtual void mergeInto(IStatisticGatherer & target) const
  1575. {
  1576. StatsOptScope block(target, id);
  1577. ForEachItemIn(iStat, stats)
  1578. stats.item(iStat).mergeInto(target);
  1579. for (auto const & cur : children)
  1580. cur.mergeInto(target);
  1581. }
  1582. private:
  1583. StatsScopeId id;
  1584. CStatisticCollection * parent;
  1585. CollectionHashTable children;
  1586. StatsArray stats;
  1587. };
  1588. StringBuffer &CStatisticCollection::toXML(StringBuffer &out) const
  1589. {
  1590. out.append("<Scope id=\"");
  1591. id.getScopeText(out).append("\">\n");
  1592. if (stats.ordinality())
  1593. {
  1594. out.append(" <Stats>");
  1595. ForEachItemIn(i, stats)
  1596. stats.item(i).toXML(out);
  1597. out.append(" </Stats>\n");
  1598. }
  1599. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1600. for (iter.first(); iter.isValid(); iter.next())
  1601. iter.query().toXML(out);
  1602. out.append("</Scope>\n");
  1603. return out;
  1604. }
  1605. static int compareCollection(IInterface * const * pl, IInterface * const *pr)
  1606. {
  1607. CStatisticCollection * l = static_cast<CStatisticCollection *>(static_cast<IStatisticCollection *>(*pl));
  1608. CStatisticCollection * r = static_cast<CStatisticCollection *>(static_cast<IStatisticCollection *>(*pr));
  1609. return l->queryScopeId().compare(r->queryScopeId());
  1610. }
  1611. //---------------------------------------------------------------------------------------------------------------------
  1612. void CollectionHashTable::onAdd(void *et)
  1613. {
  1614. }
  1615. void CollectionHashTable::onRemove(void *et)
  1616. {
  1617. CStatisticCollection * elem = reinterpret_cast<CStatisticCollection *>(et);
  1618. elem->Release();
  1619. }
  1620. unsigned CollectionHashTable::getHashFromElement(const void *et) const
  1621. {
  1622. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1623. return elem->id.getHash();
  1624. }
  1625. unsigned CollectionHashTable::getHashFromFindParam(const void *fp) const
  1626. {
  1627. const StatsScopeId * search = reinterpret_cast<const StatsScopeId *>(fp);
  1628. return search->getHash();
  1629. }
  1630. const void * CollectionHashTable::getFindParam(const void *et) const
  1631. {
  1632. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1633. return &elem->id;
  1634. }
  1635. bool CollectionHashTable::matchesFindParam(const void *et, const void *key, unsigned fphash) const
  1636. {
  1637. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1638. const StatsScopeId * search = reinterpret_cast<const StatsScopeId *>(key);
  1639. return elem->id.matches(*search);
  1640. }
  1641. bool CollectionHashTable::matchesElement(const void *et, const void *searchET) const
  1642. {
  1643. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1644. const CStatisticCollection * searchElem = reinterpret_cast<const CStatisticCollection *>(searchET);
  1645. return elem->id.matches(searchElem->id);
  1646. }
  1647. //---------------------------------------------------------------------------------------------------------------------
  1648. class CRootStatisticCollection : public CStatisticCollection
  1649. {
  1650. public:
  1651. CRootStatisticCollection(StatisticCreatorType _creatorType, const char * _creator, const StatsScopeId & _id)
  1652. : CStatisticCollection(NULL, _id), creatorType(_creatorType), creator(_creator)
  1653. {
  1654. whenCreated = getTimeStampNowValue();
  1655. }
  1656. CRootStatisticCollection(MemoryBuffer & in, unsigned version) : CStatisticCollection(NULL, in, version)
  1657. {
  1658. byte creatorTypeByte;
  1659. in.read(creatorTypeByte);
  1660. creatorType = (StatisticCreatorType)creatorTypeByte;
  1661. in.read(creator);
  1662. in.read(whenCreated);
  1663. }
  1664. virtual byte getCollectionType() const { return SCroot; }
  1665. virtual unsigned __int64 queryWhenCreated() const
  1666. {
  1667. return whenCreated;
  1668. }
  1669. virtual void serialize(MemoryBuffer & out) const
  1670. {
  1671. CStatisticCollection::serialize(out);
  1672. out.append((byte)creatorType);
  1673. out.append(creator);
  1674. out.append(whenCreated);
  1675. }
  1676. public:
  1677. StatisticCreatorType creatorType;
  1678. StringAttr creator;
  1679. unsigned __int64 whenCreated;
  1680. };
  1681. //---------------------------------------------------------------------------------------------------------------------
  1682. void serializeStatisticCollection(MemoryBuffer & out, IStatisticCollection * collection)
  1683. {
  1684. out.append(currentStatisticsVersion);
  1685. collection->serialize(out);
  1686. }
  1687. static CStatisticCollection * deserializeCollection(CStatisticCollection * parent, MemoryBuffer & in, unsigned version)
  1688. {
  1689. byte kind;
  1690. in.read(kind);
  1691. switch (kind)
  1692. {
  1693. case SCroot:
  1694. assertex(!parent);
  1695. return new CRootStatisticCollection(in, version);
  1696. case SCintermediate:
  1697. return new CStatisticCollection(parent, in, version);
  1698. default:
  1699. UNIMPLEMENTED;
  1700. }
  1701. }
  1702. IStatisticCollection * createStatisticCollection(MemoryBuffer & in)
  1703. {
  1704. unsigned version;
  1705. in.read(version);
  1706. return deserializeCollection(NULL, in, version);
  1707. }
  1708. //--------------------------------------------------------------------------------------------------------------------
  1709. class StatisticGatherer : implements CInterfaceOf<IStatisticGatherer>
  1710. {
  1711. public:
  1712. StatisticGatherer(CStatisticCollection * scope) : rootScope(scope)
  1713. {
  1714. scopes.append(*scope);
  1715. }
  1716. virtual void beginScope(const StatsScopeId & id) override
  1717. {
  1718. CStatisticCollection & tos = scopes.tos();
  1719. scopes.append(*tos.ensureSubScope(id, true));
  1720. }
  1721. virtual void beginActivityScope(unsigned id) override
  1722. {
  1723. StatsScopeId scopeId(SSTactivity, id);
  1724. CStatisticCollection & tos = scopes.tos();
  1725. scopes.append(*tos.ensureSubScope(scopeId, false));
  1726. }
  1727. virtual void beginSubGraphScope(unsigned id) override
  1728. {
  1729. StatsScopeId scopeId(SSTsubgraph, id);
  1730. CStatisticCollection & tos = scopes.tos();
  1731. scopes.append(*tos.ensureSubScope(scopeId, true));
  1732. }
  1733. virtual void beginEdgeScope(unsigned id, unsigned oid) override
  1734. {
  1735. StatsScopeId scopeId(SSTedge, id, oid);
  1736. CStatisticCollection & tos = scopes.tos();
  1737. scopes.append(*tos.ensureSubScope(scopeId, false));
  1738. }
  1739. virtual void beginChildGraphScope(unsigned id) override
  1740. {
  1741. StatsScopeId scopeId(SSTchildgraph, id);
  1742. CStatisticCollection & tos = scopes.tos();
  1743. scopes.append(*tos.ensureSubScope(scopeId, true));
  1744. }
  1745. virtual void endScope() override
  1746. {
  1747. scopes.tos().Release();
  1748. scopes.pop();
  1749. }
  1750. virtual void addStatistic(StatisticKind kind, unsigned __int64 value) override
  1751. {
  1752. CStatisticCollection & tos = scopes.tos();
  1753. tos.addStatistic(kind, value);
  1754. }
  1755. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction) override
  1756. {
  1757. CStatisticCollection & tos = scopes.tos();
  1758. tos.updateStatistic(kind, value, mergeAction);
  1759. }
  1760. virtual IStatisticCollection * getResult() override
  1761. {
  1762. return LINK(rootScope);
  1763. }
  1764. protected:
  1765. ICopyArrayOf<CStatisticCollection> scopes;
  1766. Linked<CStatisticCollection> rootScope;
  1767. };
  1768. extern IStatisticGatherer * createStatisticsGatherer(StatisticCreatorType creatorType, const char * creator, const StatsScopeId & rootScope)
  1769. {
  1770. //creator unused at the moment.
  1771. Owned<CStatisticCollection> rootCollection = new CRootStatisticCollection(creatorType, creator, rootScope);
  1772. return new StatisticGatherer(rootCollection);
  1773. }
  1774. //--------------------------------------------------------------------------------------------------------------------
  1775. extern IPropertyTree * selectTreeStat(IPropertyTree *node, const char *statName, const char *statType)
  1776. {
  1777. StringBuffer xpath;
  1778. xpath.appendf("att[@name='%s']", statName);
  1779. IPropertyTree *att = node->queryPropTree(xpath.str());
  1780. if (!att)
  1781. {
  1782. att = node->addPropTree("att", createPTree());
  1783. att->setProp("@name", statName);
  1784. att->setProp("@type", statType);
  1785. }
  1786. return att;
  1787. }
  1788. extern void putStatsTreeValue(IPropertyTree *node, const char *statName, const char *statType, unsigned __int64 val)
  1789. {
  1790. if (val)
  1791. selectTreeStat(node, statName, statType)->setPropInt64("@value", val);
  1792. }
  1793. class TreeNodeStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  1794. {
  1795. public:
  1796. TreeNodeStatisticGatherer(IPropertyTree & root) : node(&root) {}
  1797. virtual void beginScope(const StatsScopeId & id)
  1798. {
  1799. StringBuffer temp;
  1800. id.getScopeText(temp);
  1801. beginScope(temp.str());
  1802. }
  1803. virtual void beginSubGraphScope(unsigned id) { throwUnexpected(); }
  1804. virtual void beginChildGraphScope(unsigned id) { throwUnexpected(); }
  1805. virtual void beginActivityScope(unsigned id) { throwUnexpected(); }
  1806. virtual void beginEdgeScope(unsigned id, unsigned oid) { throwUnexpected(); }
  1807. virtual void endScope()
  1808. {
  1809. node = &stack.popGet();
  1810. }
  1811. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  1812. {
  1813. putStatsTreeValue(node, queryStatisticName(kind), "sum", value);
  1814. }
  1815. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  1816. {
  1817. if (value)
  1818. {
  1819. IPropertyTree * stat = selectTreeStat(node, queryStatisticName(kind), "sum");
  1820. unsigned __int64 newValue = mergeStatisticValue(stat->getPropInt64("@value"), value, mergeAction);
  1821. stat->setPropInt64("@value", newValue);
  1822. }
  1823. }
  1824. virtual IStatisticCollection * getResult() { throwUnexpected(); }
  1825. protected:
  1826. void beginScope(const char * id)
  1827. {
  1828. stack.append(*node);
  1829. StringBuffer xpath;
  1830. xpath.appendf("scope[@name='%s']", id);
  1831. IPropertyTree *att = node->queryPropTree(xpath.str());
  1832. if (!att)
  1833. {
  1834. att = node->addPropTree("scope", createPTree());
  1835. att->setProp("@name", id);
  1836. }
  1837. node = att;
  1838. }
  1839. protected:
  1840. IPropertyTree * node;
  1841. ICopyArrayOf<IPropertyTree> stack;
  1842. };
  1843. //--------------------------------------------------------------------------------------------------------------------
  1844. void CRuntimeStatistic::merge(unsigned __int64 otherValue, StatsMergeAction mergeAction)
  1845. {
  1846. value = mergeStatisticValue(value, otherValue, mergeAction);
  1847. }
  1848. //--------------------------------------------------------------------------------------------------------------------
  1849. CRuntimeStatisticCollection::~CRuntimeStatisticCollection()
  1850. {
  1851. delete [] values;
  1852. delete queryNested();
  1853. }
  1854. CNestedRuntimeStatisticMap * CRuntimeStatisticCollection::queryNested() const
  1855. {
  1856. return nested.load(std::memory_order_relaxed);
  1857. }
  1858. CNestedRuntimeStatisticMap * CRuntimeStatisticCollection::createNested() const
  1859. {
  1860. return new CNestedRuntimeStatisticMap;
  1861. }
  1862. CNestedRuntimeStatisticMap & CRuntimeStatisticCollection::ensureNested()
  1863. {
  1864. return *querySingleton(nested, nestlock, [this]{ return this->createNested(); });
  1865. }
  1866. CriticalSection CRuntimeStatisticCollection::nestlock;
  1867. unsigned __int64 CRuntimeStatisticCollection::getSerialStatisticValue(StatisticKind kind) const
  1868. {
  1869. unsigned __int64 value = getStatisticValue(kind);
  1870. StatisticKind rawKind= queryRawKind(kind);
  1871. if (kind == rawKind)
  1872. return value;
  1873. unsigned __int64 rawValue = getStatisticValue(rawKind);
  1874. return value + convertMeasure(rawKind, kind, rawValue);
  1875. }
  1876. void CRuntimeStatisticCollection::merge(const CRuntimeStatisticCollection & other)
  1877. {
  1878. if (&mapping == &other.mapping)
  1879. {
  1880. ForEachItemIn(i, other)
  1881. {
  1882. unsigned __int64 value = other.values[i].get();
  1883. if (value)
  1884. {
  1885. StatisticKind kind = getKind(i);
  1886. values[i].merge(value, queryMergeMode(kind));
  1887. }
  1888. }
  1889. }
  1890. else
  1891. {
  1892. ForEachItemIn(i, other)
  1893. {
  1894. StatisticKind kind = other.getKind(i);
  1895. unsigned __int64 value = other.getStatisticValue(kind);
  1896. if (value)
  1897. mergeStatistic(kind, value);
  1898. }
  1899. }
  1900. CNestedRuntimeStatisticMap *otherNested = other.queryNested();
  1901. if (otherNested)
  1902. {
  1903. ensureNested().merge(*otherNested);
  1904. }
  1905. }
  1906. void CRuntimeStatisticCollection::updateDelta(CRuntimeStatisticCollection & target, const CRuntimeStatisticCollection & source)
  1907. {
  1908. ForEachItemIn(i, source)
  1909. {
  1910. StatisticKind kind = source.getKind(i);
  1911. unsigned __int64 sourceValue = source.getStatisticValue(kind);
  1912. if (queryMergeMode(kind) == StatsMergeSum)
  1913. {
  1914. unsigned __int64 prevValue = getStatisticValue(kind);
  1915. if (sourceValue != prevValue)
  1916. {
  1917. target.mergeStatistic(kind, sourceValue - prevValue);
  1918. setStatistic(kind, sourceValue);
  1919. }
  1920. }
  1921. else
  1922. {
  1923. if (sourceValue)
  1924. target.mergeStatistic(kind, sourceValue);
  1925. }
  1926. }
  1927. CNestedRuntimeStatisticMap *sourceNested = source.queryNested();
  1928. if (sourceNested)
  1929. {
  1930. ensureNested().updateDelta(target.ensureNested(), *sourceNested);
  1931. }
  1932. }
  1933. void CRuntimeStatisticCollection::mergeStatistic(StatisticKind kind, unsigned __int64 value)
  1934. {
  1935. queryStatistic(kind).merge(value, queryMergeMode(kind));
  1936. }
  1937. void CRuntimeStatisticCollection::reset()
  1938. {
  1939. unsigned num = mapping.numStatistics();
  1940. for (unsigned i = 0; i <= num; i++)
  1941. values[i].clear();
  1942. }
  1943. void CRuntimeStatisticCollection::reset(const StatisticsMapping & toClear)
  1944. {
  1945. unsigned num = toClear.numStatistics();
  1946. for (unsigned i = 0; i < num; i++)
  1947. queryStatistic(toClear.getKind(i)).clear();
  1948. }
  1949. CRuntimeStatisticCollection & CRuntimeStatisticCollection::registerNested(const StatsScopeId & scope, const StatisticsMapping & mapping)
  1950. {
  1951. return ensureNested().addNested(scope, mapping).queryStats();
  1952. }
  1953. void CRuntimeStatisticCollection::rollupStatistics(unsigned numTargets, IContextLogger * const * targets) const
  1954. {
  1955. ForEachItem(iStat)
  1956. {
  1957. unsigned __int64 value = values[iStat].getClear();
  1958. if (value)
  1959. {
  1960. StatisticKind kind = getKind(iStat);
  1961. for (unsigned iTarget = 0; iTarget < numTargets; iTarget++)
  1962. targets[iTarget]->noteStatistic(kind, value);
  1963. }
  1964. }
  1965. reportIgnoredStats();
  1966. }
  1967. void CRuntimeStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  1968. {
  1969. ForEachItem(i)
  1970. {
  1971. unsigned __int64 value = values[i].get();
  1972. if (value)
  1973. {
  1974. StatisticKind kind = getKind(i);
  1975. StatisticKind serialKind= querySerializedKind(kind);
  1976. if (kind != serialKind)
  1977. value = convertMeasure(kind, serialKind, value);
  1978. StatsMergeAction mergeAction = queryMergeMode(serialKind);
  1979. target.updateStatistic(serialKind, value, mergeAction);
  1980. }
  1981. }
  1982. reportIgnoredStats();
  1983. CNestedRuntimeStatisticMap *qn = queryNested();
  1984. if (qn)
  1985. qn->recordStatistics(target);
  1986. }
  1987. void CRuntimeStatisticCollection::reportIgnoredStats() const
  1988. {
  1989. if (values[mapping.numStatistics()].getClear())
  1990. DBGLOG("Some statistics were added but thrown away");
  1991. }
  1992. StringBuffer & CRuntimeStatisticCollection::toXML(StringBuffer &str) const
  1993. {
  1994. ForEachItem(iStat)
  1995. {
  1996. unsigned __int64 value = values[iStat].get();
  1997. if (value)
  1998. {
  1999. StatisticKind kind = getKind(iStat);
  2000. const char * name = queryStatisticName(kind);
  2001. str.appendf("<%s>%" I64F "d</%s>", name, value, name);
  2002. }
  2003. }
  2004. CNestedRuntimeStatisticMap *qn = queryNested();
  2005. if (qn)
  2006. qn->toXML(str);
  2007. return str;
  2008. }
  2009. StringBuffer & CRuntimeStatisticCollection::toStr(StringBuffer &str) const
  2010. {
  2011. ForEachItem(iStat)
  2012. {
  2013. unsigned __int64 value = values[iStat].get();
  2014. if (value)
  2015. {
  2016. StatisticKind kind = getKind(iStat);
  2017. StatisticKind serialKind = querySerializedKind(kind);
  2018. if (kind != serialKind)
  2019. value = convertMeasure(kind, serialKind, value);
  2020. const char * name = queryStatisticName(serialKind);
  2021. str.append(' ').append(name).append("=");
  2022. formatStatistic(str, value, serialKind);
  2023. }
  2024. }
  2025. CNestedRuntimeStatisticMap *qn = queryNested();
  2026. if (qn)
  2027. qn->toStr(str);
  2028. return str;
  2029. }
  2030. void CRuntimeStatisticCollection::deserialize(MemoryBuffer& in)
  2031. {
  2032. unsigned numValid;
  2033. in.readPacked(numValid);
  2034. for (unsigned i=0; i < numValid; i++)
  2035. {
  2036. unsigned kindVal;
  2037. unsigned __int64 value;
  2038. in.readPacked(kindVal).readPacked(value);
  2039. StatisticKind kind = (StatisticKind)kindVal;
  2040. setStatistic(kind, value);
  2041. }
  2042. bool hasNested;
  2043. in.read(hasNested);
  2044. if (hasNested)
  2045. {
  2046. ensureNested().deserializeMerge(in);
  2047. }
  2048. }
  2049. void CRuntimeStatisticCollection::deserializeMerge(MemoryBuffer& in)
  2050. {
  2051. unsigned numValid;
  2052. in.readPacked(numValid);
  2053. for (unsigned i=0; i < numValid; i++)
  2054. {
  2055. unsigned kindVal;
  2056. unsigned __int64 value;
  2057. in.readPacked(kindVal).readPacked(value);
  2058. StatisticKind kind = (StatisticKind)kindVal;
  2059. StatsMergeAction mergeAction = queryMergeMode(kind);
  2060. mergeStatistic(kind, value, mergeAction);
  2061. }
  2062. bool hasNested;
  2063. in.read(hasNested);
  2064. if (hasNested)
  2065. {
  2066. ensureNested().deserializeMerge(in);
  2067. }
  2068. }
  2069. void CRuntimeStatisticCollection::getNodeProgressInfo(IPropertyTree &node) const
  2070. {
  2071. TreeNodeStatisticGatherer gatherer(node);
  2072. recordStatistics(gatherer);
  2073. }
  2074. bool CRuntimeStatisticCollection::serialize(MemoryBuffer& out) const
  2075. {
  2076. unsigned numValid = 0;
  2077. ForEachItem(i1)
  2078. {
  2079. if (values[i1].get())
  2080. numValid++;
  2081. }
  2082. out.appendPacked(numValid);
  2083. ForEachItem(i2)
  2084. {
  2085. unsigned __int64 value = values[i2].get();
  2086. if (value)
  2087. {
  2088. StatisticKind kind = mapping.getKind(i2);
  2089. StatisticKind serialKind= querySerializedKind(kind);
  2090. if (kind != serialKind)
  2091. value = convertMeasure(kind, serialKind, value);
  2092. out.appendPacked((unsigned)serialKind);
  2093. out.appendPacked(value);
  2094. }
  2095. }
  2096. bool nonEmpty = (numValid != 0);
  2097. CNestedRuntimeStatisticMap *qn = queryNested();
  2098. out.append(qn != nullptr);
  2099. if (qn)
  2100. {
  2101. if (qn->serialize(out))
  2102. nonEmpty = true;
  2103. }
  2104. return nonEmpty;
  2105. }
  2106. //---------------------------------------------------------------------------------------------------------------------
  2107. void CRuntimeSummaryStatisticCollection::DerivedStats::mergeStatistic(unsigned __int64 value, unsigned node)
  2108. {
  2109. if (count == 0)
  2110. {
  2111. min = value;
  2112. max = value;
  2113. minNode = node;
  2114. maxNode = node;
  2115. }
  2116. else
  2117. {
  2118. if (value < min)
  2119. {
  2120. min = value;
  2121. minNode = node;
  2122. }
  2123. if (value > max)
  2124. {
  2125. max = value;
  2126. maxNode = node;
  2127. }
  2128. }
  2129. count++;
  2130. double dvalue = (double)value;
  2131. sumSquares += dvalue * dvalue;
  2132. }
  2133. CRuntimeSummaryStatisticCollection::CRuntimeSummaryStatisticCollection(const StatisticsMapping & _mapping) : CRuntimeStatisticCollection(_mapping)
  2134. {
  2135. derived = new DerivedStats[ordinality()+1];
  2136. }
  2137. CRuntimeSummaryStatisticCollection::~CRuntimeSummaryStatisticCollection()
  2138. {
  2139. delete[] derived;
  2140. }
  2141. CNestedRuntimeStatisticMap * CRuntimeSummaryStatisticCollection::createNested() const
  2142. {
  2143. return new CNestedSummaryRuntimeStatisticMap;
  2144. }
  2145. void CRuntimeSummaryStatisticCollection::mergeStatistic(StatisticKind kind, unsigned __int64 value)
  2146. {
  2147. CRuntimeStatisticCollection::mergeStatistic(kind, value);
  2148. unsigned index = queryMapping().getIndex(kind);
  2149. derived[index].mergeStatistic(value, 0);
  2150. }
  2151. static bool isSignificantSkew(StatisticKind kind, unsigned __int64 range, unsigned __int64 count)
  2152. {
  2153. //MORE: Could get more sophisticated!
  2154. return range > 1;
  2155. }
  2156. void CRuntimeSummaryStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  2157. {
  2158. CRuntimeStatisticCollection::recordStatistics(target);
  2159. for (unsigned i = 0; i < ordinality(); i++)
  2160. {
  2161. DerivedStats & cur = derived[i];
  2162. if (cur.count)
  2163. {
  2164. StatisticKind kind = getKind(i);
  2165. StatisticKind serialKind= querySerializedKind(kind);
  2166. unsigned __int64 minValue = convertMeasure(kind, serialKind, cur.min);
  2167. unsigned __int64 maxValue = convertMeasure(kind, serialKind, cur.max);
  2168. if (minValue != maxValue)
  2169. {
  2170. double sum = (double)convertMeasure(kind, serialKind, values[i].get());
  2171. //Sum of squares needs to be translated twice
  2172. double sumSquares = convertSquareMeasure(kind, serialKind, cur.sumSquares);
  2173. double mean = (double)(sum / cur.count);
  2174. double variance = (sumSquares - sum * mean) / cur.count;
  2175. double stdDev = sqrt(variance);
  2176. double maxSkew = (10000.0 * ((maxValue-mean)/mean));
  2177. double minSkew = (10000.0 * ((mean-minValue)/mean));
  2178. unsigned __int64 range = maxValue - minValue;
  2179. target.addStatistic((StatisticKind)(serialKind|StMinX), minValue);
  2180. target.addStatistic((StatisticKind)(serialKind|StMaxX), maxValue);
  2181. target.addStatistic((StatisticKind)(serialKind|StAvgX), (unsigned __int64)mean);
  2182. target.addStatistic((StatisticKind)(serialKind|StDeltaX), range);
  2183. target.addStatistic((StatisticKind)(serialKind|StStdDevX), (unsigned __int64)stdDev);
  2184. //If all nodes are the same then we re actually merging results from multiple runs
  2185. //if the range is less than the count then
  2186. if ((cur.minNode != cur.maxNode) && isSignificantSkew(serialKind, range, cur.count))
  2187. {
  2188. target.addStatistic((StatisticKind)(serialKind|StSkewMin), (unsigned __int64)minSkew);
  2189. target.addStatistic((StatisticKind)(serialKind|StSkewMax), (unsigned __int64)maxSkew);
  2190. target.addStatistic((StatisticKind)(serialKind|StNodeMin), cur.minNode);
  2191. target.addStatistic((StatisticKind)(serialKind|StNodeMax), cur.maxNode);
  2192. }
  2193. }
  2194. else if (cur.count != 1)
  2195. target.addStatistic((StatisticKind)(serialKind|StAvgX), minValue);
  2196. }
  2197. }
  2198. }
  2199. bool CRuntimeSummaryStatisticCollection::serialize(MemoryBuffer & out) const
  2200. {
  2201. UNIMPLEMENTED; // NB: Need to convert sum squares twice.
  2202. }
  2203. void CRuntimeSummaryStatisticCollection::deserialize(MemoryBuffer & in)
  2204. {
  2205. UNIMPLEMENTED;
  2206. }
  2207. void CRuntimeSummaryStatisticCollection::deserializeMerge(MemoryBuffer& in)
  2208. {
  2209. UNIMPLEMENTED;
  2210. }
  2211. //---------------------------------------------------
  2212. bool CNestedRuntimeStatisticCollection::matches(const StatsScopeId & otherScope) const
  2213. {
  2214. return scope.matches(otherScope);
  2215. }
  2216. //NOTE: When deserializing, the scope is deserialized by the caller, and the correct target selected
  2217. //which is why there is no corresponding deserialize() ofthe scope at this point
  2218. void CNestedRuntimeStatisticCollection::deserialize(MemoryBuffer & in)
  2219. {
  2220. stats->deserialize(in);
  2221. }
  2222. void CNestedRuntimeStatisticCollection::deserializeMerge(MemoryBuffer& in)
  2223. {
  2224. stats->deserialize(in);
  2225. }
  2226. void CNestedRuntimeStatisticCollection::merge(const CNestedRuntimeStatisticCollection & other)
  2227. {
  2228. stats->merge(other.queryStats());
  2229. }
  2230. bool CNestedRuntimeStatisticCollection::serialize(MemoryBuffer& out) const
  2231. {
  2232. scope.serialize(out);
  2233. return stats->serialize(out);
  2234. }
  2235. void CNestedRuntimeStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  2236. {
  2237. target.beginScope(scope);
  2238. stats->recordStatistics(target);
  2239. target.endScope();
  2240. }
  2241. StringBuffer & CNestedRuntimeStatisticCollection::toStr(StringBuffer &str) const
  2242. {
  2243. str.append(' ');
  2244. scope.getScopeText(str).append("={");
  2245. stats->toStr(str);
  2246. return str.append(" }");
  2247. }
  2248. StringBuffer & CNestedRuntimeStatisticCollection::toXML(StringBuffer &str) const
  2249. {
  2250. str.append("<Scope id=\"");
  2251. scope.getScopeText(str).append("\">");
  2252. stats->toXML(str);
  2253. return str.append("</Scope>");
  2254. }
  2255. void CNestedRuntimeStatisticCollection::updateDelta(CNestedRuntimeStatisticCollection & target, const CNestedRuntimeStatisticCollection & source)
  2256. {
  2257. stats->updateDelta(*target.stats, *source.stats);
  2258. }
  2259. //---------------------------------------------------
  2260. CNestedRuntimeStatisticCollection & CNestedRuntimeStatisticMap::addNested(const StatsScopeId & scope, const StatisticsMapping & mapping)
  2261. {
  2262. unsigned mapSize;
  2263. unsigned entry;
  2264. {
  2265. ReadLockBlock b(lock);
  2266. mapSize = map.length();
  2267. for (entry = 0; entry < mapSize; entry++)
  2268. {
  2269. CNestedRuntimeStatisticCollection & cur = map.item(entry);
  2270. if (cur.matches(scope))
  2271. return cur;
  2272. }
  2273. }
  2274. {
  2275. WriteLockBlock b(lock);
  2276. // Check no-one added anything between the read and write locks
  2277. mapSize = map.length();
  2278. for (; entry < mapSize; entry++)
  2279. {
  2280. CNestedRuntimeStatisticCollection & cur = map.item(entry);
  2281. if (cur.matches(scope))
  2282. return cur;
  2283. }
  2284. CNestedRuntimeStatisticCollection * stats = new CNestedRuntimeStatisticCollection(scope, createStats(mapping));
  2285. map.append(*stats);
  2286. return *stats;
  2287. }
  2288. }
  2289. void CNestedRuntimeStatisticMap::deserialize(MemoryBuffer& in)
  2290. {
  2291. unsigned numItems;
  2292. in.readPacked(numItems);
  2293. for (unsigned i=0; i < numItems; i++)
  2294. {
  2295. StatsScopeId scope;
  2296. scope.deserialize(in, currentStatisticsVersion);
  2297. //Use allStatistics as the default mapping if it hasn't already been added.
  2298. CNestedRuntimeStatisticCollection & child = addNested(scope, allStatistics);
  2299. child.deserialize(in);
  2300. }
  2301. }
  2302. void CNestedRuntimeStatisticMap::deserializeMerge(MemoryBuffer& in)
  2303. {
  2304. unsigned numItems;
  2305. in.readPacked(numItems);
  2306. for (unsigned i=0; i < numItems; i++)
  2307. {
  2308. StatsScopeId scope;
  2309. scope.deserialize(in, currentStatisticsVersion);
  2310. //Use allStatistics as the default mapping if it hasn't already been added.
  2311. CNestedRuntimeStatisticCollection & child = addNested(scope, allStatistics);
  2312. child.deserializeMerge(in);
  2313. }
  2314. }
  2315. void CNestedRuntimeStatisticMap::merge(const CNestedRuntimeStatisticMap & other)
  2316. {
  2317. ReadLockBlock b(other.lock);
  2318. ForEachItemIn(i, other.map)
  2319. {
  2320. CNestedRuntimeStatisticCollection & cur = other.map.item(i);
  2321. CNestedRuntimeStatisticCollection & target = addNested(cur.scope, cur.queryMapping());
  2322. target.merge(cur);
  2323. }
  2324. }
  2325. void CNestedRuntimeStatisticMap::updateDelta(CNestedRuntimeStatisticMap & target, const CNestedRuntimeStatisticMap & source)
  2326. {
  2327. ReadLockBlock b(source.lock);
  2328. ForEachItemIn(i, source.map)
  2329. {
  2330. CNestedRuntimeStatisticCollection & curSource = source.map.item(i);
  2331. CNestedRuntimeStatisticCollection & curTarget = target.addNested(curSource.scope, curSource.queryMapping());
  2332. CNestedRuntimeStatisticCollection & curDelta = addNested(curSource.scope, curSource.queryMapping());
  2333. curDelta.updateDelta(curTarget, curSource);
  2334. }
  2335. }
  2336. bool CNestedRuntimeStatisticMap::serialize(MemoryBuffer& out) const
  2337. {
  2338. ReadLockBlock b(lock);
  2339. out.appendPacked(map.ordinality());
  2340. bool nonEmpty = false;
  2341. ForEachItemIn(i, map)
  2342. {
  2343. if (map.item(i).serialize(out))
  2344. nonEmpty = true;
  2345. }
  2346. return nonEmpty;
  2347. }
  2348. void CNestedRuntimeStatisticMap::recordStatistics(IStatisticGatherer & target) const
  2349. {
  2350. ReadLockBlock b(lock);
  2351. ForEachItemIn(i, map)
  2352. map.item(i).recordStatistics(target);
  2353. }
  2354. StringBuffer & CNestedRuntimeStatisticMap::toStr(StringBuffer &str) const
  2355. {
  2356. ReadLockBlock b(lock);
  2357. ForEachItemIn(i, map)
  2358. map.item(i).toStr(str);
  2359. return str;
  2360. }
  2361. StringBuffer & CNestedRuntimeStatisticMap::toXML(StringBuffer &str) const
  2362. {
  2363. ReadLockBlock b(lock);
  2364. ForEachItemIn(i, map)
  2365. map.item(i).toXML(str);
  2366. return str;
  2367. }
  2368. CRuntimeStatisticCollection * CNestedRuntimeStatisticMap::createStats(const StatisticsMapping & mapping)
  2369. {
  2370. return new CRuntimeStatisticCollection(mapping);
  2371. }
  2372. CRuntimeStatisticCollection * CNestedSummaryRuntimeStatisticMap::createStats(const StatisticsMapping & mapping)
  2373. {
  2374. return new CRuntimeSummaryStatisticCollection(mapping);
  2375. }
  2376. //---------------------------------------------------
  2377. void StatsAggregation::noteValue(stat_type value)
  2378. {
  2379. if (count == 0)
  2380. {
  2381. minValue = value;
  2382. maxValue = value;
  2383. }
  2384. else
  2385. {
  2386. if (value < minValue)
  2387. minValue = value;
  2388. else if (value > maxValue)
  2389. maxValue = value;
  2390. }
  2391. count++;
  2392. sumValue += value;
  2393. }
  2394. stat_type StatsAggregation::getAve() const
  2395. {
  2396. return (sumValue / count);
  2397. }
  2398. //---------------------------------------------------
  2399. ScopeCompare compareScopes(const char * scope, const char * key)
  2400. {
  2401. byte left = *scope;
  2402. byte right = *key;
  2403. //Check for root scope "" compared with anything
  2404. if (!left)
  2405. {
  2406. if (!right)
  2407. return SCequal;
  2408. return SCparent;
  2409. }
  2410. else if (!right)
  2411. {
  2412. return SCchild;
  2413. }
  2414. bool hadCommonScope = false;
  2415. for (;;)
  2416. {
  2417. if (left != right)
  2418. {
  2419. //FUTURE: Extend this function to support skipping numbers to allow wildcard matching
  2420. if (!left)
  2421. {
  2422. if (right == ':')
  2423. return SCparent; // scope is a parent (prefix) of the key
  2424. }
  2425. if (!right)
  2426. {
  2427. if (left == ':')
  2428. return SCchild; // scope is a child (superset) of the key
  2429. }
  2430. return hadCommonScope ? SCrelated : SCunrelated;
  2431. }
  2432. if (!left)
  2433. return SCequal;
  2434. if (left == ':')
  2435. hadCommonScope = true;
  2436. left = *++scope;
  2437. right =*++key;
  2438. }
  2439. }
  2440. ScopeFilter::ScopeFilter(const char * scopeList)
  2441. {
  2442. //MORE: This currently expands a list of scopes - it should probably be improved
  2443. scopes.appendList(scopeList, ",");
  2444. }
  2445. void ScopeFilter::addScope(const char * scope)
  2446. {
  2447. if (!scope)
  2448. return;
  2449. if (streq(scope, "*"))
  2450. {
  2451. scopes.kill();
  2452. minDepth = 0;
  2453. maxDepth = UINT_MAX;
  2454. return;
  2455. }
  2456. if (ids)
  2457. throw makeStringExceptionV(0, "Cannot filter by id and scope in the same request");
  2458. unsigned depth = queryScopeDepth(scope);
  2459. if ((scopes.ordinality() == 0) || (depth < minDepth))
  2460. minDepth = depth;
  2461. if ((scopes.ordinality() == 0) || (depth > maxDepth))
  2462. maxDepth = depth;
  2463. scopes.append(scope);
  2464. }
  2465. void ScopeFilter::addScopes(const char * scope)
  2466. {
  2467. StringArray list;
  2468. list.appendList(scope, ",");
  2469. ForEachItemIn(i, list)
  2470. addScope(list.item(i));
  2471. }
  2472. void ScopeFilter::addScopeType(StatisticScopeType scopeType)
  2473. {
  2474. if (scopeType == SSTall)
  2475. return;
  2476. scopeTypes.append(scopeType);
  2477. }
  2478. void ScopeFilter::addId(const char * id)
  2479. {
  2480. if (scopes)
  2481. throw makeStringExceptionV(0, "Cannot filter by id and scope in the same request");
  2482. ids.append(id);
  2483. }
  2484. void ScopeFilter::setDepth(unsigned low, unsigned high)
  2485. {
  2486. if (low > high)
  2487. throw makeStringExceptionV(0, "Depth parameters in wrong order %u..%u", low, high);
  2488. minDepth = low;
  2489. maxDepth = high;
  2490. }
  2491. void ScopeFilter::intersectDepth(const unsigned low, const unsigned high)
  2492. {
  2493. if (low > high)
  2494. throw makeStringExceptionV(0, "Depth parameters in wrong order %u..%u", low, high);
  2495. if (minDepth < low)
  2496. minDepth = low;
  2497. if (maxDepth > high)
  2498. maxDepth = high;
  2499. }
  2500. ScopeCompare ScopeFilter::compare(const char * scope) const
  2501. {
  2502. ScopeCompare result = SCunknown;
  2503. if (scopes)
  2504. {
  2505. //If scopes have been provided, then we are searching for an exact match against that scope
  2506. ForEachItemIn(i, scopes)
  2507. result |= compareScopes(scope, scopes.item(i));
  2508. }
  2509. else
  2510. {
  2511. //How does the depth of the scope compare with the range we are expecting?
  2512. unsigned depth = queryScopeDepth(scope);
  2513. if (depth < minDepth)
  2514. return SCparent;
  2515. if (depth > maxDepth)
  2516. return SCchild;
  2517. //Assume it is a match until proven otherwise
  2518. result |= SCequal;
  2519. // Could be the child of a match
  2520. if (depth > minDepth)
  2521. result |= SCchild;
  2522. //Could be the parent of a match
  2523. if (depth < maxDepth)
  2524. result |= SCparent;
  2525. //Check if the type of the current object matches the type
  2526. const char * tail = queryScopeTail(scope);
  2527. if (scopeTypes.ordinality())
  2528. {
  2529. StatsScopeId id(tail);
  2530. if (!scopeTypes.contains(id.queryScopeType()))
  2531. result &= ~SCequal;
  2532. }
  2533. if (ids)
  2534. {
  2535. if (!ids.contains(tail))
  2536. result &= ~SCequal;
  2537. }
  2538. }
  2539. if (!(result & SCequal))
  2540. return result;
  2541. //Have a match - now check that the attributes match as required
  2542. //MORE:
  2543. if (false)
  2544. {
  2545. result &= ~SCequal;
  2546. }
  2547. return result;
  2548. }
  2549. bool ScopeFilter::canAlwaysPreFilter() const
  2550. {
  2551. //If the only filter being applied is a restriction on the minimum depth, then you can always apply it as a pre-filter
  2552. return (!ids && !scopeTypes && !scopes && maxDepth == UINT_MAX);
  2553. }
  2554. int ScopeFilter::compareDepth(unsigned depth) const
  2555. {
  2556. if (depth < minDepth)
  2557. return -1;
  2558. if (depth > maxDepth)
  2559. return +1;
  2560. return 0;
  2561. }
  2562. void ScopeFilter::finishedFilter()
  2563. {
  2564. //If scopeTypes are provided, then this code ensure that any scopes and ids match them
  2565. //but that would have little benefit, and would cause complications if the only id was removed
  2566. //Some scope types can only exist at a single level.
  2567. if (scopeTypes.ordinality() == 1)
  2568. {
  2569. switch (scopeTypes.item(0))
  2570. {
  2571. case SSTglobal:
  2572. intersectDepth(0, 0);
  2573. break;
  2574. case SSTworkflow:
  2575. intersectDepth(1, 1);
  2576. break;
  2577. case SSTgraph:
  2578. intersectDepth(2, 2);
  2579. break;
  2580. case SSTsubgraph:
  2581. intersectDepth(3, UINT_MAX);
  2582. break;
  2583. case SSTactivity:
  2584. intersectDepth(4, UINT_MAX);
  2585. break;
  2586. }
  2587. }
  2588. }
  2589. bool ScopeFilter::hasSingleMatch() const
  2590. {
  2591. return scopes.ordinality() == 1 || ids.ordinality() == 1;
  2592. }
  2593. bool ScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2594. {
  2595. if ((scopeTypes.ordinality() == 1) && (scopeTypes.item(0) == scopeType))
  2596. return true;
  2597. //Check the types of the scopes that are being searched
  2598. if (scopes.ordinality())
  2599. {
  2600. ForEachItemIn(i, scopes)
  2601. {
  2602. const char * scopeId = queryScopeTail(scopes.item(i));
  2603. StatsScopeId id(scopeId);
  2604. if (id.queryScopeType() != scopeType)
  2605. return false;
  2606. }
  2607. return true;
  2608. }
  2609. if (ids.ordinality())
  2610. {
  2611. ForEachItemIn(i, ids)
  2612. {
  2613. const char * scopeId = ids.item(i);
  2614. StatsScopeId id(scopeId);
  2615. if (id.queryScopeType() != scopeType)
  2616. return false;
  2617. }
  2618. return true;
  2619. }
  2620. return false;
  2621. }
  2622. //---------------------------------------------------
  2623. bool ScopedItemFilter::matchDepth(unsigned low, unsigned high) const
  2624. {
  2625. if (maxDepth && low && maxDepth < low)
  2626. return false;
  2627. if (minDepth && high && minDepth > high)
  2628. return false;
  2629. return true;
  2630. }
  2631. bool ScopedItemFilter::match(const char * search) const
  2632. {
  2633. if (search)
  2634. {
  2635. if (value)
  2636. {
  2637. if (hasWildcard)
  2638. {
  2639. //MORE: If wildcarding ends up being used a lot then this should be replaced with something that creates a DFA
  2640. if (!WildMatch(search, value, false))
  2641. return false;
  2642. }
  2643. else
  2644. {
  2645. return streq(search, value);
  2646. }
  2647. }
  2648. if (minDepth || maxDepth)
  2649. {
  2650. unsigned searchDepth = queryScopeDepth(search);
  2651. if (searchDepth < minDepth)
  2652. return false;
  2653. if (maxDepth && searchDepth > maxDepth)
  2654. return false;
  2655. }
  2656. }
  2657. return true;
  2658. }
  2659. bool ScopedItemFilter::recurseChildScopes(const char * curScope) const
  2660. {
  2661. if (maxDepth == 0 || !curScope)
  2662. return true;
  2663. if (queryScopeDepth(curScope) >= maxDepth)
  2664. return false;
  2665. return true;
  2666. }
  2667. void ScopedItemFilter::set(const char * _value)
  2668. {
  2669. if (_value && !streq(_value, "*") )
  2670. {
  2671. value.set(_value);
  2672. minDepth = queryScopeDepth(_value);
  2673. if (!strchr(_value, '*'))
  2674. {
  2675. maxDepth = minDepth;
  2676. hasWildcard = strchr(_value, '?') != NULL;
  2677. }
  2678. else
  2679. hasWildcard = true;
  2680. }
  2681. else
  2682. value.clear();
  2683. }
  2684. void ScopedItemFilter::setDepth(unsigned _depth)
  2685. {
  2686. minDepth = _depth;
  2687. maxDepth = _depth;
  2688. }
  2689. void ScopedItemFilter::setDepth(unsigned _minDepth, unsigned _maxDepth)
  2690. {
  2691. minDepth = _minDepth;
  2692. maxDepth = _maxDepth;
  2693. }
  2694. StatisticsFilter::StatisticsFilter()
  2695. {
  2696. init();
  2697. }
  2698. StatisticsFilter::StatisticsFilter(const char * filter)
  2699. {
  2700. init();
  2701. setFilter(filter);
  2702. }
  2703. StatisticsFilter::StatisticsFilter(StatisticCreatorType _creatorType, StatisticScopeType _scopeType, StatisticMeasure _measure, StatisticKind _kind)
  2704. {
  2705. init();
  2706. creatorType = _creatorType;
  2707. scopeType = _scopeType;
  2708. measure = _measure;
  2709. kind = _kind;
  2710. }
  2711. StatisticsFilter::StatisticsFilter(const char * _creatorType, const char * _scopeType, const char * _kind)
  2712. {
  2713. init();
  2714. set(_creatorType, _scopeType, _kind);
  2715. }
  2716. StatisticsFilter::StatisticsFilter(const char * _creatorTypeText, const char * _creator, const char * _scopeTypeText, const char * _scope, const char * _measureText, const char * _kindText)
  2717. {
  2718. init();
  2719. set(_creatorTypeText, _creator, _scopeTypeText, _scope, _measureText, _kindText);
  2720. }
  2721. StatisticsFilter::StatisticsFilter(StatisticCreatorType _creatorType, const char * _creator, StatisticScopeType _scopeType, const char * _scope, StatisticMeasure _measure, StatisticKind _kind)
  2722. {
  2723. init();
  2724. creatorType = _creatorType;
  2725. setCreator(_creator);
  2726. scopeType = _scopeType;
  2727. setScope(_scope);
  2728. measure = _measure;
  2729. kind = _kind;
  2730. }
  2731. void StatisticsFilter::init()
  2732. {
  2733. creatorType = SCTall;
  2734. scopeType = SSTall;
  2735. measure = SMeasureAll;
  2736. kind = StKindAll;
  2737. }
  2738. bool StatisticsFilter::matches(StatisticCreatorType curCreatorType, const char * curCreator, StatisticScopeType curScopeType, const char * curScope, StatisticMeasure curMeasure, StatisticKind curKind, unsigned __int64 value) const
  2739. {
  2740. if ((curCreatorType != SCTall) && (creatorType != SCTall) && (creatorType != curCreatorType))
  2741. return false;
  2742. if ((curScopeType != SSTall) && (scopeType != SSTall) && (scopeType != curScopeType))
  2743. return false;
  2744. if ((curMeasure != SMeasureAll) && (measure != SMeasureAll) && (measure != curMeasure))
  2745. return false;
  2746. if ((curKind!= StKindAll) && (kind != StKindAll) && (kind != curKind))
  2747. return false;
  2748. if (!creatorFilter.match(curCreator))
  2749. return false;
  2750. if (!scopeFilter.match(curScope))
  2751. return false;
  2752. if (value != MaxStatisticValue)
  2753. {
  2754. if ((value < minValue) || (value > maxValue))
  2755. return false;
  2756. }
  2757. return true;
  2758. }
  2759. bool StatisticsFilter::recurseChildScopes(StatisticScopeType curScopeType, const char * curScope) const
  2760. {
  2761. switch (curScopeType)
  2762. {
  2763. case SSTgraph:
  2764. // A child of a graph will have depth 2 or more
  2765. if (!scopeFilter.matchDepth(2, (unsigned)-1))
  2766. return false;
  2767. break;
  2768. case SSTsubgraph:
  2769. // A child of a subgraph will have depth 3 or more
  2770. if (!scopeFilter.matchDepth(3, (unsigned)-1))
  2771. return false;
  2772. break;
  2773. }
  2774. if (!curScope)
  2775. return true;
  2776. return scopeFilter.recurseChildScopes(curScope);
  2777. }
  2778. void StatisticsFilter::set(const char * creatorTypeText, const char * scopeTypeText, const char * kindText)
  2779. {
  2780. StatisticCreatorType creatorType = queryCreatorType(creatorTypeText, SCTnone);
  2781. StatisticScopeType scopeType = queryScopeType(scopeTypeText, SSTnone);
  2782. if (creatorType != SCTnone)
  2783. setCreatorType(creatorType);
  2784. if (scopeType != SSTnone)
  2785. setScopeType(scopeType);
  2786. setKind(kindText);
  2787. }
  2788. void StatisticsFilter::set(const char * _creatorTypeText, const char * _creator, const char * _scopeTypeText, const char * _scope, const char * _measureText, const char * _kindText)
  2789. {
  2790. StatisticMeasure newMeasure = queryMeasure(_measureText, SMeasureNone);
  2791. if (newMeasure != SMeasureNone)
  2792. setMeasure(newMeasure);
  2793. set(_creatorTypeText, _scopeTypeText, _kindText);
  2794. setCreator(_creator);
  2795. setScope(_scope);
  2796. }
  2797. void StatisticsFilter::setCreatorDepth(unsigned _minCreatorDepth, unsigned _maxCreatorDepth)
  2798. {
  2799. creatorFilter.setDepth(_minCreatorDepth, _maxCreatorDepth);
  2800. }
  2801. void StatisticsFilter::setCreator(const char * _creator)
  2802. {
  2803. creatorFilter.set(_creator);
  2804. }
  2805. void StatisticsFilter::setCreatorType(StatisticCreatorType _creatorType)
  2806. {
  2807. creatorType = _creatorType;
  2808. }
  2809. void StatisticsFilter::addFilter(const char * filter)
  2810. {
  2811. //Match a filter of the form category[value] (use square brackets to avoid bash grief)
  2812. const char * openBra = strchr(filter, '[');
  2813. if (!openBra)
  2814. return;
  2815. const char * closeBra = strchr(openBra, ']');
  2816. if (!closeBra)
  2817. return;
  2818. const char * start = openBra + 1;
  2819. StringBuffer value(closeBra - start, start);
  2820. if (hasPrefix(filter, "creator[", false))
  2821. setCreator(value);
  2822. else if (hasPrefix(filter, "creatortype[", false))
  2823. setCreatorType(queryCreatorType(value, SCTall));
  2824. else if (hasPrefix(filter, "depth[", false))
  2825. {
  2826. const char * comma = strchr(value, ',');
  2827. if (comma)
  2828. setScopeDepth(atoi(value), atoi(comma+1));
  2829. else
  2830. setScopeDepth(atoi(value));
  2831. }
  2832. else if (hasPrefix(filter, "kind[", false))
  2833. setKind(value);
  2834. else if (hasPrefix(filter, "measure[", false))
  2835. setMeasure(queryMeasure(value, SMeasureAll));
  2836. else if (hasPrefix(filter, "scope[", false))
  2837. setScope(value);
  2838. else if (hasPrefix(filter, "scopetype[", false))
  2839. setScopeType(queryScopeType(value, SSTall));
  2840. else if (hasPrefix(filter, "value[", false))
  2841. {
  2842. //value[exact|low..high] where low and high are optional
  2843. unsigned __int64 lowValue = 0;
  2844. unsigned __int64 highValue = MaxStatisticValue;
  2845. if (isdigit(*value))
  2846. lowValue = (unsigned __int64)atoi64(value);
  2847. const char * dotdot = strstr(value, "..");
  2848. if (dotdot)
  2849. {
  2850. unsigned __int64 maxValue = (unsigned __int64)atoi64(dotdot + 2);
  2851. if (maxValue != 0)
  2852. highValue = maxValue;
  2853. }
  2854. else
  2855. highValue = lowValue;
  2856. setValueRange(lowValue, highValue);
  2857. }
  2858. else
  2859. throw MakeStringException(1, "Unknown stats filter '%s' - expected creator,creatortype,depth,kind,measure,scope,scopetype", filter);
  2860. }
  2861. void StatisticsFilter::setFilter(const char * filter)
  2862. {
  2863. if (isEmptyString(filter))
  2864. return;
  2865. for (;;)
  2866. {
  2867. const char * closeBra = strchr(filter, ']');
  2868. if (!closeBra)
  2869. throw MakeStringException(1, "Missing close bracket ']' in '%s' ", filter);
  2870. const char * comma = strchr(closeBra, ',');
  2871. if (comma)
  2872. {
  2873. //Take a copy - simplicity rather than efficiency
  2874. StringBuffer temp(comma - filter, filter);
  2875. addFilter(temp);
  2876. filter = comma + 1;
  2877. }
  2878. else
  2879. {
  2880. addFilter(filter);
  2881. return;
  2882. }
  2883. }
  2884. }
  2885. void StatisticsFilter::setScopeDepth(unsigned _scopeDepth)
  2886. {
  2887. scopeFilter.setDepth(_scopeDepth);
  2888. }
  2889. void StatisticsFilter::setScopeDepth(unsigned _minScopeDepth, unsigned _maxScopeDepth)
  2890. {
  2891. scopeFilter.setDepth(_minScopeDepth, _maxScopeDepth);
  2892. }
  2893. void StatisticsFilter::setScope(const char * _scope)
  2894. {
  2895. scopeFilter.set(_scope);
  2896. }
  2897. void StatisticsFilter::setScopeType(StatisticScopeType _scopeType)
  2898. {
  2899. scopeType = _scopeType;
  2900. switch (scopeType)
  2901. {
  2902. case SSTglobal:
  2903. case SSTgraph:
  2904. scopeFilter.setDepth(1);
  2905. break;
  2906. case SSTsubgraph:
  2907. scopeFilter.setDepth(2);
  2908. break;
  2909. case SSTactivity:
  2910. scopeFilter.setDepth(3);
  2911. break;
  2912. }
  2913. }
  2914. void StatisticsFilter::setMeasure(StatisticMeasure _measure)
  2915. {
  2916. measure = _measure;
  2917. }
  2918. void StatisticsFilter::setValueRange(unsigned __int64 _minValue, unsigned __int64 _maxValue)
  2919. {
  2920. minValue = _minValue;
  2921. maxValue = _maxValue;
  2922. }
  2923. void StatisticsFilter::setKind(StatisticKind _kind)
  2924. {
  2925. kind = _kind;
  2926. if (measure == SMeasureAll)
  2927. measure = queryMeasure(kind);
  2928. }
  2929. void StatisticsFilter::setKind(const char * _kind)
  2930. {
  2931. if (!_kind || !*_kind || streq(_kind, "*"))
  2932. {
  2933. if (measure == SMeasureNone)
  2934. measure = SMeasureAll;
  2935. kind = StKindAll;
  2936. return;
  2937. }
  2938. //Convert a kind wildcard to a measure
  2939. for (unsigned i1=SMeasureAll+1; i1 < SMeasureMax; i1++)
  2940. {
  2941. const char * prefix = queryMeasurePrefix((StatisticMeasure)i1);
  2942. size_t len = strlen(prefix);
  2943. if (len && strnicmp(_kind, prefix, len) == 0)
  2944. {
  2945. setMeasure((StatisticMeasure)i1);
  2946. //Treat When* and When as filters on times.
  2947. if (streq(_kind + len, "*") || !_kind[len])
  2948. return;
  2949. }
  2950. }
  2951. //Other wildcards not currently supported
  2952. kind = queryStatisticKind(_kind, StKindAll);
  2953. }
  2954. //---------------------------------------------------
  2955. class CStatsCategory : public CInterface
  2956. {
  2957. public:
  2958. StringAttr longName;
  2959. StringAttr shortName;
  2960. CStatsCategory(const char *_longName, const char *_shortName)
  2961. : longName(_longName), shortName(_shortName)
  2962. {
  2963. }
  2964. bool match(const char *_longName, const char *_shortName)
  2965. {
  2966. bool lm = stricmp(_longName, longName)==0;
  2967. bool sm = stricmp(_shortName, shortName)==0;
  2968. if (lm || sm)
  2969. {
  2970. if (lm && sm)
  2971. return true;
  2972. throw MakeStringException(0, "A stats category %s (%s) is already registered", shortName.get(), longName.get());
  2973. }
  2974. return false;
  2975. }
  2976. };
  2977. static CIArrayOf<CStatsCategory> statsCategories;
  2978. static CriticalSection statsCategoriesCrit;
  2979. extern int registerStatsCategory(const char *longName, const char *shortName)
  2980. {
  2981. CriticalBlock b(statsCategoriesCrit);
  2982. ForEachItemIn(idx, statsCategories)
  2983. {
  2984. if (statsCategories.item(idx).match(longName, shortName))
  2985. return idx;
  2986. }
  2987. statsCategories.append(*new CStatsCategory(longName, shortName));
  2988. return statsCategories.ordinality()-1;
  2989. }
  2990. static void checkKind(StatisticKind kind)
  2991. {
  2992. if (kind < StMax)
  2993. {
  2994. const StatisticMeta & meta = statsMetaData[kind];
  2995. if (meta.kind != kind)
  2996. throw makeStringExceptionV(0, "Statistic %u in the wrong order", kind);
  2997. }
  2998. StatisticKind serialKind = querySerializedKind(kind);
  2999. StatisticKind rawKind = queryRawKind(kind);
  3000. if (kind != serialKind)
  3001. assertex(queryRawKind(serialKind) == kind);
  3002. if (kind != rawKind)
  3003. assertex(querySerializedKind(rawKind) == kind);
  3004. StatisticMeasure measure = queryMeasure(kind);
  3005. const char * shortName = queryStatisticName(kind);
  3006. StringBuffer longName;
  3007. queryLongStatisticName(longName, kind);
  3008. const char * tagName __attribute__ ((unused)) = queryTreeTag(kind);
  3009. const char * prefix = queryMeasurePrefix(measure);
  3010. //Check short names are all correctly prefixed.
  3011. assertex(strncmp(shortName, prefix, strlen(prefix)) == 0);
  3012. }
  3013. static void checkDistributedKind(StatisticKind kind)
  3014. {
  3015. checkKind(kind);
  3016. checkKind((StatisticKind)(kind|StMinX));
  3017. checkKind((StatisticKind)(kind|StMaxX));
  3018. checkKind((StatisticKind)(kind|StAvgX));
  3019. checkKind((StatisticKind)(kind|StSkew));
  3020. checkKind((StatisticKind)(kind|StSkewMin));
  3021. checkKind((StatisticKind)(kind|StSkewMax));
  3022. checkKind((StatisticKind)(kind|StNodeMin));
  3023. checkKind((StatisticKind)(kind|StNodeMax));
  3024. checkKind((StatisticKind)(kind|StDeltaX));
  3025. }
  3026. void verifyStatisticFunctions()
  3027. {
  3028. static_assert(_elements_in(measureNames) == SMeasureMax+1 && !measureNames[SMeasureMax], "measureNames needs updating");
  3029. static_assert(_elements_in(creatorTypeNames) == SCTmax+1 && !creatorTypeNames[SCTmax], "creatorTypeNames needs updating");
  3030. static_assert(_elements_in(scopeTypeNames) == SSTmax+1 && !scopeTypeNames[SSTmax], "scopeTypeNames needs updating");
  3031. //Check the various functions return values for all possible values.
  3032. for (unsigned i1=SMeasureAll; i1 < SMeasureMax; i1++)
  3033. {
  3034. const char * prefix __attribute__((unused)) = queryMeasurePrefix((StatisticMeasure)i1);
  3035. const char * name = queryMeasureName((StatisticMeasure)i1);
  3036. assertex(queryMeasure(name, SMeasureMax) == i1);
  3037. }
  3038. for (StatisticScopeType sst = SSTnone; sst < SSTmax; sst = (StatisticScopeType)(sst+1))
  3039. {
  3040. const char * name = queryScopeTypeName(sst);
  3041. assertex(queryScopeType(name, SSTmax) == sst);
  3042. }
  3043. for (StatisticCreatorType sct = SCTnone; sct < SCTmax; sct = (StatisticCreatorType)(sct+1))
  3044. {
  3045. const char * name = queryCreatorTypeName(sct);
  3046. assertex(queryCreatorType(name, SCTmax) == sct);
  3047. }
  3048. for (unsigned i2=StKindAll+1; i2 < StMax; i2++)
  3049. {
  3050. checkDistributedKind((StatisticKind)i2);
  3051. }
  3052. }
  3053. #if 0
  3054. MODULE_INIT(INIT_PRIORITY_STANDARD)
  3055. {
  3056. verifyStatisticFunctions();
  3057. return true;
  3058. }
  3059. #endif