jstats.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586
  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 const char * const measureNames[] = { "", "all", "ns", "ts", "cnt", "sz", "cpu", "skw", "node", "ppm", "ip", "cy", NULL };
  55. static const char * const creatorTypeNames[]= { "", "all", "unknown", "hthor", "roxie", "roxie:s", "thor", "thor:m", "thor:s", "eclcc", "esp", "summary", NULL };
  56. static const char * const scopeTypeNames[] = { "", "all", "global", "graph", "subgraph", "activity", "allocator", "section", "compile", "dfu", "edge", "function", NULL };
  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. loop
  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. extern jlib_decl unsigned __int64 getTimeStampNowValue()
  76. {
  77. #ifdef _WIN32
  78. struct _timeb now;
  79. _ftime(&now);
  80. return (unsigned __int64)now.time * I64C(1000000) + now.millitm * 1000;
  81. #else
  82. struct timeval tm;
  83. gettimeofday(&tm,NULL);
  84. return (unsigned __int64)tm.tv_sec * I64C(1000000) + tm.tv_usec;
  85. #endif
  86. }
  87. const static unsigned __int64 msUntilResync = 1000; // resync every second ~= 1ms accuracy
  88. static cycle_t cyclesUntilResync;
  89. MODULE_INIT(INIT_PRIORITY_STANDARD)
  90. {
  91. cyclesUntilResync = nanosec_to_cycle(msUntilResync * 1000000);
  92. return true;
  93. }
  94. OptimizedTimestamp::OptimizedTimestamp()
  95. {
  96. lastCycles = get_cycles_now();
  97. lastTimestamp = ::getTimeStampNowValue();
  98. }
  99. #if 0
  100. //This version almost certainly has problems if the computer is suspended and cycles->nanoseconds is only accurate to
  101. //about 0.1% - so should only be used for relatively short periods
  102. unsigned __int64 OptimizedTimestamp::getTimeStampNowValue()
  103. {
  104. cycle_t nowCycles = get_cycles_now();
  105. return lastTimestamp + cycle_to_microsec(nowCycles - lastCycles);
  106. }
  107. #else
  108. //This version will resync every minute, but is not thread safe. Adding a critical section makes it less efficient than recalculating
  109. unsigned __int64 OptimizedTimestamp::getTimeStampNowValue()
  110. {
  111. cycle_t nowCycles = get_cycles_now();
  112. if (nowCycles - lastCycles > cyclesUntilResync)
  113. {
  114. lastCycles = nowCycles;
  115. lastTimestamp = ::getTimeStampNowValue();
  116. }
  117. return lastTimestamp + cycle_to_microsec(nowCycles - lastCycles);
  118. }
  119. #endif
  120. unsigned __int64 getIPV4StatsValue(const IpAddress & ip)
  121. {
  122. unsigned ipValue;
  123. if (ip.getNetAddress(sizeof(ipValue),&ipValue))
  124. return ipValue;
  125. return 0;
  126. }
  127. //--------------------------------------------------------------------------------------------------------------------
  128. const static unsigned __int64 oneMilliSecond = I64C(1000000);
  129. const static unsigned __int64 oneSecond = I64C(1000000000);
  130. const static unsigned __int64 oneMinute = I64C(60000000000);
  131. const static unsigned __int64 oneHour = I64C(3600000000000);
  132. const static unsigned __int64 oneDay = 24 * I64C(3600000000000);
  133. static void formatTime(StringBuffer & out, unsigned __int64 value)
  134. {
  135. //Aim to display at least 3 significant digits in the result string
  136. if (value < oneMilliSecond)
  137. out.appendf("%uns", (unsigned)value);
  138. else if (value < oneSecond)
  139. {
  140. unsigned uvalue = (unsigned)value;
  141. out.appendf("%u.%03ums", uvalue / 1000000, (uvalue / 1000) % 1000);
  142. }
  143. else
  144. {
  145. unsigned days = (unsigned)(value / oneDay);
  146. value = value % oneDay;
  147. unsigned hours = (unsigned)(value / oneHour);
  148. value = value % oneHour;
  149. unsigned mins = (unsigned)(value / oneMinute);
  150. value = value % oneMinute;
  151. unsigned secs = (unsigned)(value / oneSecond);
  152. unsigned ns = (unsigned)(value % oneSecond);
  153. if (days > 0)
  154. out.appendf("%u days ", days);
  155. if (hours > 0 || days)
  156. out.appendf("%u:%02u:%02u", hours, mins, secs);
  157. else if (mins >= 10)
  158. out.appendf("%u:%02u", mins, secs);
  159. else if (mins >= 1)
  160. out.appendf("%u:%02u.%03u", mins, secs, ns / 1000000);
  161. else
  162. out.appendf("%u.%03us", secs, ns / 1000000);
  163. }
  164. }
  165. extern void formatTimeCollatable(StringBuffer & out, unsigned __int64 value, bool nano)
  166. {
  167. unsigned days = (unsigned)(value / oneDay);
  168. value = value % oneDay;
  169. unsigned hours = (unsigned)(value / oneHour);
  170. value = value % oneHour;
  171. unsigned mins = (unsigned)(value / oneMinute);
  172. value = value % oneMinute;
  173. unsigned secs = (unsigned)(value / oneSecond);
  174. unsigned ns = (unsigned)(value % oneSecond);
  175. if (days)
  176. out.appendf(" %3ud ", days); // Two leading spaces helps the cassandra driver force to a single partition
  177. else
  178. out.appendf(" ");
  179. if (nano)
  180. out.appendf("%2u:%02u:%02u.%09u", hours, mins, secs, ns);
  181. else
  182. out.appendf("%2u:%02u:%02u.%03u", hours, mins, secs, ns/1000000);
  183. // More than 999 days, I don't care that it goes wrong.
  184. }
  185. extern unsigned __int64 extractTimeCollatable(const char *s, bool nano)
  186. {
  187. if (!s)
  188. return 0;
  189. unsigned days,hours,mins,secs,fracs;
  190. if (sscanf(s, " %ud %u:%u:%u.%u", &days, &hours, &mins, &secs, &fracs)!=5)
  191. {
  192. days = 0;
  193. if (sscanf(s, " %u:%u:%u.%u", &hours, &mins, &secs, &fracs) != 4)
  194. return 0;
  195. }
  196. unsigned __int64 ret = days*oneDay + hours*oneHour + mins*oneMinute + secs*oneSecond;
  197. if (nano)
  198. ret += fracs;
  199. else
  200. ret += milliToNano(fracs);
  201. return ret;
  202. }
  203. static void formatTimeStamp(StringBuffer & out, unsigned __int64 value)
  204. {
  205. time_t seconds = value / 1000000;
  206. unsigned us = value % 1000000;
  207. char timeStamp[64];
  208. time_t tNow = seconds;
  209. #ifdef _WIN32
  210. struct tm *gmtNow;
  211. gmtNow = gmtime(&tNow);
  212. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%S", gmtNow);
  213. #else
  214. struct tm gmtNow;
  215. gmtime_r(&tNow, &gmtNow);
  216. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%S", &gmtNow);
  217. #endif //_WIN32
  218. out.append(timeStamp).appendf(".%03uZ", us / 1000);
  219. }
  220. void formatTimeStampAsLocalTime(StringBuffer & out, unsigned __int64 value)
  221. {
  222. time_t seconds = value / 1000000;
  223. unsigned us = value % 1000000;
  224. char timeStamp[64];
  225. time_t tNow = seconds;
  226. #ifdef _WIN32
  227. struct tm *gmtNow;
  228. gmtNow = localtime(&tNow);
  229. strftime(timeStamp, 64, "%H:%M:%S", gmtNow);
  230. #else
  231. struct tm gmtNow;
  232. localtime_r(&tNow, &gmtNow);
  233. strftime(timeStamp, 64, "%H:%M:%S", &gmtNow);
  234. #endif //_WIN32
  235. out.append(timeStamp).appendf(".%03u", us / 1000);
  236. }
  237. static const unsigned oneKb = 1024;
  238. static const unsigned oneMb = 1024 * 1024;
  239. static const unsigned oneGb = 1024 * 1024 * 1024;
  240. static unsigned toPermille(unsigned x) { return (x * 1000) / 1024; }
  241. static void formatSize(StringBuffer & out, unsigned __int64 value)
  242. {
  243. unsigned Gb = (unsigned)(value / oneGb);
  244. unsigned Mb = (unsigned)((value % oneGb) / oneMb);
  245. unsigned Kb = (unsigned)((value % oneMb) / oneKb);
  246. unsigned b = (unsigned)(value % oneKb);
  247. if (Gb)
  248. out.appendf("%u.%03uGb", Gb, toPermille(Mb));
  249. else if (Mb)
  250. out.appendf("%u.%03uMb", Mb, toPermille(Kb));
  251. else if (Kb)
  252. out.appendf("%u.%03uKb", Kb, toPermille(b));
  253. else
  254. out.appendf("%ub", b);
  255. }
  256. static void formatLoad(StringBuffer & out, unsigned __int64 value)
  257. {
  258. //Stored as millionth of a core. Display as a percentage => scale by 10,000
  259. out.appendf("%u.%03u%%", (unsigned)(value / 10000), (unsigned)(value % 10000) / 10);
  260. }
  261. static void formatSkew(StringBuffer & out, unsigned __int64 value)
  262. {
  263. //Skew stored as 10000 = perfect, display as percentage
  264. out.appendf("%.2f%%", ((double)(__int64)value) / 100.0);
  265. }
  266. static void formatIPV4(StringBuffer & out, unsigned __int64 value)
  267. {
  268. byte ip1 = (value & 255);
  269. byte ip2 = ((value >> 8) & 255);
  270. byte ip3 = ((value >> 16) & 255);
  271. byte ip4 = ((value >> 24) & 255);
  272. out.appendf("%d.%d.%d.%d", ip1, ip2, ip3, ip4);
  273. }
  274. void formatStatistic(StringBuffer & out, unsigned __int64 value, StatisticMeasure measure)
  275. {
  276. switch (measure)
  277. {
  278. case SMeasureNone: // Unknown stat - e.g, on old esp accessing a new workunit
  279. out.append(value);
  280. break;
  281. case SMeasureTimeNs:
  282. formatTime(out, value);
  283. break;
  284. case SMeasureTimestampUs:
  285. formatTimeStamp(out, value);
  286. break;
  287. case SMeasureCount:
  288. out.append(value);
  289. break;
  290. case SMeasureSize:
  291. formatSize(out, value);
  292. break;
  293. case SMeasureLoad:
  294. formatLoad(out, value);
  295. break;
  296. case SMeasureSkew:
  297. formatSkew(out, value);
  298. break;
  299. case SMeasureNode:
  300. out.append(value);
  301. break;
  302. case SMeasurePercent:
  303. out.appendf("%.2f%%", (double)value / 10000.0); // stored as ppm
  304. break;
  305. case SMeasureIPV4:
  306. formatIPV4(out, value);
  307. break;
  308. case SMeasureCycle:
  309. out.append(value);
  310. break;
  311. default:
  312. out.append(value).append('?');
  313. }
  314. }
  315. void formatStatistic(StringBuffer & out, unsigned __int64 value, StatisticKind kind)
  316. {
  317. formatStatistic(out, value, queryMeasure(kind));
  318. }
  319. //--------------------------------------------------------------------------------------------------------------------
  320. unsigned queryStatisticsDepth(const char * text)
  321. {
  322. unsigned depth = 1;
  323. loop
  324. {
  325. switch (*text)
  326. {
  327. case 0:
  328. return depth;
  329. case ':':
  330. depth++;
  331. break;
  332. }
  333. text++;
  334. }
  335. }
  336. const char * queryMeasurePrefix(StatisticMeasure measure)
  337. {
  338. switch (measure)
  339. {
  340. case SMeasureAll: return NULL;
  341. case SMeasureTimeNs: return "Time";
  342. case SMeasureTimestampUs: return "When";
  343. case SMeasureCount: return "Num";
  344. case SMeasureSize: return "Size";
  345. case SMeasureLoad: return "Load";
  346. case SMeasureSkew: return "Skew";
  347. case SMeasureNode: return "Node";
  348. case SMeasurePercent: return "Per";
  349. case SMeasureIPV4: return "Ip";
  350. case SMeasureCycle: return "Cycle";
  351. default:
  352. return "Unknown";
  353. }
  354. }
  355. const char * queryMeasureName(StatisticMeasure measure)
  356. {
  357. return measureNames[measure];
  358. }
  359. StatisticMeasure queryMeasure(const char * measure)
  360. {
  361. //MORE: Use a hash table??
  362. StatisticMeasure ret = (StatisticMeasure)matchString(measureNames, measure);
  363. //Legacy support for an unusual statistic - pretend the sizes are in bytes instead of kb.
  364. if ((ret == SMeasureNone) && measure)
  365. {
  366. if (streq(measure, "kb"))
  367. {
  368. ret = SMeasureSize;
  369. }
  370. else
  371. {
  372. for (unsigned i1=SMeasureAll+1; i1 < SMeasureMax; i1++)
  373. {
  374. const char * prefix = queryMeasurePrefix((StatisticMeasure)i1);
  375. if (strieq(measure, prefix))
  376. return (StatisticMeasure)i1;
  377. }
  378. }
  379. }
  380. return ret;
  381. }
  382. StatsMergeAction queryMergeMode(StatisticMeasure measure)
  383. {
  384. switch (measure)
  385. {
  386. case SMeasureTimeNs: return StatsMergeSum;
  387. case SMeasureTimestampUs: return StatsMergeKeepNonZero;
  388. case SMeasureCount: return StatsMergeSum;
  389. case SMeasureSize: return StatsMergeSum;
  390. case SMeasureLoad: return StatsMergeMax;
  391. case SMeasureSkew: return StatsMergeMax;
  392. case SMeasureNode: return StatsMergeKeepNonZero;
  393. case SMeasurePercent: return StatsMergeReplace;
  394. case SMeasureIPV4: return StatsMergeKeepNonZero;
  395. case SMeasureCycle: return StatsMergeSum;
  396. default:
  397. #ifdef _DEBUG
  398. throwUnexpected();
  399. #else
  400. return StatsMergeSum;
  401. #endif
  402. }
  403. }
  404. extern jlib_decl StatsMergeAction queryMergeMode(StatisticKind kind)
  405. {
  406. //MORE: Optimize by looking up in the meta
  407. return queryMergeMode(queryMeasure(kind));
  408. }
  409. //--------------------------------------------------------------------------------------------------------------------
  410. #define BASE_NAMES(x, y) \
  411. #x #y, \
  412. #x "Min" # y, \
  413. #x "Max" # y, \
  414. #x "Avg" # y, \
  415. "Skew" # y, \
  416. "SkewMin" # y, \
  417. "SkewMax" # y, \
  418. "NodeMin" # y, \
  419. "NodeMax" # y,
  420. #define NAMES(x, y) \
  421. BASE_NAMES(x, y) \
  422. #x "Delta" # y, \
  423. #x "StdDev" #y,
  424. #define WHENNAMES(x, y) \
  425. BASE_NAMES(x, y) \
  426. "TimeDelta" # y, \
  427. "TimeStdDev" # y,
  428. #define BASE_TAGS(x, y) \
  429. "@" #x "Min" # y, \
  430. "@" #x "Max" # y, \
  431. "@" #x "Avg" # y, \
  432. "@Skew" # y, \
  433. "@SkewMin" # y, \
  434. "@SkewMax" # y, \
  435. "@NodeMin" # y, \
  436. "@NodeMax" # y,
  437. //Default tags nothing special overriden
  438. #define TAGS(x, y) \
  439. "@" #x #y, \
  440. BASE_TAGS(x, y) \
  441. "@" #x "Delta" # y, \
  442. "@" #x "StdDev" # y,
  443. //Define the tags for time items.
  444. #define WHENTAGS(x, y) \
  445. "@" #x #y, \
  446. BASE_TAGS(x, y) \
  447. "@TimeDelta" # y, \
  448. "@TimeStdDev" # y,
  449. #define CORESTAT(x, y, m) St##x##y, m, St##x##y, { NAMES(x, y) }, { TAGS(x, y) }
  450. #define STAT(x, y, m) CORESTAT(x, y, m)
  451. //--------------------------------------------------------------------------------------------------------------------
  452. //These are the macros to use to define the different entries in the stats meta table
  453. #define TIMESTAT(y) STAT(Time, y, SMeasureTimeNs)
  454. #define WHENSTAT(y) St##When##y, SMeasureTimestampUs, St##When##y, { WHENNAMES(When, y) }, { WHENTAGS(When, y) }
  455. #define NUMSTAT(y) STAT(Num, y, SMeasureCount)
  456. #define SIZESTAT(y) STAT(Size, y, SMeasureSize)
  457. #define LOADSTAT(y) STAT(Load, y, SMeasureLoad)
  458. #define SKEWSTAT(y) STAT(Skew, y, SMeasureSkew)
  459. #define NODESTAT(y) STAT(Node, y, SMeasureNode)
  460. #define PERSTAT(y) STAT(Per, y, SMeasurePercent)
  461. #define IPV4STAT(y) STAT(IPV4, y, SMeasureIPV4)
  462. #define CYCLESTAT(y) St##Cycle##y##Cycles, SMeasureCycle, St##Time##y, { NAMES(Cycle, y##Cycles) }, { TAGS(Cycle, y##Cycles) }
  463. //--------------------------------------------------------------------------------------------------------------------
  464. class StatisticMeta
  465. {
  466. public:
  467. StatisticKind kind;
  468. StatisticMeasure measure;
  469. StatisticKind serializeKind;
  470. const char * names[StNextModifier/StVariantScale];
  471. const char * tags[StNextModifier/StVariantScale];
  472. };
  473. //The order of entries in this table must match the order in the enumeration
  474. static const StatisticMeta statsMetaData[StMax] = {
  475. { StKindNone, SMeasureNone, StKindNone, { "none" }, { "@none" } },
  476. { StKindAll, SMeasureAll, StKindAll, { "all" }, { "@all" } },
  477. { WHENSTAT(GraphStarted) },
  478. { WHENSTAT(GraphFinished) },
  479. { WHENSTAT(FirstRow) },
  480. { WHENSTAT(QueryStarted) },
  481. { WHENSTAT(QueryFinished) },
  482. { WHENSTAT(Created) },
  483. { WHENSTAT(Compiled) },
  484. { WHENSTAT(WorkunitModified) },
  485. { TIMESTAT(Elapsed) },
  486. { TIMESTAT(LocalExecute) },
  487. { TIMESTAT(TotalExecute) },
  488. { TIMESTAT(Remaining) },
  489. { SIZESTAT(GeneratedCpp) },
  490. { SIZESTAT(PeakMemory) },
  491. { SIZESTAT(MaxRowSize) },
  492. { NUMSTAT(RowsProcessed) },
  493. { NUMSTAT(Slaves) },
  494. { NUMSTAT(Started) },
  495. { NUMSTAT(Stopped) },
  496. { NUMSTAT(IndexSeeks) },
  497. { NUMSTAT(IndexScans) },
  498. { NUMSTAT(IndexWildSeeks) },
  499. { NUMSTAT(IndexSkips) },
  500. { NUMSTAT(IndexNullSkips) },
  501. { NUMSTAT(IndexMerges) },
  502. { NUMSTAT(IndexMergeCompares) },
  503. { NUMSTAT(PreFiltered) },
  504. { NUMSTAT(PostFiltered) },
  505. { NUMSTAT(BlobCacheHits) },
  506. { NUMSTAT(LeafCacheHits) },
  507. { NUMSTAT(NodeCacheHits) },
  508. { NUMSTAT(BlobCacheAdds) },
  509. { NUMSTAT(LeafCacheAdds) },
  510. { NUMSTAT(NodeCacheAdds) },
  511. { NUMSTAT(PreloadCacheHits) },
  512. { NUMSTAT(PreloadCacheAdds) },
  513. { NUMSTAT(ServerCacheHits) },
  514. { NUMSTAT(IndexAccepted) },
  515. { NUMSTAT(IndexRejected) },
  516. { NUMSTAT(AtmostTriggered) },
  517. { NUMSTAT(DiskSeeks) },
  518. { NUMSTAT(Iterations) },
  519. { LOADSTAT(WhileSorting) },
  520. { NUMSTAT(LeftRows) },
  521. { NUMSTAT(RightRows) },
  522. { PERSTAT(Replicated) },
  523. { NUMSTAT(DiskRowsRead) },
  524. { NUMSTAT(IndexRowsRead) },
  525. { NUMSTAT(DiskAccepted) },
  526. { NUMSTAT(DiskRejected) },
  527. { TIMESTAT(Soapcall) },
  528. { TIMESTAT(FirstExecute) },
  529. { TIMESTAT(DiskReadIO) },
  530. { TIMESTAT(DiskWriteIO) },
  531. { SIZESTAT(DiskRead) },
  532. { SIZESTAT(DiskWrite) },
  533. { CYCLESTAT(DiskReadIO) },
  534. { CYCLESTAT(DiskWriteIO) },
  535. { NUMSTAT(DiskReads) },
  536. { NUMSTAT(DiskWrites) },
  537. { NUMSTAT(Spills) },
  538. { TIMESTAT(SpillElapsed) },
  539. { TIMESTAT(SortElapsed) },
  540. { NUMSTAT(Groups) },
  541. { NUMSTAT(GroupMax) },
  542. { SIZESTAT(SpillFile) },
  543. { CYCLESTAT(SpillElapsed) },
  544. { CYCLESTAT(SortElapsed) },
  545. { NUMSTAT(Strands) },
  546. { CYCLESTAT(TotalExecute) },
  547. { NUMSTAT(Executions) },
  548. { TIMESTAT(TotalNested) },
  549. { CYCLESTAT(LocalExecute) },
  550. { NUMSTAT(Compares) },
  551. { NUMSTAT(ScansPerRow) },
  552. { NUMSTAT(Allocations) },
  553. { NUMSTAT(AllocationScans) },
  554. { NUMSTAT(DiskRetries) },
  555. };
  556. //--------------------------------------------------------------------------------------------------------------------
  557. StatisticMeasure queryMeasure(StatisticKind kind)
  558. {
  559. unsigned variant = queryStatsVariant(kind);
  560. switch (variant)
  561. {
  562. case StSkew:
  563. case StSkewMin:
  564. case StSkewMax:
  565. return SMeasureSkew;
  566. case StNodeMin:
  567. case StNodeMax:
  568. return SMeasureNode;
  569. case StDeltaX:
  570. case StStdDevX:
  571. {
  572. StatisticMeasure measure = queryMeasure((StatisticKind)(kind & StKindMask));
  573. switch (measure)
  574. {
  575. case SMeasureTimestampUs:
  576. return SMeasureTimeNs;
  577. default:
  578. return measure;
  579. }
  580. break;
  581. }
  582. }
  583. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  584. if (rawkind >= StKindNone && rawkind < StMax)
  585. return statsMetaData[rawkind].measure;
  586. return SMeasureNone;
  587. }
  588. const char * queryStatisticName(StatisticKind kind)
  589. {
  590. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  591. unsigned variant = (kind / StVariantScale);
  592. dbgassertex(variant < (StNextModifier/StVariantScale));
  593. if (rawkind >= StKindNone && rawkind < StMax)
  594. return statsMetaData[rawkind].names[variant];
  595. return "Unknown";
  596. }
  597. unsigned __int64 convertMeasure(StatisticMeasure from, StatisticMeasure to, unsigned __int64 value)
  598. {
  599. if (from == to)
  600. return value;
  601. if ((from == SMeasureCycle) && (to == SMeasureTimeNs))
  602. return cycle_to_nanosec(value);
  603. if ((from == SMeasureTimeNs) && (to == SMeasureCycle))
  604. return nanosec_to_cycle(value);
  605. #ifdef _DEBUG
  606. throwUnexpected();
  607. #else
  608. return value;
  609. #endif
  610. }
  611. unsigned __int64 convertMeasure(StatisticKind from, StatisticKind to, unsigned __int64 value)
  612. {
  613. return convertMeasure(queryMeasure(from), queryMeasure(to), value);
  614. }
  615. static double convertSquareMeasure(StatisticMeasure from, StatisticMeasure to, double value)
  616. {
  617. if (from == to)
  618. return value;
  619. const unsigned __int64 largeValue = 1000000000;
  620. double scale;
  621. if ((from == SMeasureCycle) && (to == SMeasureTimeNs))
  622. scale = (double)cycle_to_nanosec(largeValue) / (double)largeValue;
  623. else if ((from == SMeasureTimeNs) && (to == SMeasureCycle))
  624. scale = (double)nanosec_to_cycle(largeValue) / (double)largeValue;
  625. else
  626. {
  627. #ifdef _DEBUG
  628. throwUnexpected();
  629. #else
  630. scale = 1.0;
  631. #endif
  632. }
  633. return value * scale * scale;
  634. }
  635. static double convertSquareMeasure(StatisticKind from, StatisticKind to, double value)
  636. {
  637. return convertSquareMeasure(queryMeasure(from), queryMeasure(to), value);
  638. }
  639. StatisticKind querySerializedKind(StatisticKind kind)
  640. {
  641. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  642. if (rawkind >= StMax)
  643. return kind;
  644. StatisticKind serialKind = statsMetaData[rawkind].serializeKind;
  645. return (StatisticKind)(serialKind | (kind & ~StKindMask));
  646. }
  647. //--------------------------------------------------------------------------------------------------------------------
  648. void queryLongStatisticName(StringBuffer & out, StatisticKind kind)
  649. {
  650. out.append(queryStatisticName(kind));
  651. }
  652. //--------------------------------------------------------------------------------------------------------------------
  653. const char * queryTreeTag(StatisticKind kind)
  654. {
  655. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  656. unsigned variant = (kind / StVariantScale);
  657. dbgassertex(variant < (StNextModifier/StVariantScale));
  658. if (rawkind >= StKindNone && rawkind < StMax)
  659. return statsMetaData[rawkind].tags[variant];
  660. return "@Unknown";
  661. }
  662. //--------------------------------------------------------------------------------------------------------------------
  663. StatisticKind queryStatisticKind(const char * search)
  664. {
  665. if (!search)
  666. return StKindNone;
  667. if (streq(search, "*"))
  668. return StKindAll;
  669. //Slow - should use a hash table....
  670. for (unsigned variant=0; variant < StNextModifier; variant += StVariantScale)
  671. {
  672. for (unsigned i=0; i < StMax; i++)
  673. {
  674. StatisticKind kind = (StatisticKind)(i+variant);
  675. const char * shortName = queryStatisticName(kind);
  676. if (shortName && strieq(shortName, search))
  677. return kind;
  678. }
  679. }
  680. return StKindNone;
  681. }
  682. //--------------------------------------------------------------------------------------------------------------------
  683. const char * queryCreatorTypeName(StatisticCreatorType sct)
  684. {
  685. return creatorTypeNames[sct];
  686. }
  687. StatisticCreatorType queryCreatorType(const char * sct)
  688. {
  689. //MORE: Use a hash table??
  690. return (StatisticCreatorType)matchString(creatorTypeNames, sct);
  691. }
  692. //--------------------------------------------------------------------------------------------------------------------
  693. const char * queryScopeTypeName(StatisticScopeType sst)
  694. {
  695. return scopeTypeNames[sst];
  696. }
  697. extern jlib_decl StatisticScopeType queryScopeType(const char * sst)
  698. {
  699. //MORE: Use a hash table??
  700. return (StatisticScopeType)matchString(scopeTypeNames, sst);
  701. }
  702. //--------------------------------------------------------------------------------------------------------------------
  703. inline void mergeUpdate(StatisticMeasure measure, unsigned __int64 & value, const unsigned __int64 otherValue)
  704. {
  705. switch (measure)
  706. {
  707. case SMeasureTimeNs:
  708. case SMeasureCount:
  709. case SMeasureSize:
  710. case SMeasureLoad:
  711. case SMeasureSkew:
  712. case SMeasureCycle:
  713. value += otherValue;
  714. break;
  715. case SMeasureTimestampUs:
  716. if (otherValue && otherValue < value)
  717. value = otherValue;
  718. break;
  719. }
  720. }
  721. unsigned __int64 mergeStatistic(StatisticMeasure measure, unsigned __int64 value, unsigned __int64 otherValue)
  722. {
  723. mergeUpdate(measure, value, otherValue);
  724. return value;
  725. }
  726. unsigned __int64 mergeStatisticValue(unsigned __int64 prevValue, unsigned __int64 newValue, StatsMergeAction mergeAction)
  727. {
  728. switch (mergeAction)
  729. {
  730. case StatsMergeKeepNonZero:
  731. if (prevValue)
  732. return prevValue;
  733. return newValue;
  734. case StatsMergeAppend:
  735. case StatsMergeReplace:
  736. return newValue;
  737. case StatsMergeSum:
  738. return prevValue + newValue;
  739. case StatsMergeMin:
  740. if (prevValue > newValue)
  741. return newValue;
  742. else
  743. return prevValue;
  744. case StatsMergeMax:
  745. if (prevValue < newValue)
  746. return newValue;
  747. else
  748. return prevValue;
  749. default:
  750. #ifdef _DEBUG
  751. throwUnexpected();
  752. #else
  753. return newValue;
  754. #endif
  755. }
  756. }
  757. //--------------------------------------------------------------------------------------------------------------------
  758. class CComponentStatistics
  759. {
  760. protected:
  761. StringAttr creator;
  762. byte creatorDepth;
  763. byte scopeDepth;
  764. // StatisticArray stats;
  765. };
  766. //--------------------------------------------------------------------------------------------------------------------
  767. static int compareUnsigned(unsigned const * left, unsigned const * right)
  768. {
  769. return (*left < *right) ? -1 : (*left > *right) ? +1 : 0;
  770. }
  771. StatisticsMapping::StatisticsMapping(StatisticKind kind, ...)
  772. {
  773. if (kind != StKindNone)
  774. {
  775. indexToKind.append(kind);
  776. va_list args;
  777. va_start(args, kind);
  778. for (;;)
  779. {
  780. unsigned next = va_arg(args, unsigned);
  781. if (!next)
  782. break;
  783. indexToKind.appendUniq(next);
  784. }
  785. va_end(args);
  786. }
  787. createMappings();
  788. }
  789. StatisticsMapping::StatisticsMapping(const StatisticsMapping * from, ...)
  790. {
  791. ForEachItemIn(idx, from->indexToKind)
  792. indexToKind.append(from->indexToKind.item(idx));
  793. va_list args;
  794. va_start(args, from);
  795. for (;;)
  796. {
  797. unsigned next = va_arg(args, unsigned);
  798. if (!next)
  799. break;
  800. indexToKind.appendUniq(next);
  801. }
  802. va_end(args);
  803. createMappings();
  804. }
  805. StatisticsMapping::StatisticsMapping()
  806. {
  807. for (int i = StKindAll+1; i < StMax; i++)
  808. indexToKind.append(i);
  809. createMappings();
  810. }
  811. void StatisticsMapping::createMappings()
  812. {
  813. //Possibly not needed, but sort the kinds, so that it is easy to merge/stream the results out in the correct order.
  814. indexToKind.sort(compareUnsigned);
  815. //Provide mappings to all statistics to map them to the "unknown" bin by default
  816. for (unsigned i=0; i < StMax; i++)
  817. kindToIndex.append(numStatistics());
  818. ForEachItemIn(i2, indexToKind)
  819. {
  820. unsigned kind = indexToKind.item(i2);
  821. kindToIndex.replace(i2, kind);
  822. }
  823. }
  824. const StatisticsMapping allStatistics;
  825. const StatisticsMapping heapStatistics(StNumAllocations, StNumAllocationScans, StKindNone);
  826. const StatisticsMapping diskLocalStatistics(StCycleDiskReadIOCycles, StSizeDiskRead, StNumDiskReads, StCycleDiskWriteIOCycles, StSizeDiskWrite, StNumDiskWrites, StNumDiskRetries, StKindNone);
  827. const StatisticsMapping diskRemoteStatistics(StTimeDiskReadIO, StSizeDiskRead, StNumDiskReads, StTimeDiskWriteIO, StSizeDiskWrite, StNumDiskWrites, StNumDiskRetries, StKindNone);
  828. const StatisticsMapping diskReadRemoteStatistics(StTimeDiskReadIO, StSizeDiskRead, StNumDiskReads, StNumDiskRetries, StKindNone);
  829. const StatisticsMapping diskWriteRemoteStatistics(StTimeDiskWriteIO, StSizeDiskWrite, StNumDiskWrites, StNumDiskRetries, StKindNone);
  830. //--------------------------------------------------------------------------------------------------------------------
  831. class Statistic
  832. {
  833. public:
  834. Statistic(StatisticKind _kind, unsigned __int64 _value) : kind(_kind), value(_value)
  835. {
  836. }
  837. Statistic(MemoryBuffer & in, unsigned version)
  838. {
  839. unsigned _kind;
  840. in.read(_kind);
  841. kind = (StatisticKind)_kind;
  842. in.read(value);
  843. }
  844. virtual StatisticKind queryKind() const
  845. {
  846. return kind;
  847. }
  848. virtual unsigned __int64 queryValue() const
  849. {
  850. return value;
  851. }
  852. void merge(unsigned __int64 otherValue)
  853. {
  854. mergeUpdate(queryMeasure(kind), value, otherValue);
  855. }
  856. void serialize(MemoryBuffer & out) const
  857. {
  858. //MORE: Could compress - e.g., store as a packed integers
  859. out.append((unsigned)kind);
  860. out.append(value);
  861. }
  862. StringBuffer & toXML(StringBuffer &out) const
  863. {
  864. return out.append(" <Stat name=\"").append(queryStatisticName(kind)).append("\" value=\"").append(value).append("\"/>\n");
  865. }
  866. public:
  867. StatisticKind kind;
  868. unsigned __int64 value;
  869. };
  870. //--------------------------------------------------------------------------------------------------------------------
  871. StringBuffer & StatsScopeId::getScopeText(StringBuffer & out) const
  872. {
  873. switch (scopeType)
  874. {
  875. case SSTgraph:
  876. return out.append(GraphScopePrefix).append(id);
  877. case SSTsubgraph:
  878. return out.append(SubGraphScopePrefix).append(id);
  879. case SSTactivity:
  880. return out.append(ActivityScopePrefix).append(id);
  881. case SSTedge:
  882. return out.append(EdgeScopePrefix).append(id).append("_").append(extra);
  883. case SSTfunction:
  884. return out.append(FunctionScopePrefix).append(name);
  885. default:
  886. #ifdef _DEBUG
  887. throwUnexpected();
  888. #endif
  889. return out.append("????").append(id);
  890. }
  891. }
  892. unsigned StatsScopeId::getHash() const
  893. {
  894. switch (scopeType)
  895. {
  896. case SSTfunction:
  897. return hashc((const byte *)name.get(), strlen(name), (unsigned)scopeType);
  898. default:
  899. return hashc((const byte *)&id, sizeof(id), (unsigned)scopeType);
  900. }
  901. }
  902. bool StatsScopeId::matches(const StatsScopeId & other) const
  903. {
  904. return (scopeType == other.scopeType) && (id == other.id) && (extra == other.extra) && strsame(name, other.name);
  905. }
  906. unsigned StatsScopeId::queryActivity() const
  907. {
  908. switch (scopeType)
  909. {
  910. case SSTactivity:
  911. case SSTedge:
  912. return id;
  913. default:
  914. return 0;
  915. }
  916. }
  917. void StatsScopeId::deserialize(MemoryBuffer & in, unsigned version)
  918. {
  919. byte scopeTypeByte;
  920. in.read(scopeTypeByte);
  921. scopeType = (StatisticScopeType)scopeTypeByte;
  922. switch (scopeType)
  923. {
  924. case SSTgraph:
  925. case SSTsubgraph:
  926. case SSTactivity:
  927. in.read(id);
  928. break;
  929. case SSTedge:
  930. in.read(id);
  931. in.read(extra);
  932. break;
  933. case SSTfunction:
  934. in.read(name);
  935. break;
  936. default:
  937. throwUnexpected();
  938. break;
  939. }
  940. }
  941. void StatsScopeId::serialize(MemoryBuffer & out) const
  942. {
  943. out.append((byte)scopeType);
  944. switch (scopeType)
  945. {
  946. case SSTgraph:
  947. case SSTsubgraph:
  948. case SSTactivity:
  949. out.append(id);
  950. break;
  951. case SSTedge:
  952. out.append(id);
  953. out.append(extra);
  954. break;
  955. case SSTfunction:
  956. out.append(name);
  957. break;
  958. default:
  959. throwUnexpected();
  960. break;
  961. }
  962. }
  963. void StatsScopeId::setId(StatisticScopeType _scopeType, unsigned _id, unsigned _extra)
  964. {
  965. scopeType = _scopeType;
  966. id = _id;
  967. extra = _extra;
  968. }
  969. bool StatsScopeId::setScopeText(const char * text)
  970. {
  971. if (MATCHES_CONST_PREFIX(text, ActivityScopePrefix))
  972. setActivityId(atoi(text + CONST_STRLEN(ActivityScopePrefix)));
  973. else if (MATCHES_CONST_PREFIX(text, GraphScopePrefix))
  974. setId(SSTgraph, atoi(text + CONST_STRLEN(GraphScopePrefix)));
  975. else if (MATCHES_CONST_PREFIX(text, SubGraphScopePrefix))
  976. setSubgraphId(atoi(text + CONST_STRLEN(SubGraphScopePrefix)));
  977. else if (MATCHES_CONST_PREFIX(text, EdgeScopePrefix))
  978. {
  979. const char * underscore = strchr(text, '_');
  980. if (!underscore)
  981. return false;
  982. setEdgeId(atoi(text + CONST_STRLEN(EdgeScopePrefix)), atoi(underscore+1));
  983. }
  984. else if (MATCHES_CONST_PREFIX(text, FunctionScopePrefix))
  985. setFunctionId(text+CONST_STRLEN(FunctionScopePrefix));
  986. else
  987. return false;
  988. return true;
  989. }
  990. void StatsScopeId::setActivityId(unsigned _id)
  991. {
  992. setId(SSTactivity, _id);
  993. }
  994. void StatsScopeId::setEdgeId(unsigned _id, unsigned _output)
  995. {
  996. setId(SSTedge, _id, _output);
  997. }
  998. void StatsScopeId::setSubgraphId(unsigned _id)
  999. {
  1000. setId(SSTsubgraph, _id);
  1001. }
  1002. void StatsScopeId::setFunctionId(const char * _name)
  1003. {
  1004. scopeType = SSTfunction;
  1005. name.set(_name);
  1006. }
  1007. //--------------------------------------------------------------------------------------------------------------------
  1008. enum
  1009. {
  1010. SCroot,
  1011. SCintermediate,
  1012. SCleaf,
  1013. };
  1014. class CStatisticCollection;
  1015. static CStatisticCollection * deserializeCollection(CStatisticCollection * parent, MemoryBuffer & in, unsigned version);
  1016. //MORE: Create an implementation with no children
  1017. typedef StructArrayOf<Statistic> StatsArray;
  1018. class CollectionHashTable : public SuperHashTableOf<CStatisticCollection, StatsScopeId>
  1019. {
  1020. public:
  1021. ~CollectionHashTable() { _releaseAll(); }
  1022. virtual void onAdd(void *et);
  1023. virtual void onRemove(void *et);
  1024. virtual unsigned getHashFromElement(const void *et) const;
  1025. virtual unsigned getHashFromFindParam(const void *fp) const;
  1026. virtual const void * getFindParam(const void *et) const;
  1027. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const;
  1028. virtual bool matchesElement(const void *et, const void *searchET) const;
  1029. };
  1030. typedef IArrayOf<CStatisticCollection> CollectionArray;
  1031. class CStatisticCollection : public CInterfaceOf<IStatisticCollection>
  1032. {
  1033. friend class CollectionHashTable;
  1034. public:
  1035. CStatisticCollection(CStatisticCollection * _parent, const StatsScopeId & _id) : id(_id), parent(_parent)
  1036. {
  1037. }
  1038. CStatisticCollection(CStatisticCollection * _parent, MemoryBuffer & in, unsigned version) : parent(_parent)
  1039. {
  1040. id.deserialize(in, version);
  1041. unsigned numStats;
  1042. in.read(numStats);
  1043. stats.ensure(numStats);
  1044. while (numStats-- > 0)
  1045. {
  1046. Statistic next (in, version);
  1047. stats.append(next);
  1048. }
  1049. unsigned numChildren;
  1050. in.read(numChildren);
  1051. children.ensure(numChildren);
  1052. while (numChildren-- > 0)
  1053. {
  1054. CStatisticCollection * next = deserializeCollection(this, in, version);
  1055. children.add(*next);
  1056. }
  1057. }
  1058. virtual byte getCollectionType() const { return SCintermediate; }
  1059. StringBuffer &toXML(StringBuffer &out) const;
  1060. //interface IStatisticCollection:
  1061. virtual StatisticScopeType queryScopeType() const
  1062. {
  1063. return id.queryScopeType();
  1064. }
  1065. virtual unsigned __int64 queryWhenCreated() const
  1066. {
  1067. if (parent)
  1068. return parent->queryWhenCreated();
  1069. return 0;
  1070. }
  1071. virtual StringBuffer & getScope(StringBuffer & str) const
  1072. {
  1073. return id.getScopeText(str);
  1074. }
  1075. virtual StringBuffer & getFullScope(StringBuffer & str) const
  1076. {
  1077. if (parent)
  1078. {
  1079. parent->getFullScope(str);
  1080. str.append(':');
  1081. }
  1082. id.getScopeText(str);
  1083. return str;
  1084. }
  1085. virtual unsigned __int64 queryStatistic(StatisticKind kind) const
  1086. {
  1087. ForEachItemIn(i, stats)
  1088. {
  1089. const Statistic & cur = stats.item(i);
  1090. if (cur.kind == kind)
  1091. return cur.value;
  1092. }
  1093. return 0;
  1094. }
  1095. virtual unsigned getNumStatistics() const
  1096. {
  1097. return stats.ordinality();
  1098. }
  1099. virtual void getStatistic(StatisticKind & kind, unsigned __int64 & value, unsigned idx) const
  1100. {
  1101. const Statistic & cur = stats.item(idx);
  1102. kind = cur.kind;
  1103. value = cur.value;
  1104. }
  1105. virtual IStatisticCollectionIterator & getScopes(const char * filter)
  1106. {
  1107. assertex(!filter);
  1108. return * new SuperHashIIteratorOf<IStatisticCollection, IStatisticCollectionIterator, false>(children);
  1109. }
  1110. virtual void getMinMaxScope(IStringVal & minValue, IStringVal & maxValue, StatisticScopeType searchScopeType) const
  1111. {
  1112. if (id.queryScopeType() == searchScopeType)
  1113. {
  1114. const char * curMin = minValue.str();
  1115. const char * curMax = maxValue.str();
  1116. StringBuffer name;
  1117. id.getScopeText(name);
  1118. if (!curMin || !*curMin || strcmp(name.str(), curMin) < 0)
  1119. minValue.set(name.str());
  1120. if (!curMax || strcmp(name.str(), curMax) > 0)
  1121. maxValue.set(name.str());
  1122. }
  1123. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1124. for (iter.first(); iter.isValid(); iter.next())
  1125. iter.query().getMinMaxScope(minValue, maxValue, searchScopeType);
  1126. }
  1127. virtual void getMinMaxActivity(unsigned & minValue, unsigned & maxValue) const
  1128. {
  1129. unsigned activityId = id.queryActivity();
  1130. if (activityId)
  1131. {
  1132. if ((minValue == 0) || (activityId < minValue))
  1133. minValue = activityId;
  1134. if (activityId > maxValue)
  1135. maxValue = activityId;
  1136. }
  1137. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1138. for (iter.first(); iter.isValid(); iter.next())
  1139. iter.query().getMinMaxActivity(minValue, maxValue);
  1140. }
  1141. //other public interface functions
  1142. void addStatistic(StatisticKind kind, unsigned __int64 value)
  1143. {
  1144. Statistic s(kind, value);
  1145. stats.append(s);
  1146. }
  1147. void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  1148. {
  1149. if (mergeAction != StatsMergeAppend)
  1150. {
  1151. ForEachItemIn(i, stats)
  1152. {
  1153. Statistic & cur = stats.element(i);
  1154. if (cur.kind == kind)
  1155. {
  1156. cur.value = mergeStatisticValue(cur.value, value, mergeAction);
  1157. return;
  1158. }
  1159. }
  1160. }
  1161. Statistic s(kind, value);
  1162. stats.append(s);
  1163. }
  1164. CStatisticCollection * ensureSubScope(const StatsScopeId & search, bool hasChildren)
  1165. {
  1166. //MORE: Implement hasChildren
  1167. return resolveSubScope(search, true, false);
  1168. }
  1169. CStatisticCollection * resolveSubScope(const StatsScopeId & search, bool create, bool replace)
  1170. {
  1171. if (!replace)
  1172. {
  1173. CStatisticCollection * match = children.find(&search);
  1174. if (match)
  1175. return LINK(match);
  1176. }
  1177. if (create)
  1178. {
  1179. CStatisticCollection * ret = new CStatisticCollection(this, search);
  1180. children.add(*ret);
  1181. return LINK(ret);
  1182. }
  1183. return NULL;
  1184. }
  1185. virtual void serialize(MemoryBuffer & out) const
  1186. {
  1187. out.append(getCollectionType());
  1188. id.serialize(out);
  1189. out.append(stats.ordinality());
  1190. ForEachItemIn(iStat, stats)
  1191. stats.item(iStat).serialize(out);
  1192. out.append(children.ordinality());
  1193. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1194. for (iter.first(); iter.isValid(); iter.next())
  1195. iter.query().serialize(out);
  1196. }
  1197. private:
  1198. StatsScopeId id;
  1199. CStatisticCollection * parent;
  1200. CollectionHashTable children;
  1201. StatsArray stats;
  1202. };
  1203. StringBuffer &CStatisticCollection::toXML(StringBuffer &out) const
  1204. {
  1205. out.append("<Scope id=\"");
  1206. id.getScopeText(out).append("\">\n");
  1207. if (stats.ordinality())
  1208. {
  1209. out.append(" <Stats>");
  1210. ForEachItemIn(i, stats)
  1211. stats.item(i).toXML(out);
  1212. out.append(" </Stats>\n");
  1213. }
  1214. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1215. for (iter.first(); iter.isValid(); iter.next())
  1216. iter.query().toXML(out);
  1217. out.append("</Scope>\n");
  1218. return out;
  1219. }
  1220. //---------------------------------------------------------------------------------------------------------------------
  1221. void CollectionHashTable::onAdd(void *et)
  1222. {
  1223. }
  1224. void CollectionHashTable::onRemove(void *et)
  1225. {
  1226. CStatisticCollection * elem = reinterpret_cast<CStatisticCollection *>(et);
  1227. elem->Release();
  1228. }
  1229. unsigned CollectionHashTable::getHashFromElement(const void *et) const
  1230. {
  1231. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1232. return elem->id.getHash();
  1233. }
  1234. unsigned CollectionHashTable::getHashFromFindParam(const void *fp) const
  1235. {
  1236. const StatsScopeId * search = reinterpret_cast<const StatsScopeId *>(fp);
  1237. return search->getHash();
  1238. }
  1239. const void * CollectionHashTable::getFindParam(const void *et) const
  1240. {
  1241. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1242. return &elem->id;
  1243. }
  1244. bool CollectionHashTable::matchesFindParam(const void *et, const void *key, unsigned fphash) const
  1245. {
  1246. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1247. const StatsScopeId * search = reinterpret_cast<const StatsScopeId *>(key);
  1248. return elem->id.matches(*search);
  1249. }
  1250. bool CollectionHashTable::matchesElement(const void *et, const void *searchET) const
  1251. {
  1252. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1253. const CStatisticCollection * searchElem = reinterpret_cast<const CStatisticCollection *>(searchET);
  1254. return elem->id.matches(searchElem->id);
  1255. }
  1256. //---------------------------------------------------------------------------------------------------------------------
  1257. class CRootStatisticCollection : public CStatisticCollection
  1258. {
  1259. public:
  1260. CRootStatisticCollection(StatisticCreatorType _creatorType, const char * _creator, const StatsScopeId & _id)
  1261. : CStatisticCollection(NULL, _id), creatorType(_creatorType), creator(_creator)
  1262. {
  1263. whenCreated = getTimeStampNowValue();
  1264. }
  1265. CRootStatisticCollection(MemoryBuffer & in, unsigned version) : CStatisticCollection(NULL, in, version)
  1266. {
  1267. byte creatorTypeByte;
  1268. in.read(creatorTypeByte);
  1269. creatorType = (StatisticCreatorType)creatorTypeByte;
  1270. in.read(creator);
  1271. in.read(whenCreated);
  1272. }
  1273. virtual byte getCollectionType() const { return SCroot; }
  1274. virtual unsigned __int64 queryWhenCreated() const
  1275. {
  1276. return whenCreated;
  1277. }
  1278. virtual void serialize(MemoryBuffer & out) const
  1279. {
  1280. CStatisticCollection::serialize(out);
  1281. out.append((byte)creatorType);
  1282. out.append(creator);
  1283. out.append(whenCreated);
  1284. }
  1285. public:
  1286. StatisticCreatorType creatorType;
  1287. StringAttr creator;
  1288. unsigned __int64 whenCreated;
  1289. };
  1290. //---------------------------------------------------------------------------------------------------------------------
  1291. void serializeStatisticCollection(MemoryBuffer & out, IStatisticCollection * collection)
  1292. {
  1293. out.append(currentStatisticsVersion);
  1294. collection->serialize(out);
  1295. }
  1296. static CStatisticCollection * deserializeCollection(CStatisticCollection * parent, MemoryBuffer & in, unsigned version)
  1297. {
  1298. byte kind;
  1299. in.read(kind);
  1300. switch (kind)
  1301. {
  1302. case SCroot:
  1303. assertex(!parent);
  1304. return new CRootStatisticCollection(in, version);
  1305. case SCintermediate:
  1306. return new CStatisticCollection(parent, in, version);
  1307. default:
  1308. UNIMPLEMENTED;
  1309. }
  1310. }
  1311. IStatisticCollection * createStatisticCollection(MemoryBuffer & in)
  1312. {
  1313. unsigned version;
  1314. in.read(version);
  1315. return deserializeCollection(NULL, in, version);
  1316. }
  1317. //--------------------------------------------------------------------------------------------------------------------
  1318. class StatisticGatherer : implements CInterfaceOf<IStatisticGatherer>
  1319. {
  1320. public:
  1321. StatisticGatherer(CStatisticCollection * scope) : rootScope(scope)
  1322. {
  1323. scopes.append(*scope);
  1324. }
  1325. virtual void beginScope(const StatsScopeId & id)
  1326. {
  1327. CStatisticCollection & tos = scopes.tos();
  1328. scopes.append(*tos.ensureSubScope(id, true));
  1329. }
  1330. virtual void beginActivityScope(unsigned id)
  1331. {
  1332. StatsScopeId scopeId(SSTactivity, id);
  1333. CStatisticCollection & tos = scopes.tos();
  1334. scopes.append(*tos.ensureSubScope(scopeId, false));
  1335. }
  1336. virtual void beginSubGraphScope(unsigned id)
  1337. {
  1338. StatsScopeId scopeId(SSTsubgraph, id);
  1339. CStatisticCollection & tos = scopes.tos();
  1340. scopes.append(*tos.ensureSubScope(scopeId, true));
  1341. }
  1342. virtual void beginEdgeScope(unsigned id, unsigned oid)
  1343. {
  1344. StatsScopeId scopeId(SSTedge, id, oid);
  1345. CStatisticCollection & tos = scopes.tos();
  1346. scopes.append(*tos.ensureSubScope(scopeId, false));
  1347. }
  1348. virtual void endScope()
  1349. {
  1350. scopes.tos().Release();
  1351. scopes.pop();
  1352. }
  1353. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  1354. {
  1355. CStatisticCollection & tos = scopes.tos();
  1356. tos.addStatistic(kind, value);
  1357. }
  1358. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  1359. {
  1360. CStatisticCollection & tos = scopes.tos();
  1361. tos.updateStatistic(kind, value, mergeAction);
  1362. }
  1363. virtual IStatisticCollection * getResult()
  1364. {
  1365. return LINK(rootScope);
  1366. }
  1367. protected:
  1368. ICopyArrayOf<CStatisticCollection> scopes;
  1369. Linked<CStatisticCollection> rootScope;
  1370. };
  1371. extern IStatisticGatherer * createStatisticsGatherer(StatisticCreatorType creatorType, const char * creator, const StatsScopeId & rootScope)
  1372. {
  1373. //creator unused at the moment.
  1374. Owned<CStatisticCollection> rootCollection = new CRootStatisticCollection(creatorType, creator, rootScope);
  1375. return new StatisticGatherer(rootCollection);
  1376. }
  1377. //--------------------------------------------------------------------------------------------------------------------
  1378. extern IPropertyTree * selectTreeStat(IPropertyTree *node, const char *statName, const char *statType)
  1379. {
  1380. StringBuffer xpath;
  1381. xpath.appendf("att[@name='%s']", statName);
  1382. IPropertyTree *att = node->queryPropTree(xpath.str());
  1383. if (!att)
  1384. {
  1385. att = node->addPropTree("att", createPTree());
  1386. att->setProp("@name", statName);
  1387. att->setProp("@type", statType);
  1388. }
  1389. return att;
  1390. }
  1391. extern void putStatsTreeValue(IPropertyTree *node, const char *statName, const char *statType, unsigned __int64 val)
  1392. {
  1393. if (val)
  1394. selectTreeStat(node, statName, statType)->setPropInt64("@value", val);
  1395. }
  1396. class TreeNodeStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  1397. {
  1398. public:
  1399. TreeNodeStatisticGatherer(IPropertyTree & root) : node(&root) {}
  1400. virtual void beginScope(const StatsScopeId & id)
  1401. {
  1402. StringBuffer temp;
  1403. id.getScopeText(temp);
  1404. beginScope(temp.str());
  1405. }
  1406. virtual void beginSubGraphScope(unsigned id) { throwUnexpected(); }
  1407. virtual void beginActivityScope(unsigned id) { throwUnexpected(); }
  1408. virtual void beginEdgeScope(unsigned id, unsigned oid) { throwUnexpected(); }
  1409. virtual void endScope()
  1410. {
  1411. node = &stack.popGet();
  1412. }
  1413. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  1414. {
  1415. putStatsTreeValue(node, queryStatisticName(kind), "sum", value);
  1416. }
  1417. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  1418. {
  1419. if (value)
  1420. {
  1421. IPropertyTree * stat = selectTreeStat(node, queryStatisticName(kind), "sum");
  1422. unsigned __int64 newValue = mergeStatisticValue(stat->getPropInt64("@value"), value, mergeAction);
  1423. stat->setPropInt64("@value", newValue);
  1424. }
  1425. }
  1426. virtual IStatisticCollection * getResult() { throwUnexpected(); }
  1427. protected:
  1428. void beginScope(const char * id)
  1429. {
  1430. stack.append(*node);
  1431. StringBuffer xpath;
  1432. xpath.appendf("scope[@name='%s']", id);
  1433. IPropertyTree *att = node->queryPropTree(xpath.str());
  1434. if (!att)
  1435. {
  1436. att = node->addPropTree("scope", createPTree());
  1437. att->setProp("@name", id);
  1438. }
  1439. node = att;
  1440. }
  1441. protected:
  1442. IPropertyTree * node;
  1443. ICopyArrayOf<IPropertyTree> stack;
  1444. };
  1445. //--------------------------------------------------------------------------------------------------------------------
  1446. void CRuntimeStatistic::merge(unsigned __int64 otherValue, StatsMergeAction mergeAction)
  1447. {
  1448. value = mergeStatisticValue(value, otherValue, mergeAction);
  1449. }
  1450. //--------------------------------------------------------------------------------------------------------------------
  1451. CRuntimeStatisticCollection::~CRuntimeStatisticCollection()
  1452. {
  1453. delete [] values;
  1454. delete nested;
  1455. }
  1456. CNestedRuntimeStatisticMap & CRuntimeStatisticCollection::ensureNested()
  1457. {
  1458. if (!nested)
  1459. nested = new CNestedRuntimeStatisticMap;
  1460. return *nested;
  1461. }
  1462. void CRuntimeStatisticCollection::merge(const CRuntimeStatisticCollection & other)
  1463. {
  1464. ForEachItemIn(i, other)
  1465. {
  1466. StatisticKind kind = other.getKind(i);
  1467. unsigned __int64 value = other.getStatisticValue(kind);
  1468. if (value)
  1469. mergeStatistic(kind, value);
  1470. }
  1471. if (other.nested)
  1472. {
  1473. ensureNested().merge(*other.nested);
  1474. }
  1475. }
  1476. void CRuntimeStatisticCollection::updateDelta(CRuntimeStatisticCollection & target, const CRuntimeStatisticCollection & source)
  1477. {
  1478. ForEachItemIn(i, source)
  1479. {
  1480. StatisticKind kind = source.getKind(i);
  1481. unsigned __int64 sourceValue = source.getStatisticValue(kind);
  1482. if (queryMergeMode(kind) == StatsMergeSum)
  1483. {
  1484. unsigned __int64 prevValue = getStatisticValue(kind);
  1485. if (sourceValue != prevValue)
  1486. {
  1487. target.mergeStatistic(kind, sourceValue - prevValue);
  1488. setStatistic(kind, sourceValue);
  1489. }
  1490. }
  1491. else
  1492. {
  1493. if (sourceValue)
  1494. target.mergeStatistic(kind, sourceValue);
  1495. }
  1496. }
  1497. if (source.nested)
  1498. {
  1499. ensureNested().updateDelta(target.ensureNested(), *source.nested);
  1500. }
  1501. }
  1502. void CRuntimeStatisticCollection::mergeStatistic(StatisticKind kind, unsigned __int64 value)
  1503. {
  1504. queryStatistic(kind).merge(value, queryMergeMode(kind));
  1505. }
  1506. void CRuntimeStatisticCollection::reset()
  1507. {
  1508. unsigned num = mapping.numStatistics();
  1509. for (unsigned i = 0; i <= num; i++)
  1510. values[i].clear();
  1511. }
  1512. void CRuntimeStatisticCollection::reset(const StatisticsMapping & toClear)
  1513. {
  1514. unsigned num = toClear.numStatistics();
  1515. for (unsigned i = 0; i < num; i++)
  1516. queryStatistic(toClear.getKind(i)).clear();
  1517. }
  1518. CRuntimeStatisticCollection & CRuntimeStatisticCollection::registerNested(const StatsScopeId & scope, const StatisticsMapping & mapping)
  1519. {
  1520. return ensureNested().addNested(scope, mapping).queryStats();
  1521. }
  1522. void CRuntimeStatisticCollection::rollupStatistics(unsigned numTargets, IContextLogger * const * targets) const
  1523. {
  1524. ForEachItem(iStat)
  1525. {
  1526. unsigned __int64 value = values[iStat].getClear();
  1527. if (value)
  1528. {
  1529. StatisticKind kind = getKind(iStat);
  1530. for (unsigned iTarget = 0; iTarget < numTargets; iTarget++)
  1531. targets[iTarget]->noteStatistic(kind, value);
  1532. }
  1533. }
  1534. reportIgnoredStats();
  1535. }
  1536. void CRuntimeStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  1537. {
  1538. ForEachItem(i)
  1539. {
  1540. unsigned __int64 value = values[i].get();
  1541. if (value)
  1542. {
  1543. StatisticKind kind = getKind(i);
  1544. StatisticKind serialKind= querySerializedKind(kind);
  1545. if (kind != serialKind)
  1546. value = convertMeasure(kind, serialKind, value);
  1547. StatsMergeAction mergeAction = queryMergeMode(serialKind);
  1548. target.updateStatistic(serialKind, value, mergeAction);
  1549. }
  1550. }
  1551. reportIgnoredStats();
  1552. if (nested)
  1553. nested->recordStatistics(target);
  1554. }
  1555. void CRuntimeStatisticCollection::reportIgnoredStats() const
  1556. {
  1557. if (values[mapping.numStatistics()].getClear())
  1558. DBGLOG("Some statistics were added but thrown away");
  1559. }
  1560. StringBuffer & CRuntimeStatisticCollection::toXML(StringBuffer &str) const
  1561. {
  1562. ForEachItem(iStat)
  1563. {
  1564. unsigned __int64 value = values[iStat].get();
  1565. if (value)
  1566. {
  1567. StatisticKind kind = getKind(iStat);
  1568. const char * name = queryStatisticName(kind);
  1569. str.appendf("<%s>%" I64F "d</%s>", name, value, name);
  1570. }
  1571. }
  1572. if (nested)
  1573. nested->toXML(str);
  1574. return str;
  1575. }
  1576. StringBuffer & CRuntimeStatisticCollection::toStr(StringBuffer &str) const
  1577. {
  1578. ForEachItem(iStat)
  1579. {
  1580. unsigned __int64 value = values[iStat].get();
  1581. if (value)
  1582. {
  1583. StatisticKind kind = getKind(iStat);
  1584. const char * name = queryStatisticName(kind);
  1585. str.append(' ').append(name).append("=");
  1586. formatStatistic(str, value, kind);
  1587. }
  1588. }
  1589. if (nested)
  1590. nested->toStr(str);
  1591. return str;
  1592. }
  1593. void CRuntimeStatisticCollection::deserialize(MemoryBuffer& in)
  1594. {
  1595. unsigned numValid;
  1596. in.readPacked(numValid);
  1597. for (unsigned i=0; i < numValid; i++)
  1598. {
  1599. unsigned kindVal;
  1600. unsigned __int64 value;
  1601. in.readPacked(kindVal).readPacked(value);
  1602. StatisticKind kind = (StatisticKind)kindVal;
  1603. setStatistic(kind, value);
  1604. }
  1605. bool hasNested;
  1606. in.read(hasNested);
  1607. if (hasNested)
  1608. {
  1609. ensureNested().deserializeMerge(in);
  1610. }
  1611. }
  1612. void CRuntimeStatisticCollection::deserializeMerge(MemoryBuffer& in)
  1613. {
  1614. unsigned numValid;
  1615. in.readPacked(numValid);
  1616. for (unsigned i=0; i < numValid; i++)
  1617. {
  1618. unsigned kindVal;
  1619. unsigned __int64 value;
  1620. in.readPacked(kindVal).readPacked(value);
  1621. StatisticKind kind = (StatisticKind)kindVal;
  1622. StatsMergeAction mergeAction = queryMergeMode(kind);
  1623. mergeStatistic(kind, value, mergeAction);
  1624. }
  1625. bool hasNested;
  1626. in.read(hasNested);
  1627. if (hasNested)
  1628. {
  1629. ensureNested().deserializeMerge(in);
  1630. }
  1631. }
  1632. void CRuntimeStatisticCollection::getNodeProgressInfo(IPropertyTree &node) const
  1633. {
  1634. TreeNodeStatisticGatherer gatherer(node);
  1635. recordStatistics(gatherer);
  1636. }
  1637. bool CRuntimeStatisticCollection::serialize(MemoryBuffer& out) const
  1638. {
  1639. unsigned numValid = 0;
  1640. ForEachItem(i1)
  1641. {
  1642. if (values[i1].get())
  1643. numValid++;
  1644. }
  1645. out.appendPacked(numValid);
  1646. ForEachItem(i2)
  1647. {
  1648. unsigned __int64 value = values[i2].get();
  1649. if (value)
  1650. {
  1651. StatisticKind kind = mapping.getKind(i2);
  1652. StatisticKind serialKind= querySerializedKind(kind);
  1653. if (kind != serialKind)
  1654. value = convertMeasure(kind, serialKind, value);
  1655. out.appendPacked((unsigned)serialKind);
  1656. out.appendPacked(value);
  1657. }
  1658. }
  1659. bool nonEmpty = (numValid != 0);
  1660. out.append(nested != nullptr);
  1661. if (nested)
  1662. {
  1663. if (nested->serialize(out))
  1664. nonEmpty = true;
  1665. }
  1666. return nonEmpty;
  1667. }
  1668. //---------------------------------------------------------------------------------------------------------------------
  1669. void CRuntimeSummaryStatisticCollection::DerivedStats::mergeStatistic(unsigned __int64 value, unsigned node)
  1670. {
  1671. if (count == 0)
  1672. {
  1673. min = value;
  1674. max = value;
  1675. minNode = node;
  1676. maxNode = node;
  1677. }
  1678. else
  1679. {
  1680. if (value < min)
  1681. {
  1682. min = value;
  1683. minNode = node;
  1684. }
  1685. if (value > max)
  1686. {
  1687. max = value;
  1688. maxNode = node;
  1689. }
  1690. }
  1691. count++;
  1692. double dvalue = (double)value;
  1693. sumSquares += dvalue * dvalue;
  1694. }
  1695. CRuntimeSummaryStatisticCollection::CRuntimeSummaryStatisticCollection(const StatisticsMapping & _mapping) : CRuntimeStatisticCollection(_mapping)
  1696. {
  1697. derived = new DerivedStats[ordinality()+1];
  1698. }
  1699. CRuntimeSummaryStatisticCollection::~CRuntimeSummaryStatisticCollection()
  1700. {
  1701. delete[] derived;
  1702. }
  1703. CNestedRuntimeStatisticMap & CRuntimeSummaryStatisticCollection::ensureNested()
  1704. {
  1705. if (!nested)
  1706. nested = new CNestedSummaryRuntimeStatisticMap;
  1707. return *nested;
  1708. }
  1709. void CRuntimeSummaryStatisticCollection::mergeStatistic(StatisticKind kind, unsigned __int64 value)
  1710. {
  1711. CRuntimeStatisticCollection::mergeStatistic(kind, value);
  1712. unsigned index = queryMapping().getIndex(kind);
  1713. derived[index].mergeStatistic(value, 0);
  1714. }
  1715. static bool isSignificantSkew(StatisticKind kind, unsigned __int64 range, unsigned __int64 count)
  1716. {
  1717. //MORE: Could get more sophisticated!
  1718. return range > 1;
  1719. }
  1720. void CRuntimeSummaryStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  1721. {
  1722. CRuntimeStatisticCollection::recordStatistics(target);
  1723. for (unsigned i = 0; i < ordinality(); i++)
  1724. {
  1725. DerivedStats & cur = derived[i];
  1726. if (cur.count)
  1727. {
  1728. StatisticKind kind = getKind(i);
  1729. StatisticKind serialKind= querySerializedKind(kind);
  1730. unsigned __int64 minValue = convertMeasure(kind, serialKind, cur.min);
  1731. unsigned __int64 maxValue = convertMeasure(kind, serialKind, cur.max);
  1732. if (minValue != maxValue)
  1733. {
  1734. double sum = (double)convertMeasure(kind, serialKind, values[i].get());
  1735. //Sum of squares needs to be translated twice
  1736. double sumSquares = convertSquareMeasure(kind, serialKind, cur.sumSquares);
  1737. double mean = (double)(sum / cur.count);
  1738. double variance = (sumSquares - sum * mean) / cur.count;
  1739. double stdDev = sqrt(variance);
  1740. double maxSkew = (10000.0 * ((maxValue-mean)/mean));
  1741. double minSkew = (10000.0 * ((mean-minValue)/mean));
  1742. unsigned __int64 range = maxValue - minValue;
  1743. target.addStatistic((StatisticKind)(serialKind|StMinX), minValue);
  1744. target.addStatistic((StatisticKind)(serialKind|StMaxX), maxValue);
  1745. target.addStatistic((StatisticKind)(serialKind|StAvgX), (unsigned __int64)mean);
  1746. target.addStatistic((StatisticKind)(serialKind|StDeltaX), range);
  1747. target.addStatistic((StatisticKind)(serialKind|StStdDevX), (unsigned __int64)stdDev);
  1748. //If all nodes are the same then we re actually merging results from multiple runs
  1749. //if the range is less than the count then
  1750. if ((cur.minNode != cur.maxNode) && isSignificantSkew(serialKind, range, cur.count))
  1751. {
  1752. target.addStatistic((StatisticKind)(serialKind|StSkewMin), (unsigned __int64)minSkew);
  1753. target.addStatistic((StatisticKind)(serialKind|StSkewMax), (unsigned __int64)maxSkew);
  1754. target.addStatistic((StatisticKind)(serialKind|StNodeMin), cur.minNode);
  1755. target.addStatistic((StatisticKind)(serialKind|StNodeMax), cur.maxNode);
  1756. }
  1757. }
  1758. else if (cur.count != 1)
  1759. target.addStatistic((StatisticKind)(serialKind|StAvgX), minValue);
  1760. }
  1761. }
  1762. }
  1763. bool CRuntimeSummaryStatisticCollection::serialize(MemoryBuffer & out) const
  1764. {
  1765. UNIMPLEMENTED; // NB: Need to convert sum squares twice.
  1766. }
  1767. void CRuntimeSummaryStatisticCollection::deserialize(MemoryBuffer & in)
  1768. {
  1769. UNIMPLEMENTED;
  1770. }
  1771. void CRuntimeSummaryStatisticCollection::deserializeMerge(MemoryBuffer& in)
  1772. {
  1773. UNIMPLEMENTED;
  1774. }
  1775. //---------------------------------------------------
  1776. bool CNestedRuntimeStatisticCollection::matches(const StatsScopeId & otherScope) const
  1777. {
  1778. return scope.matches(otherScope);
  1779. }
  1780. //NOTE: When deserializing, the scope is deserialized by the caller, and the correct target selected
  1781. //which is why there is no corresponding deserialize() ofthe scope at this point
  1782. void CNestedRuntimeStatisticCollection::deserialize(MemoryBuffer & in)
  1783. {
  1784. stats->deserialize(in);
  1785. }
  1786. void CNestedRuntimeStatisticCollection::deserializeMerge(MemoryBuffer& in)
  1787. {
  1788. stats->deserialize(in);
  1789. }
  1790. void CNestedRuntimeStatisticCollection::merge(const CNestedRuntimeStatisticCollection & other)
  1791. {
  1792. stats->merge(other.queryStats());
  1793. }
  1794. bool CNestedRuntimeStatisticCollection::serialize(MemoryBuffer& out) const
  1795. {
  1796. scope.serialize(out);
  1797. return stats->serialize(out);
  1798. }
  1799. void CNestedRuntimeStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  1800. {
  1801. target.beginScope(scope);
  1802. stats->recordStatistics(target);
  1803. target.endScope();
  1804. }
  1805. StringBuffer & CNestedRuntimeStatisticCollection::toStr(StringBuffer &str) const
  1806. {
  1807. str.append(' ');
  1808. scope.getScopeText(str).append("={");
  1809. stats->toStr(str);
  1810. return str.append(" }");
  1811. }
  1812. StringBuffer & CNestedRuntimeStatisticCollection::toXML(StringBuffer &str) const
  1813. {
  1814. str.append("<Scope id=\"");
  1815. scope.getScopeText(str).append("\">");
  1816. stats->toXML(str);
  1817. return str.append("</Scope>");
  1818. }
  1819. void CNestedRuntimeStatisticCollection::updateDelta(CNestedRuntimeStatisticCollection & target, const CNestedRuntimeStatisticCollection & source)
  1820. {
  1821. stats->updateDelta(*target.stats, *source.stats);
  1822. }
  1823. //---------------------------------------------------
  1824. CNestedRuntimeStatisticCollection & CNestedRuntimeStatisticMap::addNested(const StatsScopeId & scope, const StatisticsMapping & mapping)
  1825. {
  1826. ForEachItemIn(i, map)
  1827. {
  1828. CNestedRuntimeStatisticCollection & cur = map.item(i);
  1829. if (cur.matches(scope))
  1830. return cur;
  1831. }
  1832. CNestedRuntimeStatisticCollection * stats = new CNestedRuntimeStatisticCollection(scope, createStats(mapping));
  1833. map.append(*stats);
  1834. return *stats;
  1835. }
  1836. void CNestedRuntimeStatisticMap::deserialize(MemoryBuffer& in)
  1837. {
  1838. unsigned numItems;
  1839. in.readPacked(numItems);
  1840. for (unsigned i=0; i < numItems; i++)
  1841. {
  1842. StatsScopeId scope;
  1843. scope.deserialize(in, currentStatisticsVersion);
  1844. //Use allStatistics as the default mapping if it hasn't already been added.
  1845. CNestedRuntimeStatisticCollection & child = addNested(scope, allStatistics);
  1846. child.deserialize(in);
  1847. }
  1848. }
  1849. void CNestedRuntimeStatisticMap::deserializeMerge(MemoryBuffer& in)
  1850. {
  1851. unsigned numItems;
  1852. in.readPacked(numItems);
  1853. for (unsigned i=0; i < numItems; i++)
  1854. {
  1855. StatsScopeId scope;
  1856. scope.deserialize(in, currentStatisticsVersion);
  1857. //Use allStatistics as the default mapping if it hasn't already been added.
  1858. CNestedRuntimeStatisticCollection & child = addNested(scope, allStatistics);
  1859. child.deserializeMerge(in);
  1860. }
  1861. }
  1862. void CNestedRuntimeStatisticMap::merge(const CNestedRuntimeStatisticMap & other)
  1863. {
  1864. ForEachItemIn(i, other.map)
  1865. {
  1866. CNestedRuntimeStatisticCollection & cur = other.map.item(i);
  1867. CNestedRuntimeStatisticCollection & target = addNested(cur.scope, cur.queryMapping());
  1868. target.merge(cur);
  1869. }
  1870. }
  1871. void CNestedRuntimeStatisticMap::updateDelta(CNestedRuntimeStatisticMap & target, const CNestedRuntimeStatisticMap & source)
  1872. {
  1873. ForEachItemIn(i, source.map)
  1874. {
  1875. CNestedRuntimeStatisticCollection & curSource = source.map.item(i);
  1876. CNestedRuntimeStatisticCollection & curTarget = target.addNested(curSource.scope, curSource.queryMapping());
  1877. CNestedRuntimeStatisticCollection & curDelta = addNested(curSource.scope, curSource.queryMapping());
  1878. curDelta.updateDelta(curTarget, curSource);
  1879. }
  1880. }
  1881. bool CNestedRuntimeStatisticMap::serialize(MemoryBuffer& out) const
  1882. {
  1883. out.appendPacked(map.ordinality());
  1884. bool nonEmpty = false;
  1885. ForEachItemIn(i, map)
  1886. {
  1887. if (map.item(i).serialize(out))
  1888. nonEmpty = true;
  1889. }
  1890. return nonEmpty;
  1891. }
  1892. void CNestedRuntimeStatisticMap::recordStatistics(IStatisticGatherer & target) const
  1893. {
  1894. ForEachItemIn(i, map)
  1895. map.item(i).recordStatistics(target);
  1896. }
  1897. StringBuffer & CNestedRuntimeStatisticMap::toStr(StringBuffer &str) const
  1898. {
  1899. ForEachItemIn(i, map)
  1900. map.item(i).toStr(str);
  1901. return str;
  1902. }
  1903. StringBuffer & CNestedRuntimeStatisticMap::toXML(StringBuffer &str) const
  1904. {
  1905. ForEachItemIn(i, map)
  1906. map.item(i).toXML(str);
  1907. return str;
  1908. }
  1909. CRuntimeStatisticCollection * CNestedRuntimeStatisticMap::createStats(const StatisticsMapping & mapping)
  1910. {
  1911. return new CRuntimeStatisticCollection(mapping);
  1912. }
  1913. CRuntimeStatisticCollection * CNestedSummaryRuntimeStatisticMap::createStats(const StatisticsMapping & mapping)
  1914. {
  1915. return new CRuntimeSummaryStatisticCollection(mapping);
  1916. }
  1917. //---------------------------------------------------
  1918. bool ScopedItemFilter::matchDepth(unsigned low, unsigned high) const
  1919. {
  1920. if (maxDepth && low && maxDepth < low)
  1921. return false;
  1922. if (minDepth && high && minDepth > high)
  1923. return false;
  1924. return true;
  1925. }
  1926. bool ScopedItemFilter::match(const char * search) const
  1927. {
  1928. if (search)
  1929. {
  1930. if (value)
  1931. {
  1932. if (hasWildcard)
  1933. {
  1934. //MORE: If wildcarding ends up being used a lot then this should be replaced with something that creates a DFA
  1935. if (!WildMatch(search, value, false))
  1936. return false;
  1937. }
  1938. else
  1939. {
  1940. return streq(search, value);
  1941. }
  1942. }
  1943. if (minDepth || maxDepth)
  1944. {
  1945. unsigned searchDepth = queryStatisticsDepth(search);
  1946. if (searchDepth < minDepth)
  1947. return false;
  1948. if (maxDepth && searchDepth > maxDepth)
  1949. return false;
  1950. }
  1951. }
  1952. return true;
  1953. }
  1954. bool ScopedItemFilter::recurseChildScopes(const char * curScope) const
  1955. {
  1956. if (maxDepth == 0 || !curScope)
  1957. return true;
  1958. if (queryStatisticsDepth(curScope) >= maxDepth)
  1959. return false;
  1960. return true;
  1961. }
  1962. void ScopedItemFilter::set(const char * _value)
  1963. {
  1964. if (_value && *_value && !streq(_value, "*") )
  1965. {
  1966. value.set(_value);
  1967. minDepth = queryStatisticsDepth(_value);
  1968. if (!strchr(_value, '*'))
  1969. {
  1970. maxDepth = minDepth;
  1971. hasWildcard = strchr(_value, '?') != NULL;
  1972. }
  1973. else
  1974. hasWildcard = true;
  1975. }
  1976. else
  1977. value.clear();
  1978. }
  1979. void ScopedItemFilter::setDepth(unsigned _depth)
  1980. {
  1981. minDepth = _depth;
  1982. maxDepth = _depth;
  1983. }
  1984. void ScopedItemFilter::setDepth(unsigned _minDepth, unsigned _maxDepth)
  1985. {
  1986. minDepth = _minDepth;
  1987. maxDepth = _maxDepth;
  1988. }
  1989. StatisticsFilter::StatisticsFilter()
  1990. {
  1991. init();
  1992. }
  1993. StatisticsFilter::StatisticsFilter(const char * filter)
  1994. {
  1995. init();
  1996. setFilter(filter);
  1997. }
  1998. StatisticsFilter::StatisticsFilter(StatisticCreatorType _creatorType, StatisticScopeType _scopeType, StatisticMeasure _measure, StatisticKind _kind)
  1999. {
  2000. init();
  2001. creatorType = _creatorType;
  2002. scopeType = _scopeType;
  2003. measure = _measure;
  2004. kind = _kind;
  2005. }
  2006. StatisticsFilter::StatisticsFilter(const char * _creatorType, const char * _scopeType, const char * _kind)
  2007. {
  2008. init();
  2009. set(_creatorType, _scopeType, _kind);
  2010. }
  2011. StatisticsFilter::StatisticsFilter(const char * _creatorTypeText, const char * _creator, const char * _scopeTypeText, const char * _scope, const char * _measureText, const char * _kindText)
  2012. {
  2013. init();
  2014. set(_creatorTypeText, _creator, _scopeTypeText, _scope, _measureText, _kindText);
  2015. }
  2016. StatisticsFilter::StatisticsFilter(StatisticCreatorType _creatorType, const char * _creator, StatisticScopeType _scopeType, const char * _scope, StatisticMeasure _measure, StatisticKind _kind)
  2017. {
  2018. init();
  2019. creatorType = _creatorType;
  2020. setCreator(_creator);
  2021. scopeType = _scopeType;
  2022. setScope(_scope);
  2023. measure = _measure;
  2024. kind = _kind;
  2025. }
  2026. void StatisticsFilter::init()
  2027. {
  2028. creatorType = SCTall;
  2029. scopeType = SSTall;
  2030. measure = SMeasureAll;
  2031. kind = StKindAll;
  2032. }
  2033. bool StatisticsFilter::matches(StatisticCreatorType curCreatorType, const char * curCreator, StatisticScopeType curScopeType, const char * curScope, StatisticMeasure curMeasure, StatisticKind curKind) const
  2034. {
  2035. if ((curCreatorType != SCTall) && (creatorType != SCTall) && (creatorType != curCreatorType))
  2036. return false;
  2037. if ((curScopeType != SSTall) && (scopeType != SSTall) && (scopeType != curScopeType))
  2038. return false;
  2039. if ((curMeasure != SMeasureAll) && (measure != SMeasureAll) && (measure != curMeasure))
  2040. return false;
  2041. if ((curKind!= StKindAll) && (kind != StKindAll) && (kind != curKind))
  2042. return false;
  2043. if (!creatorFilter.match(curCreator))
  2044. return false;
  2045. if (!scopeFilter.match(curScope))
  2046. return false;
  2047. return true;
  2048. }
  2049. bool StatisticsFilter::recurseChildScopes(StatisticScopeType curScopeType, const char * curScope) const
  2050. {
  2051. return scopeFilter.recurseChildScopes(curScope);
  2052. }
  2053. void StatisticsFilter::set(const char * creatorTypeText, const char * scopeTypeText, const char * kindText)
  2054. {
  2055. StatisticCreatorType creatorType = queryCreatorType(creatorTypeText);
  2056. StatisticScopeType scopeType = queryScopeType(scopeTypeText);
  2057. if (creatorType != SCTnone)
  2058. setCreatorType(creatorType);
  2059. if (scopeType != SSTnone)
  2060. setScopeType(scopeType);
  2061. setKind(kindText);
  2062. }
  2063. void StatisticsFilter::set(const char * _creatorTypeText, const char * _creator, const char * _scopeTypeText, const char * _scope, const char * _measureText, const char * _kindText)
  2064. {
  2065. StatisticMeasure newMeasure = queryMeasure(_measureText);
  2066. if (newMeasure != SMeasureNone)
  2067. setMeasure(newMeasure);
  2068. set(_creatorTypeText, _scopeTypeText, _kindText);
  2069. setCreator(_creator);
  2070. setScope(_scope);
  2071. }
  2072. void StatisticsFilter::setCreatorDepth(unsigned _minCreatorDepth, unsigned _maxCreatorDepth)
  2073. {
  2074. creatorFilter.setDepth(_minCreatorDepth, _maxCreatorDepth);
  2075. }
  2076. void StatisticsFilter::setCreator(const char * _creator)
  2077. {
  2078. creatorFilter.set(_creator);
  2079. }
  2080. void StatisticsFilter::setCreatorType(StatisticCreatorType _creatorType)
  2081. {
  2082. creatorType = _creatorType;
  2083. }
  2084. void StatisticsFilter::addFilter(const char * filter)
  2085. {
  2086. //Match a filter of the form category[value] (use square brackets to avoid bash grief)
  2087. const char * openBra = strchr(filter, '[');
  2088. if (!openBra)
  2089. return;
  2090. const char * closeBra = strchr(openBra, ']');
  2091. if (!closeBra)
  2092. return;
  2093. const char * start = openBra + 1;
  2094. StringBuffer value(closeBra - start, start);
  2095. if (hasPrefix(filter, "creator[", false))
  2096. setCreator(value);
  2097. else if (hasPrefix(filter, "creatortype[", false))
  2098. setCreatorType(queryCreatorType(value));
  2099. else if (hasPrefix(filter, "depth[", false))
  2100. {
  2101. const char * comma = strchr(value, ',');
  2102. if (comma)
  2103. setScopeDepth(atoi(value), atoi(comma+1));
  2104. else
  2105. setScopeDepth(atoi(value));
  2106. }
  2107. else if (hasPrefix(filter, "kind[", false))
  2108. setKind(value);
  2109. else if (hasPrefix(filter, "measure[", false))
  2110. setMeasure(queryMeasure(value));
  2111. else if (hasPrefix(filter, "scope[", false))
  2112. setScope(value);
  2113. else if (hasPrefix(filter, "scopetype[", false))
  2114. setScopeType(queryScopeType(value));
  2115. else
  2116. throw MakeStringException(1, "Unknown stats filter '%s' - expected creator,creatortype,depth,kind,measure,scope,scopetype", filter);
  2117. }
  2118. void StatisticsFilter::setFilter(const char * filter)
  2119. {
  2120. if (isEmptyString(filter))
  2121. return;
  2122. loop
  2123. {
  2124. const char * closeBra = strchr(filter, ']');
  2125. if (!closeBra)
  2126. throw MakeStringException(1, "Missing close bracket ']' in '%s' ", filter);
  2127. const char * comma = strchr(closeBra, ',');
  2128. if (comma)
  2129. {
  2130. //Take a copy - simplicity rather than efficiency
  2131. StringBuffer temp(comma - filter, filter);
  2132. addFilter(temp);
  2133. filter = comma + 1;
  2134. }
  2135. else
  2136. {
  2137. addFilter(filter);
  2138. return;
  2139. }
  2140. }
  2141. }
  2142. void StatisticsFilter::setScopeDepth(unsigned _scopeDepth)
  2143. {
  2144. scopeFilter.setDepth(_scopeDepth);
  2145. }
  2146. void StatisticsFilter::setScopeDepth(unsigned _minScopeDepth, unsigned _maxScopeDepth)
  2147. {
  2148. scopeFilter.setDepth(_minScopeDepth, _maxScopeDepth);
  2149. }
  2150. void StatisticsFilter::setScope(const char * _scope)
  2151. {
  2152. scopeFilter.set(_scope);
  2153. }
  2154. void StatisticsFilter::setScopeType(StatisticScopeType _scopeType)
  2155. {
  2156. scopeType = _scopeType;
  2157. }
  2158. void StatisticsFilter::setMeasure(StatisticMeasure _measure)
  2159. {
  2160. measure = _measure;
  2161. }
  2162. void StatisticsFilter::setKind(StatisticKind _kind)
  2163. {
  2164. kind = _kind;
  2165. if (measure == SMeasureAll)
  2166. measure = queryMeasure(kind);
  2167. }
  2168. void StatisticsFilter::setKind(const char * _kind)
  2169. {
  2170. if (!_kind || !*_kind || streq(_kind, "*"))
  2171. {
  2172. if (measure == SMeasureNone)
  2173. measure = SMeasureAll;
  2174. kind = StKindAll;
  2175. return;
  2176. }
  2177. //Convert a kind wildcard to a measure
  2178. for (unsigned i1=SMeasureAll+1; i1 < SMeasureMax; i1++)
  2179. {
  2180. const char * prefix = queryMeasurePrefix((StatisticMeasure)i1);
  2181. size_t len = strlen(prefix);
  2182. if (strnicmp(_kind, prefix, len) == 0)
  2183. {
  2184. setMeasure((StatisticMeasure)i1);
  2185. //Treat When* and When as filters on times.
  2186. if (streq(_kind + len, "*") || !_kind[len])
  2187. return;
  2188. }
  2189. }
  2190. //Other wildcards not currently supported
  2191. kind = queryStatisticKind(_kind);
  2192. }
  2193. //---------------------------------------------------
  2194. class CStatsCategory : public CInterface
  2195. {
  2196. public:
  2197. StringAttr longName;
  2198. StringAttr shortName;
  2199. CStatsCategory(const char *_longName, const char *_shortName)
  2200. : longName(_longName), shortName(_shortName)
  2201. {
  2202. }
  2203. bool match(const char *_longName, const char *_shortName)
  2204. {
  2205. bool lm = stricmp(_longName, longName)==0;
  2206. bool sm = stricmp(_shortName, shortName)==0;
  2207. if (lm || sm)
  2208. {
  2209. if (lm && sm)
  2210. return true;
  2211. throw MakeStringException(0, "A stats category %s (%s) is already registered", shortName.get(), longName.get());
  2212. }
  2213. return false;
  2214. }
  2215. };
  2216. static CIArrayOf<CStatsCategory> statsCategories;
  2217. static CriticalSection statsCategoriesCrit;
  2218. extern int registerStatsCategory(const char *longName, const char *shortName)
  2219. {
  2220. CriticalBlock b(statsCategoriesCrit);
  2221. ForEachItemIn(idx, statsCategories)
  2222. {
  2223. if (statsCategories.item(idx).match(longName, shortName))
  2224. return idx;
  2225. }
  2226. statsCategories.append(*new CStatsCategory(longName, shortName));
  2227. return statsCategories.ordinality()-1;
  2228. }
  2229. static void checkKind(StatisticKind kind)
  2230. {
  2231. if (kind < StMax)
  2232. {
  2233. const StatisticMeta & meta = statsMetaData[kind];
  2234. if (meta.kind != kind)
  2235. throw makeStringExceptionV(0, "Statistic %u in the wrong order", kind);
  2236. }
  2237. StatisticMeasure measure = queryMeasure(kind);
  2238. const char * shortName = queryStatisticName(kind);
  2239. StringBuffer longName;
  2240. queryLongStatisticName(longName, kind);
  2241. const char * tagName __attribute__ ((unused)) = queryTreeTag(kind);
  2242. const char * prefix = queryMeasurePrefix(measure);
  2243. //Check short names are all correctly prefixed.
  2244. assertex(strncmp(shortName, prefix, strlen(prefix)) == 0);
  2245. }
  2246. static void checkDistributedKind(StatisticKind kind)
  2247. {
  2248. checkKind(kind);
  2249. checkKind((StatisticKind)(kind|StMinX));
  2250. checkKind((StatisticKind)(kind|StMaxX));
  2251. checkKind((StatisticKind)(kind|StAvgX));
  2252. checkKind((StatisticKind)(kind|StSkew));
  2253. checkKind((StatisticKind)(kind|StSkewMin));
  2254. checkKind((StatisticKind)(kind|StSkewMax));
  2255. checkKind((StatisticKind)(kind|StNodeMin));
  2256. checkKind((StatisticKind)(kind|StNodeMax));
  2257. checkKind((StatisticKind)(kind|StDeltaX));
  2258. }
  2259. void verifyStatisticFunctions()
  2260. {
  2261. assertex(_elements_in(measureNames) == SMeasureMax+1 && !measureNames[SMeasureMax]);
  2262. assertex(_elements_in(creatorTypeNames) == SCTmax+1 && !creatorTypeNames[SCTmax]);
  2263. assertex(_elements_in(scopeTypeNames) == SSTmax+1 && !scopeTypeNames[SSTmax]);
  2264. //Check the various functions return values for all possible values.
  2265. for (unsigned i1=SMeasureAll; i1 < SMeasureMax; i1++)
  2266. {
  2267. const char * prefix __attribute__((unused)) = queryMeasurePrefix((StatisticMeasure)i1);
  2268. const char * name = queryMeasureName((StatisticMeasure)i1);
  2269. assertex(queryMeasure(name) == i1);
  2270. }
  2271. for (StatisticScopeType sst = SSTnone; sst < SSTmax; sst = (StatisticScopeType)(sst+1))
  2272. {
  2273. const char * name = queryScopeTypeName(sst);
  2274. assertex(queryScopeType(name) == sst);
  2275. }
  2276. for (StatisticCreatorType sct = SCTnone; sct < SCTmax; sct = (StatisticCreatorType)(sct+1))
  2277. {
  2278. const char * name = queryCreatorTypeName(sct);
  2279. assertex(queryCreatorType(name) == sct);
  2280. }
  2281. for (unsigned i2=StKindAll+1; i2 < StMax; i2++)
  2282. {
  2283. checkDistributedKind((StatisticKind)i2);
  2284. }
  2285. }
  2286. #if 0
  2287. MODULE_INIT(INIT_PRIORITY_STANDARD)
  2288. {
  2289. verifyStatisticFunctions();
  2290. return true;
  2291. }
  2292. #endif