jstats.cpp 95 KB

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