jstats.cpp 100 KB

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