jstats.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  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. #ifdef _WIN32
  20. #include <sys/timeb.h>
  21. #endif
  22. static CriticalSection statsNameCs;
  23. static StringBuffer statisticsComponentName;
  24. static StatisticCreatorType statisticsComponentType = SCTunknown;
  25. StatisticCreatorType queryStatisticsComponentType()
  26. {
  27. return statisticsComponentType;
  28. }
  29. const char * queryStatisticsComponentName()
  30. {
  31. CriticalBlock c(statsNameCs);
  32. if (statisticsComponentName.length() == 0)
  33. {
  34. statisticsComponentName.append("unknown").append(GetCachedHostName());
  35. DBGLOG("getProcessUniqueName hasn't been configured correctly");
  36. }
  37. return statisticsComponentName.str();
  38. }
  39. void setStatisticsComponentName(StatisticCreatorType processType, const char * processName, bool appendIP)
  40. {
  41. if (!processName)
  42. return;
  43. CriticalBlock c(statsNameCs);
  44. statisticsComponentType = processType;
  45. statisticsComponentName.clear().append(processName);
  46. if (appendIP)
  47. statisticsComponentName.append("@").append(GetCachedHostName()); // should I use _ instead?
  48. }
  49. //--------------------------------------------------------------------------------------------------------------------
  50. // Textual forms of the different enumerations, first items are for none and all.
  51. static const char * const measureNames[] = { "", "all", "ns", "ts", "cnt", "sz", "cpu", "skw", "node", "ppm", "ip", NULL };
  52. static const char * const creatorTypeNames[]= { "", "all", "unknown", "hthor", "roxie", "roxie:s", "thor", "thor:m", "thor:s", "eclcc", "esp", "summary", NULL };
  53. static const char * const scopeTypeNames[] = { "", "all", "global", "graph", "subgraph", "activity", "allocator", "section", "compile", "dfu", "edge", NULL };
  54. static unsigned matchString(const char * const * names, const char * search)
  55. {
  56. if (!search)
  57. return 0;
  58. if (streq(search, "*"))
  59. search = "all";
  60. unsigned i=0;
  61. loop
  62. {
  63. const char * next = names[i];
  64. if (!next)
  65. return 0;
  66. if (streq(next, search))
  67. return i;
  68. i++;
  69. }
  70. }
  71. //--------------------------------------------------------------------------------------------------------------------
  72. extern jlib_decl unsigned __int64 getTimeStampNowValue()
  73. {
  74. #ifdef _WIN32
  75. struct _timeb now;
  76. _ftime(&now);
  77. return (unsigned __int64)now.time * I64C(1000000) + now.millitm * 1000;
  78. #else
  79. struct timeval tm;
  80. gettimeofday(&tm,NULL);
  81. return (unsigned __int64)tm.tv_sec * I64C(1000000) + tm.tv_usec;
  82. #endif
  83. }
  84. const static unsigned __int64 msUntilResync = 1000; // resync every second ~= 1ms accuracy
  85. static cycle_t cyclesUntilResync;
  86. MODULE_INIT(INIT_PRIORITY_STANDARD)
  87. {
  88. cyclesUntilResync = nanosec_to_cycle(msUntilResync * 1000000);
  89. return true;
  90. }
  91. OptimizedTimestamp::OptimizedTimestamp()
  92. {
  93. lastCycles = get_cycles_now();
  94. lastTimestamp = ::getTimeStampNowValue();
  95. }
  96. #if 0
  97. //This version almost certainly has problems if the computer is suspended and cycles->nanoseconds is only accurate to
  98. //about 0.1% - so should only be used for relatively short periods
  99. unsigned __int64 OptimizedTimestamp::getTimeStampNowValue()
  100. {
  101. cycle_t nowCycles = get_cycles_now();
  102. return lastTimestamp + cycle_to_microsec(nowCycles - lastCycles);
  103. }
  104. #else
  105. //This version will resync every minute, but is not thread safe. Adding a critical section makes it less efficient than recalculating
  106. unsigned __int64 OptimizedTimestamp::getTimeStampNowValue()
  107. {
  108. cycle_t nowCycles = get_cycles_now();
  109. if (nowCycles - lastCycles > cyclesUntilResync)
  110. {
  111. lastCycles = nowCycles;
  112. lastTimestamp = ::getTimeStampNowValue();
  113. }
  114. return lastTimestamp + cycle_to_microsec(nowCycles - lastCycles);
  115. }
  116. #endif
  117. unsigned __int64 getIPV4StatsValue(const IpAddress & ip)
  118. {
  119. unsigned ipValue;
  120. if (ip.getNetAddress(sizeof(ipValue),&ipValue))
  121. return ipValue;
  122. return 0;
  123. }
  124. //--------------------------------------------------------------------------------------------------------------------
  125. const static unsigned __int64 oneMilliSecond = I64C(1000000);
  126. const static unsigned __int64 oneSecond = I64C(1000000000);
  127. const static unsigned __int64 oneMinute = I64C(60000000000);
  128. const static unsigned __int64 oneHour = I64C(3600000000000);
  129. const static unsigned __int64 oneDay = 24 * I64C(3600000000000);
  130. static void formatTime(StringBuffer & out, unsigned __int64 value)
  131. {
  132. //Aim to display at least 3 significant digits in the result string
  133. if (value < oneMilliSecond)
  134. out.appendf("%uns", (unsigned)value);
  135. else if (value < oneSecond)
  136. {
  137. unsigned uvalue = (unsigned)value;
  138. out.appendf("%u.%03ums", uvalue / 1000000, (uvalue / 1000) % 1000);
  139. }
  140. else
  141. {
  142. unsigned days = (unsigned)(value / oneDay);
  143. value = value % oneDay;
  144. unsigned hours = (unsigned)(value / oneHour);
  145. value = value % oneHour;
  146. unsigned mins = (unsigned)(value / oneMinute);
  147. value = value % oneMinute;
  148. unsigned secs = (unsigned)(value / oneSecond);
  149. unsigned ns = (unsigned)(value % oneSecond);
  150. if (days > 0)
  151. out.appendf("%u days ", days);
  152. if (hours > 0 || days)
  153. out.appendf("%u:%02u:%02u", hours, mins, secs);
  154. else if (mins >= 10)
  155. out.appendf("%u:%02u", mins, secs);
  156. else if (mins >= 1)
  157. out.appendf("%u:%02u.%03u", mins, secs, ns / 1000000);
  158. else
  159. out.appendf("%u.%03us", secs, ns / 1000000);
  160. }
  161. }
  162. static void formatTimeStamp(StringBuffer & out, unsigned __int64 value)
  163. {
  164. time_t seconds = value / 1000000;
  165. unsigned us = value % 1000000;
  166. char timeStamp[64];
  167. time_t tNow = seconds;
  168. #ifdef _WIN32
  169. struct tm *gmtNow;
  170. gmtNow = gmtime(&tNow);
  171. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%S", gmtNow);
  172. #else
  173. struct tm gmtNow;
  174. gmtime_r(&tNow, &gmtNow);
  175. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%S", &gmtNow);
  176. #endif //_WIN32
  177. out.append(timeStamp).appendf(".%03uZ", us / 1000);
  178. }
  179. static const unsigned oneKb = 1024;
  180. static const unsigned oneMb = 1024 * 1024;
  181. static const unsigned oneGb = 1024 * 1024 * 1024;
  182. static unsigned toPermille(unsigned x) { return (x * 1000) / 1024; }
  183. static void formatSize(StringBuffer & out, unsigned __int64 value)
  184. {
  185. unsigned Gb = (unsigned)(value / oneGb);
  186. unsigned Mb = (unsigned)((value % oneGb) / oneMb);
  187. unsigned Kb = (unsigned)((value % oneMb) / oneKb);
  188. unsigned b = (unsigned)(value % oneKb);
  189. if (Gb)
  190. out.appendf("%u.%03uGb", Gb, toPermille(Mb));
  191. else if (Mb)
  192. out.appendf("%u.%03uMb", Mb, toPermille(Kb));
  193. else if (Kb)
  194. out.appendf("%u.%03uKb", Kb, toPermille(b));
  195. else
  196. out.appendf("%ub", b);
  197. }
  198. static void formatLoad(StringBuffer & out, unsigned __int64 value)
  199. {
  200. //Stored as millionth of a core. Display as a percentage => scale by 10,000
  201. out.appendf("%u.%03u%%", (unsigned)(value / 10000), (unsigned)(value % 10000) / 10);
  202. }
  203. static void formatSkew(StringBuffer & out, unsigned __int64 value)
  204. {
  205. //Skew stored as 10000 = perfect, display as percentage
  206. out.appendf("%.2f%%", ((double)(__int64)value) / 100.0);
  207. }
  208. static void formatIPV4(StringBuffer & out, unsigned __int64 value)
  209. {
  210. byte ip1 = (value & 255);
  211. byte ip2 = ((value >> 8) & 255);
  212. byte ip3 = ((value >> 16) & 255);
  213. byte ip4 = ((value >> 24) & 255);
  214. out.appendf("%d.%d.%d.%d", ip1, ip2, ip3, ip4);
  215. }
  216. void formatStatistic(StringBuffer & out, unsigned __int64 value, StatisticMeasure measure)
  217. {
  218. switch (measure)
  219. {
  220. case SMeasureTimeNs:
  221. formatTime(out, value);
  222. break;
  223. case SMeasureTimestampUs:
  224. formatTimeStamp(out, value);
  225. break;
  226. case SMeasureCount:
  227. out.append(value);
  228. break;
  229. case SMeasureSize:
  230. formatSize(out, value);
  231. break;
  232. case SMeasureLoad:
  233. formatLoad(out, value);
  234. break;
  235. case SMeasureSkew:
  236. formatSkew(out, value);
  237. break;
  238. case SMeasureNode:
  239. out.append(value);
  240. break;
  241. case SMeasurePercent:
  242. out.appendf("%.2f%%", (double)value / 10000.0); // stored as ppm
  243. break;
  244. case SMeasureIPV4:
  245. formatIPV4(out, value);
  246. break;
  247. default:
  248. throwUnexpected();
  249. }
  250. }
  251. void formatStatistic(StringBuffer & out, unsigned __int64 value, StatisticKind kind)
  252. {
  253. formatStatistic(out, value, queryMeasure(kind));
  254. }
  255. //--------------------------------------------------------------------------------------------------------------------
  256. unsigned queryStatisticsDepth(const char * text)
  257. {
  258. unsigned depth = 1;
  259. loop
  260. {
  261. switch (*text)
  262. {
  263. case 0:
  264. return depth;
  265. case ':':
  266. depth++;
  267. break;
  268. }
  269. text++;
  270. }
  271. }
  272. const char * queryMeasurePrefix(StatisticMeasure measure)
  273. {
  274. switch (measure)
  275. {
  276. case SMeasureAll: return NULL;
  277. case SMeasureTimeNs: return "Time";
  278. case SMeasureTimestampUs: return "When";
  279. case SMeasureCount: return "Num";
  280. case SMeasureSize: return "Size";
  281. case SMeasureLoad: return "Load";
  282. case SMeasureSkew: return "Skew";
  283. case SMeasureNode: return "Node";
  284. case SMeasurePercent: return "Per";
  285. case SMeasureIPV4: return "Ip";
  286. default:
  287. throwUnexpected();
  288. }
  289. }
  290. const char * queryMeasureName(StatisticMeasure measure)
  291. {
  292. return measureNames[measure];
  293. }
  294. StatisticMeasure queryMeasure(const char * measure)
  295. {
  296. //MORE: Use a hash table??
  297. StatisticMeasure ret = (StatisticMeasure)matchString(measureNames, measure);
  298. //Legacy support for an unusual statistic - pretend the sizes are in bytes instead of kb.
  299. if ((ret == SMeasureNone) && measure && streq(measure, "kb"))
  300. ret = SMeasureSize;
  301. return ret;
  302. }
  303. StatsMergeAction queryMergeMode(StatisticMeasure measure)
  304. {
  305. switch (measure)
  306. {
  307. case SMeasureTimeNs: return StatsMergeSum;
  308. case SMeasureTimestampUs: return StatsMergeKeep;
  309. case SMeasureCount: return StatsMergeSum;
  310. case SMeasureSize: return StatsMergeSum;
  311. case SMeasureLoad: return StatsMergeMax;
  312. case SMeasureSkew: return StatsMergeMax;
  313. case SMeasureNode: return StatsMergeKeep;
  314. case SMeasurePercent: return StatsMergeReplace;
  315. case SMeasureIPV4: return StatsMergeKeep;
  316. default:
  317. throwUnexpected();
  318. }
  319. }
  320. extern jlib_decl StatsMergeAction queryMergeMode(StatisticKind kind)
  321. {
  322. //MORE: Optimize by looking up in the meta
  323. return queryMergeMode(queryMeasure(kind));
  324. }
  325. //--------------------------------------------------------------------------------------------------------------------
  326. #define BASE_NAMES(x, y) \
  327. #x #y, \
  328. #x "Min" # y, \
  329. #x "Max" # y, \
  330. #x "Avg" # y, \
  331. "Skew" # y, \
  332. "SkewMin" # y, \
  333. "SkewMax" # y, \
  334. "NodeMin" # y, \
  335. "NodeMax" # y,
  336. #define NAMES(x, y) \
  337. BASE_NAMES(x, y) \
  338. #x "Delta" # y
  339. #define TIMENAMES(x, y) \
  340. BASE_NAMES(x, y) \
  341. "TimeDelta" # y
  342. #define BASE_TAGS(x, y) \
  343. "@" #x "Min" # y, \
  344. "@" #x "Max" # y, \
  345. "@" #x "Avg" # y, \
  346. "@Skew" # y, \
  347. "@SkewMin" # y, \
  348. "@SkewMax" # y, \
  349. "@NodeMin" # y, \
  350. "@NodeMax" # y,
  351. //Default tags nothing special overriden
  352. #define TAGS(x, y) \
  353. "@" #x #y, \
  354. BASE_TAGS(x, y) \
  355. "@" #x "Delta" # y
  356. //Define the tags for time items.
  357. #define TIMETAGS(x, y) \
  358. "@" #x #y, \
  359. BASE_TAGS(x, y) \
  360. "@TimeDelta" # y
  361. #define LEGACYTAGS(dft) \
  362. dft, \
  363. NULL, \
  364. NULL, \
  365. NULL, \
  366. NULL, \
  367. NULL, \
  368. NULL, \
  369. NULL, \
  370. NULL, \
  371. NULL
  372. #define CORESTAT(x, y, m) St##x##y, m, { NAMES(x, y) }, { TAGS(x, y) }
  373. #define STAT(x, y, m) CORESTAT(x, y, m), { LEGACYTAGS(NULL) }
  374. #define TAGSTAT(x, y, m, dft) St##x##y, m, { NAMES(x, y) }, { TAGS(x, y) }, { LEGACYTAGS(dft) }
  375. //--------------------------------------------------------------------------------------------------------------------
  376. //These are the macros to use to define the different entries in the stats meta table
  377. #define TIMESTAT(y) STAT(Time, y, SMeasureTimeNs)
  378. #define WHENSTAT(y) St##When##y, SMeasureTimestampUs, { TIMENAMES(When, y) }, { TIMETAGS(When, y) }, { LEGACYTAGS(NULL) }
  379. #define NUMSTAT(y) STAT(Num, y, SMeasureCount)
  380. #define SIZESTAT(y) STAT(Size, y, SMeasureSize)
  381. #define LOADSTAT(y) STAT(Load, y, SMeasureLoad)
  382. #define SKEWSTAT(y) STAT(Skew, y, SMeasureSkew)
  383. #define NODESTAT(y) STAT(Node, y, SMeasureNode)
  384. #define PERSTAT(y) STAT(Per, y, SMeasurePercent)
  385. #define IPV4STAT(y) STAT(IPV4, y, SMeasureIPV4)
  386. //The following variants are used where a different tag name is required
  387. #define TIMESTAT2(y, dft) TAGSTAT(Time, y, SMeasureTimeNs, dft)
  388. #define NUMSTAT2(y, dft) TAGSTAT(Num, y, SMeasureCount, dft)
  389. //--------------------------------------------------------------------------------------------------------------------
  390. class StatisticMeta
  391. {
  392. public:
  393. StatisticKind kind;
  394. StatisticMeasure measure;
  395. const char * names[StNextModifier/StVariantScale];
  396. const char * tags[StNextModifier/StVariantScale];
  397. const char * legacytags[StNextModifier/StVariantScale];
  398. };
  399. static const StatisticMeta statsMetaData[StMax] = {
  400. { StKindNone, SMeasureNone, { "none" }, { "@none" } },
  401. { StKindAll, SMeasureAll, { "all" }, { "@all" } },
  402. { WHENSTAT(GraphStarted) },
  403. { WHENSTAT(GraphFinished) },
  404. { WHENSTAT(FirstRow) },
  405. { WHENSTAT(QueryStarted) },
  406. { WHENSTAT(QueryFinished) },
  407. { WHENSTAT(Created) },
  408. { WHENSTAT(Compiled) },
  409. { WHENSTAT(WorkunitModified) },
  410. { TIMESTAT(Elapsed) },
  411. { CORESTAT(Time, LocalExecute, SMeasureTimeNs), { "@localTime", "@timeMinMs", "@timeMaxMs" } },
  412. { TIMESTAT2(TotalExecute, "@totalTime") },
  413. { TIMESTAT(Remaining) },
  414. { SIZESTAT(GeneratedCpp) },
  415. { SIZESTAT(PeakMemory) },
  416. { SIZESTAT(MaxRowSize) },
  417. { CORESTAT(Num, RowsProcessed, SMeasureCount), { "@count", "@min", "@max", NULL, "skew", "minskew", "maxskew", NULL, NULL, NULL } },
  418. { NUMSTAT2(Slaves, "@slaves") },
  419. { NUMSTAT2(Started, "@started") },
  420. { NUMSTAT2(Stopped, "@stopped") },
  421. { NUMSTAT2(IndexSeeks, "@seeks") },
  422. { NUMSTAT2(IndexScans, "@scans") },
  423. { NUMSTAT2(IndexWildSeeks, "@wildscans") },
  424. { NUMSTAT2(IndexSkips, "@skips") },
  425. { NUMSTAT2(IndexNullSkips, "@nullskips") },
  426. { NUMSTAT2(IndexMerges, "@merges") },
  427. { NUMSTAT2(IndexMergeCompares, "@mergecompares") },
  428. { NUMSTAT2(PreFiltered, "@prefiltered") },
  429. { NUMSTAT2(PostFiltered, "@postfiltered") },
  430. { NUMSTAT2(BlobCacheHits, "@blobhit") },
  431. { NUMSTAT2(LeafCacheHits, "@leafhit") },
  432. { NUMSTAT2(NodeCacheHits, "@nodehit") },
  433. { NUMSTAT2(BlobCacheAdds, "@blobadd") },
  434. { NUMSTAT2(LeafCacheAdds, "@leadadd") },
  435. { NUMSTAT2(NodeCacheAdds, "@nodeadd") },
  436. { NUMSTAT2(PreloadCacheHits, "@preloadhits") },
  437. { NUMSTAT2(PreloadCacheAdds, "@preloadadds") },
  438. { NUMSTAT2(ServerCacheHits, "@sschits") },
  439. { NUMSTAT2(IndexAccepted, "@accepted") },
  440. { NUMSTAT2(IndexRejected, "@rejected") },
  441. { NUMSTAT2(AtmostTriggered, "@atmost") },
  442. { NUMSTAT2(DiskSeeks, "@fseeks") },
  443. { NUMSTAT(Iterations) },
  444. { LOADSTAT(WhileSorting) },
  445. { NUMSTAT(LeftRows) },
  446. { NUMSTAT(RightRows) },
  447. { PERSTAT(Replicated) },
  448. { NUMSTAT(DiskRowsRead) },
  449. { NUMSTAT(IndexRowsRead) },
  450. { NUMSTAT(DiskAccepted) },
  451. { NUMSTAT(DiskRejected) },
  452. { TIMESTAT(Soapcall) },
  453. { TIMESTAT(FirstExecute) },
  454. };
  455. //--------------------------------------------------------------------------------------------------------------------
  456. StatisticMeasure queryMeasure(StatisticKind kind)
  457. {
  458. unsigned variant = queryStatsVariant(kind);
  459. switch (variant)
  460. {
  461. case StSkew:
  462. case StSkewMin:
  463. case StSkewMax:
  464. return SMeasureSkew;
  465. case StNodeMin:
  466. case StNodeMax:
  467. return SMeasureNode;
  468. case StDeltaX:
  469. {
  470. StatisticMeasure measure = queryMeasure((StatisticKind)(kind & StKindMask));
  471. switch (measure)
  472. {
  473. case SMeasureTimestampUs:
  474. return SMeasureTimeNs;
  475. default:
  476. return measure;
  477. }
  478. break;
  479. }
  480. }
  481. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  482. dbgassertex(rawkind >= StKindNone && rawkind < StMax);
  483. return statsMetaData[rawkind].measure;
  484. }
  485. const char * queryStatisticName(StatisticKind kind)
  486. {
  487. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  488. unsigned variant = (kind / StVariantScale);
  489. dbgassertex(rawkind >= StKindNone && rawkind < StMax);
  490. dbgassertex(variant < (StNextModifier/StVariantScale));
  491. return statsMetaData[rawkind].names[variant];
  492. }
  493. //--------------------------------------------------------------------------------------------------------------------
  494. void queryLongStatisticName(StringBuffer & out, StatisticKind kind)
  495. {
  496. out.append(queryStatisticName(kind));
  497. }
  498. //--------------------------------------------------------------------------------------------------------------------
  499. const char * queryTreeTag(StatisticKind kind)
  500. {
  501. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  502. unsigned variant = (kind / StVariantScale);
  503. dbgassertex(rawkind >= StKindNone && rawkind < StMax);
  504. dbgassertex(variant < (StNextModifier/StVariantScale));
  505. return statsMetaData[rawkind].tags[variant];
  506. }
  507. const char * queryLegacyTreeTag(StatisticKind kind)
  508. {
  509. StatisticKind rawkind = (StatisticKind)(kind & StKindMask);
  510. unsigned variant = (kind / StVariantScale);
  511. dbgassertex(rawkind >= StKindNone && rawkind < StMax);
  512. dbgassertex(variant < (StNextModifier/StVariantScale));
  513. return statsMetaData[rawkind].legacytags[variant];
  514. }
  515. //--------------------------------------------------------------------------------------------------------------------
  516. StatisticKind queryStatisticKind(const char * search)
  517. {
  518. if (!search)
  519. return StKindNone;
  520. if (streq(search, "*"))
  521. return StKindAll;
  522. //Slow - should use a hash table....
  523. for (unsigned i=0; i < StMax; i++)
  524. {
  525. StatisticKind kind = (StatisticKind)i;
  526. const char * shortName = queryStatisticName(kind);
  527. if (strieq(shortName, search))
  528. return kind;
  529. }
  530. return StKindNone;
  531. }
  532. //--------------------------------------------------------------------------------------------------------------------
  533. const char * queryCreatorTypeName(StatisticCreatorType sct)
  534. {
  535. return creatorTypeNames[sct];
  536. }
  537. StatisticCreatorType queryCreatorType(const char * sct)
  538. {
  539. //MORE: Use a hash table??
  540. return (StatisticCreatorType)matchString(creatorTypeNames, sct);
  541. }
  542. //--------------------------------------------------------------------------------------------------------------------
  543. const char * queryScopeTypeName(StatisticScopeType sst)
  544. {
  545. return scopeTypeNames[sst];
  546. }
  547. extern jlib_decl StatisticScopeType queryScopeType(const char * sst)
  548. {
  549. //MORE: Use a hash table??
  550. return (StatisticScopeType)matchString(scopeTypeNames, sst);
  551. }
  552. //--------------------------------------------------------------------------------------------------------------------
  553. inline void mergeUpdate(StatisticMeasure measure, unsigned __int64 & value, const unsigned __int64 otherValue)
  554. {
  555. switch (measure)
  556. {
  557. case SMeasureTimeNs:
  558. case SMeasureCount:
  559. case SMeasureSize:
  560. case SMeasureLoad:
  561. case SMeasureSkew:
  562. value += otherValue;
  563. break;
  564. case SMeasureTimestampUs:
  565. if (otherValue && otherValue < value)
  566. value = otherValue;
  567. break;
  568. }
  569. }
  570. unsigned __int64 mergeStatistic(StatisticMeasure measure, unsigned __int64 value, unsigned __int64 otherValue)
  571. {
  572. mergeUpdate(measure, value, otherValue);
  573. return value;
  574. }
  575. unsigned __int64 mergeStatisticValue(unsigned __int64 prevValue, unsigned __int64 newValue, StatsMergeAction mergeAction)
  576. {
  577. switch (mergeAction)
  578. {
  579. case StatsMergeKeep:
  580. return prevValue;
  581. case StatsMergeAppend:
  582. case StatsMergeReplace:
  583. return newValue;
  584. case StatsMergeSum:
  585. return prevValue + newValue;
  586. case StatsMergeMin:
  587. if (prevValue > newValue)
  588. return newValue;
  589. else
  590. return prevValue;
  591. case StatsMergeMax:
  592. if (prevValue < newValue)
  593. return newValue;
  594. else
  595. return prevValue;
  596. default:
  597. throwUnexpected();
  598. }
  599. }
  600. //--------------------------------------------------------------------------------------------------------------------
  601. class CComponentStatistics
  602. {
  603. protected:
  604. StringAttr creator;
  605. byte creatorDepth;
  606. byte scopeDepth;
  607. // StatisticArray stats;
  608. };
  609. //--------------------------------------------------------------------------------------------------------------------
  610. static int compareUnsigned(unsigned const * left, unsigned const * right)
  611. {
  612. return (*left < *right) ? -1 : (*left > *right) ? +1 : 0;
  613. }
  614. StatisticsMapping::StatisticsMapping(StatisticKind kind, ...)
  615. {
  616. indexToKind.append(kind);
  617. va_list args;
  618. va_start(args, kind);
  619. for (;;)
  620. {
  621. unsigned next = va_arg(args, unsigned);
  622. if (!next)
  623. break;
  624. indexToKind.appendUniq(next);
  625. }
  626. va_end(args);
  627. createMappings();
  628. }
  629. StatisticsMapping::StatisticsMapping(const StatisticsMapping * from, ...)
  630. {
  631. ForEachItemIn(idx, from->indexToKind)
  632. indexToKind.append(from->indexToKind.item(idx));
  633. va_list args;
  634. va_start(args, from);
  635. for (;;)
  636. {
  637. unsigned next = va_arg(args, unsigned);
  638. if (!next)
  639. break;
  640. indexToKind.appendUniq(next);
  641. }
  642. va_end(args);
  643. createMappings();
  644. }
  645. StatisticsMapping::StatisticsMapping()
  646. {
  647. for (int i = StKindAll+1; i < StMax; i++)
  648. indexToKind.append(i);
  649. createMappings();
  650. }
  651. void StatisticsMapping::createMappings()
  652. {
  653. //Possibly not needed, but sort the kinds, so that it is easy to merge/stream the results out in the correct order.
  654. indexToKind.sort(compareUnsigned);
  655. //Provide mappings to all statistics to map them to the "unknown" bin by default
  656. for (unsigned i=0; i < StMax; i++)
  657. kindToIndex.append(numStatistics());
  658. ForEachItemIn(i2, indexToKind)
  659. {
  660. unsigned kind = indexToKind.item(i2);
  661. kindToIndex.replace(i2, kind);
  662. }
  663. }
  664. const StatisticsMapping allStatistics;
  665. //--------------------------------------------------------------------------------------------------------------------
  666. class Statistic : public CInterfaceOf<IStatistic>
  667. {
  668. public:
  669. Statistic(StatisticKind _kind, unsigned __int64 _value) : kind(_kind), value(_value)
  670. {
  671. }
  672. static Statistic * deserialize(MemoryBuffer & in, unsigned version)
  673. {
  674. return new Statistic(in, version);
  675. }
  676. virtual StatisticKind queryKind() const
  677. {
  678. return kind;
  679. }
  680. virtual unsigned __int64 queryValue() const
  681. {
  682. return value;
  683. }
  684. void merge(unsigned __int64 otherValue)
  685. {
  686. mergeUpdate(queryMeasure(kind), value, otherValue);
  687. }
  688. void serialize(MemoryBuffer & out) const
  689. {
  690. //MORE: Could compress - e.g., store as a packed integers
  691. out.append((unsigned)kind);
  692. out.append(value);
  693. }
  694. protected:
  695. Statistic(MemoryBuffer & in, unsigned version)
  696. {
  697. unsigned _kind;
  698. in.read(_kind);
  699. kind = (StatisticKind)_kind;
  700. in.read(value);
  701. }
  702. public:
  703. StatisticKind kind;
  704. unsigned __int64 value;
  705. };
  706. //--------------------------------------------------------------------------------------------------------------------
  707. StringBuffer & StatsScopeId::getScopeText(StringBuffer & out) const
  708. {
  709. switch (scopeType)
  710. {
  711. case SSTgraph:
  712. return out.append(GraphScopePrefix).append(id);
  713. case SSTsubgraph:
  714. return out.append(SubGraphScopePrefix).append(id);
  715. case SSTactivity:
  716. return out.append(ActivityScopePrefix).append(id);
  717. case SSTedge:
  718. return out.append(EdgeScopePrefix).append(id).append("_").append(extra);
  719. default:
  720. throwUnexpected();
  721. }
  722. }
  723. unsigned StatsScopeId::getHash() const
  724. {
  725. return hashc((const byte *)&id, sizeof(id), (unsigned)scopeType);
  726. }
  727. bool StatsScopeId::matches(const StatsScopeId & other) const
  728. {
  729. return (scopeType == other.scopeType) && (id == other.id) && (extra == other.extra);
  730. }
  731. unsigned StatsScopeId::queryActivity() const
  732. {
  733. switch (scopeType)
  734. {
  735. case SSTactivity:
  736. case SSTedge:
  737. return id;
  738. default:
  739. return 0;
  740. }
  741. }
  742. void StatsScopeId::deserialize(MemoryBuffer & in, unsigned version)
  743. {
  744. byte scopeTypeByte;
  745. in.read(scopeTypeByte);
  746. scopeType = (StatisticScopeType)scopeTypeByte;
  747. switch (scopeType)
  748. {
  749. case SSTgraph:
  750. case SSTsubgraph:
  751. case SSTactivity:
  752. in.read(id);
  753. break;
  754. case SSTedge:
  755. in.read(id);
  756. in.read(extra);
  757. break;
  758. default:
  759. throwUnexpected();
  760. }
  761. }
  762. void StatsScopeId::serialize(MemoryBuffer & out) const
  763. {
  764. out.append((byte)scopeType);
  765. switch (scopeType)
  766. {
  767. case SSTgraph:
  768. case SSTsubgraph:
  769. case SSTactivity:
  770. out.append(id);
  771. break;
  772. case SSTedge:
  773. out.append(id);
  774. out.append(extra);
  775. break;
  776. default:
  777. throwUnexpected();
  778. }
  779. }
  780. void StatsScopeId::setId(StatisticScopeType _scopeType, unsigned _id, unsigned _extra)
  781. {
  782. scopeType = _scopeType;
  783. id = _id;
  784. extra = _extra;
  785. }
  786. bool StatsScopeId::setScopeText(const char * text)
  787. {
  788. if (MATCHES_CONST_PREFIX(text, ActivityScopePrefix))
  789. setActivityId(atoi(text + CONST_STRLEN(ActivityScopePrefix)));
  790. else if (MATCHES_CONST_PREFIX(text, GraphScopePrefix))
  791. setId(SSTgraph, atoi(text + CONST_STRLEN(GraphScopePrefix)));
  792. else if (MATCHES_CONST_PREFIX(text, SubGraphScopePrefix))
  793. setSubgraphId(atoi(text + CONST_STRLEN(SubGraphScopePrefix)));
  794. else if (MATCHES_CONST_PREFIX(text, EdgeScopePrefix))
  795. {
  796. const char * underscore = strchr(text, '_');
  797. if (!underscore)
  798. return false;
  799. setEdgeId(atoi(text + CONST_STRLEN(EdgeScopePrefix)), atoi(underscore+1));
  800. }
  801. else
  802. return false;
  803. return true;
  804. }
  805. void StatsScopeId::setActivityId(unsigned _id)
  806. {
  807. setId(SSTactivity, _id);
  808. }
  809. void StatsScopeId::setEdgeId(unsigned _id, unsigned _output)
  810. {
  811. setId(SSTedge, _id, _output);
  812. }
  813. void StatsScopeId::setSubgraphId(unsigned _id)
  814. {
  815. setId(SSTsubgraph, _id);
  816. }
  817. //Use an atom table to minimimize memory usage in esp.
  818. //The class could try and use a combination of the scope type and an unsigned, but I suspect not worth it.
  819. IAtom * createStatsScope(const char * name)
  820. {
  821. //MORE: Should this use a separate atom table?
  822. return createAtom(name);
  823. }
  824. IAtom * createActivityScope(unsigned value)
  825. {
  826. char temp[12];
  827. sprintf(temp, ActivityScopePrefix "%u", value);
  828. return createStatsScope(temp);
  829. }
  830. static IAtom * createSubGraphScope(unsigned value)
  831. {
  832. char temp[13];
  833. sprintf(temp, SubGraphScopePrefix "%u", value);
  834. return createStatsScope(temp);
  835. }
  836. IAtom * createEdgeScope(unsigned value1, unsigned value2)
  837. {
  838. StringBuffer temp;
  839. temp.append(EdgeScopePrefix).append(value1).append("_").append(value2);
  840. return createStatsScope(temp);
  841. }
  842. //--------------------------------------------------------------------------------------------------------------------
  843. enum
  844. {
  845. SCroot,
  846. SCintermediate,
  847. SCleaf,
  848. };
  849. class CStatisticCollection;
  850. static CStatisticCollection * deserializeCollection(CStatisticCollection * parent, MemoryBuffer & in, unsigned version);
  851. //MORE: Create an implementation with no children
  852. typedef StructArrayOf<Statistic> StatsArray;
  853. class CollectionHashTable : public SuperHashTableOf<CStatisticCollection, StatsScopeId>
  854. {
  855. public:
  856. ~CollectionHashTable() { releaseAll(); }
  857. virtual void onAdd(void *et);
  858. virtual void onRemove(void *et);
  859. virtual unsigned getHashFromElement(const void *et) const;
  860. virtual unsigned getHashFromFindParam(const void *fp) const;
  861. virtual const void * getFindParam(const void *et) const;
  862. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const;
  863. virtual bool matchesElement(const void *et, const void *searchET) const;
  864. };
  865. typedef IArrayOf<CStatisticCollection> CollectionArray;
  866. class CStatisticCollection : public CInterfaceOf<IStatisticCollection>
  867. {
  868. friend class CollectionHashTable;
  869. public:
  870. CStatisticCollection(CStatisticCollection * _parent, const StatsScopeId & _id) : parent(_parent), id(_id)
  871. {
  872. }
  873. CStatisticCollection(CStatisticCollection * _parent, MemoryBuffer & in, unsigned version) : parent(_parent)
  874. {
  875. id.deserialize(in, version);
  876. unsigned numStats;
  877. in.read(numStats);
  878. stats.ensure(numStats);
  879. while (numStats-- > 0)
  880. {
  881. Statistic * next = Statistic::deserialize(in, version);
  882. stats.append(*next);
  883. }
  884. unsigned numChildren;
  885. in.read(numChildren);
  886. children.ensure(numChildren);
  887. while (numChildren-- > 0)
  888. {
  889. CStatisticCollection * next = deserializeCollection(this, in, version);
  890. children.add(*next);
  891. }
  892. }
  893. virtual byte getCollectionType() const { return SCintermediate; }
  894. //interface IStatisticCollection:
  895. virtual StatisticScopeType queryScopeType() const
  896. {
  897. return id.queryScopeType();
  898. }
  899. virtual unsigned __int64 queryWhenCreated() const
  900. {
  901. if (parent)
  902. return parent->queryWhenCreated();
  903. return 0;
  904. }
  905. virtual StringBuffer & getScope(StringBuffer & str) const
  906. {
  907. return id.getScopeText(str);
  908. }
  909. virtual StringBuffer & getFullScope(StringBuffer & str) const
  910. {
  911. if (parent)
  912. {
  913. parent->getFullScope(str);
  914. str.append(':');
  915. }
  916. id.getScopeText(str);
  917. return str;
  918. }
  919. virtual unsigned __int64 queryStatistic(StatisticKind kind) const
  920. {
  921. ForEachItemIn(i, stats)
  922. {
  923. const Statistic & cur = stats.item(i);
  924. if (cur.kind == kind)
  925. return cur.value;
  926. }
  927. return 0;
  928. }
  929. virtual unsigned getNumStatistics() const
  930. {
  931. return stats.ordinality();
  932. }
  933. virtual void getStatistic(StatisticKind & kind, unsigned __int64 & value, unsigned idx) const
  934. {
  935. const Statistic & cur = stats.item(idx);
  936. kind = cur.kind;
  937. value = cur.value;
  938. }
  939. virtual IStatisticCollectionIterator & getScopes(const char * filter)
  940. {
  941. assertex(!filter);
  942. return * new SuperHashIIteratorOf<IStatisticCollection, IStatisticCollectionIterator, false>(children);
  943. }
  944. virtual void getMinMaxScope(IStringVal & minValue, IStringVal & maxValue, StatisticScopeType searchScopeType) const
  945. {
  946. if (id.queryScopeType() == searchScopeType)
  947. {
  948. const char * curMin = minValue.str();
  949. const char * curMax = maxValue.str();
  950. StringBuffer name;
  951. id.getScopeText(name);
  952. if (!curMin || !*curMin || strcmp(name.str(), curMin) < 0)
  953. minValue.set(name.str());
  954. if (!curMax || strcmp(name.str(), curMax) > 0)
  955. maxValue.set(name.str());
  956. }
  957. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  958. for (iter.first(); iter.isValid(); iter.next())
  959. iter.query().getMinMaxScope(minValue, maxValue, searchScopeType);
  960. }
  961. virtual void getMinMaxActivity(unsigned & minValue, unsigned & maxValue) const
  962. {
  963. unsigned activityId = id.queryActivity();
  964. if (activityId)
  965. {
  966. if ((minValue == 0) || (activityId < minValue))
  967. minValue = activityId;
  968. if (activityId > maxValue)
  969. maxValue = activityId;
  970. }
  971. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  972. for (iter.first(); iter.isValid(); iter.next())
  973. iter.query().getMinMaxActivity(minValue, maxValue);
  974. }
  975. //other public interface functions
  976. void addStatistic(StatisticKind kind, unsigned __int64 value)
  977. {
  978. stats.append(*new Statistic(kind, value));
  979. }
  980. void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  981. {
  982. if (mergeAction != StatsMergeAppend)
  983. {
  984. ForEachItemIn(i, stats)
  985. {
  986. Statistic & cur = stats.element(i);
  987. if (cur.kind == kind)
  988. {
  989. cur.value = mergeStatisticValue(cur.value, value, mergeAction);
  990. return;
  991. }
  992. }
  993. }
  994. stats.append(*new Statistic(kind, value));
  995. }
  996. CStatisticCollection * ensureSubScope(const StatsScopeId & search, bool hasChildren)
  997. {
  998. //MORE: Implement hasChildren
  999. return resolveSubScope(search, true, false);
  1000. }
  1001. CStatisticCollection * resolveSubScope(const StatsScopeId & search, bool create, bool replace)
  1002. {
  1003. if (!replace)
  1004. {
  1005. CStatisticCollection * match = children.find(&search);
  1006. if (match)
  1007. return LINK(match);
  1008. }
  1009. if (create)
  1010. {
  1011. CStatisticCollection * ret = new CStatisticCollection(this, search);
  1012. children.add(*ret);
  1013. return LINK(ret);
  1014. }
  1015. return NULL;
  1016. }
  1017. virtual void serialize(MemoryBuffer & out) const
  1018. {
  1019. out.append(getCollectionType());
  1020. id.serialize(out);
  1021. out.append(stats.ordinality());
  1022. ForEachItemIn(iStat, stats)
  1023. stats.item(iStat).serialize(out);
  1024. out.append(children.ordinality());
  1025. SuperHashIteratorOf<CStatisticCollection> iter(children, false);
  1026. for (iter.first(); iter.isValid(); iter.next())
  1027. iter.query().serialize(out);
  1028. }
  1029. private:
  1030. StatsScopeId id;
  1031. CStatisticCollection * parent;
  1032. CollectionHashTable children;
  1033. StatsArray stats;
  1034. };
  1035. //---------------------------------------------------------------------------------------------------------------------
  1036. void CollectionHashTable::onAdd(void *et)
  1037. {
  1038. }
  1039. void CollectionHashTable::onRemove(void *et)
  1040. {
  1041. CStatisticCollection * elem = reinterpret_cast<CStatisticCollection *>(et);
  1042. elem->Release();
  1043. }
  1044. unsigned CollectionHashTable::getHashFromElement(const void *et) const
  1045. {
  1046. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1047. return elem->id.getHash();
  1048. }
  1049. unsigned CollectionHashTable::getHashFromFindParam(const void *fp) const
  1050. {
  1051. const StatsScopeId * search = reinterpret_cast<const StatsScopeId *>(fp);
  1052. return search->getHash();
  1053. }
  1054. const void * CollectionHashTable::getFindParam(const void *et) const
  1055. {
  1056. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1057. return &elem->id;
  1058. }
  1059. bool CollectionHashTable::matchesFindParam(const void *et, const void *key, unsigned fphash) const
  1060. {
  1061. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1062. const StatsScopeId * search = reinterpret_cast<const StatsScopeId *>(key);
  1063. return elem->id.matches(*search);
  1064. }
  1065. bool CollectionHashTable::matchesElement(const void *et, const void *searchET) const
  1066. {
  1067. const CStatisticCollection * elem = reinterpret_cast<const CStatisticCollection *>(et);
  1068. const CStatisticCollection * searchElem = reinterpret_cast<const CStatisticCollection *>(searchET);
  1069. return elem->id.matches(searchElem->id);
  1070. }
  1071. //---------------------------------------------------------------------------------------------------------------------
  1072. class CRootStatisticCollection : public CStatisticCollection
  1073. {
  1074. public:
  1075. CRootStatisticCollection(StatisticCreatorType _creatorType, const char * _creator, const StatsScopeId & _id)
  1076. : CStatisticCollection(NULL, _id), creatorType(_creatorType), creator(_creator)
  1077. {
  1078. whenCreated = getTimeStampNowValue();
  1079. }
  1080. CRootStatisticCollection(MemoryBuffer & in, unsigned version) : CStatisticCollection(NULL, in, version)
  1081. {
  1082. byte creatorTypeByte;
  1083. in.read(creatorTypeByte);
  1084. creatorType = (StatisticCreatorType)creatorTypeByte;
  1085. in.read(creator);
  1086. in.read(whenCreated);
  1087. }
  1088. virtual byte getCollectionType() const { return SCroot; }
  1089. virtual unsigned __int64 queryWhenCreated() const
  1090. {
  1091. return whenCreated;
  1092. }
  1093. virtual void serialize(MemoryBuffer & out) const
  1094. {
  1095. CStatisticCollection::serialize(out);
  1096. out.append((byte)creatorType);
  1097. out.append(creator);
  1098. out.append(whenCreated);
  1099. }
  1100. public:
  1101. StatisticCreatorType creatorType;
  1102. StringAttr creator;
  1103. unsigned __int64 whenCreated;
  1104. };
  1105. //---------------------------------------------------------------------------------------------------------------------
  1106. void serializeStatisticCollection(MemoryBuffer & out, IStatisticCollection * collection)
  1107. {
  1108. unsigned currentStatisticsVersion = 1;
  1109. out.append(currentStatisticsVersion);
  1110. collection->serialize(out);
  1111. }
  1112. static CStatisticCollection * deserializeCollection(CStatisticCollection * parent, MemoryBuffer & in, unsigned version)
  1113. {
  1114. byte kind;
  1115. in.read(kind);
  1116. switch (kind)
  1117. {
  1118. case SCroot:
  1119. assertex(!parent);
  1120. return new CRootStatisticCollection(in, version);
  1121. case SCintermediate:
  1122. return new CStatisticCollection(parent, in, version);
  1123. default:
  1124. UNIMPLEMENTED;
  1125. }
  1126. }
  1127. IStatisticCollection * createStatisticCollection(MemoryBuffer & in)
  1128. {
  1129. unsigned version;
  1130. in.read(version);
  1131. return deserializeCollection(NULL, in, version);
  1132. }
  1133. //--------------------------------------------------------------------------------------------------------------------
  1134. class StatisticGatherer : implements CInterfaceOf<IStatisticGatherer>
  1135. {
  1136. public:
  1137. StatisticGatherer(CStatisticCollection * scope) : rootScope(scope)
  1138. {
  1139. scopes.append(*scope);
  1140. }
  1141. virtual void beginScope(const StatsScopeId & id)
  1142. {
  1143. CStatisticCollection & tos = scopes.tos();
  1144. scopes.append(*tos.ensureSubScope(id, true));
  1145. }
  1146. virtual void beginActivityScope(unsigned id)
  1147. {
  1148. StatsScopeId scopeId(SSTactivity, id);
  1149. CStatisticCollection & tos = scopes.tos();
  1150. scopes.append(*tos.ensureSubScope(scopeId, false));
  1151. }
  1152. virtual void beginSubGraphScope(unsigned id)
  1153. {
  1154. StatsScopeId scopeId(SSTsubgraph, id);
  1155. CStatisticCollection & tos = scopes.tos();
  1156. scopes.append(*tos.ensureSubScope(scopeId, true));
  1157. }
  1158. virtual void beginEdgeScope(unsigned id, unsigned oid)
  1159. {
  1160. StatsScopeId scopeId(SSTedge, id, oid);
  1161. CStatisticCollection & tos = scopes.tos();
  1162. scopes.append(*tos.ensureSubScope(scopeId, false));
  1163. }
  1164. virtual void endScope()
  1165. {
  1166. scopes.tos().Release();
  1167. scopes.pop();
  1168. }
  1169. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  1170. {
  1171. CStatisticCollection & tos = scopes.tos();
  1172. tos.addStatistic(kind, value);
  1173. }
  1174. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  1175. {
  1176. CStatisticCollection & tos = scopes.tos();
  1177. tos.updateStatistic(kind, value, mergeAction);
  1178. }
  1179. virtual IStatisticCollection * getResult()
  1180. {
  1181. return LINK(rootScope);
  1182. }
  1183. protected:
  1184. ICopyArrayOf<CStatisticCollection> scopes;
  1185. Linked<CStatisticCollection> rootScope;
  1186. };
  1187. extern IStatisticGatherer * createStatisticsGatherer(StatisticCreatorType creatorType, const char * creator, const StatsScopeId & rootScope)
  1188. {
  1189. //creator unused at the moment.
  1190. Owned<CStatisticCollection> rootCollection = new CRootStatisticCollection(creatorType, creator, rootScope);
  1191. return new StatisticGatherer(rootCollection);
  1192. }
  1193. //--------------------------------------------------------------------------------------------------------------------
  1194. void CRuntimeStatistic::merge(unsigned __int64 otherValue, StatsMergeAction mergeAction)
  1195. {
  1196. value = mergeStatisticValue(value, otherValue, mergeAction);
  1197. }
  1198. void CRuntimeStatisticCollection::merge(const CRuntimeStatisticCollection & other)
  1199. {
  1200. ForEachItemIn(i, other)
  1201. {
  1202. StatisticKind kind = other.getKind(i);
  1203. unsigned __int64 value = other.getStatisticValue(kind);
  1204. if (value)
  1205. {
  1206. StatsMergeAction mergeAction = queryMergeMode(kind);
  1207. mergeStatistic(kind, other.getStatisticValue(kind), mergeAction);
  1208. }
  1209. }
  1210. }
  1211. void CRuntimeStatisticCollection::rollupStatistics(unsigned numTargets, IContextLogger * const * targets) const
  1212. {
  1213. ForEachItem(iStat)
  1214. {
  1215. unsigned __int64 value = values[iStat].getClear();
  1216. if (value)
  1217. {
  1218. StatisticKind kind = getKind(iStat);
  1219. for (unsigned iTarget = 0; iTarget < numTargets; iTarget++)
  1220. targets[iTarget]->noteStatistic(kind, value);
  1221. }
  1222. }
  1223. reportIgnoredStats();
  1224. }
  1225. void CRuntimeStatisticCollection::recordStatistics(IStatisticGatherer & target) const
  1226. {
  1227. ForEachItem(i)
  1228. {
  1229. unsigned __int64 value = values[i].get();
  1230. if (value)
  1231. {
  1232. StatisticKind kind = getKind(i);
  1233. StatsMergeAction mergeAction = queryMergeMode(kind);
  1234. target.updateStatistic(kind, values[i].get(), mergeAction);
  1235. }
  1236. }
  1237. reportIgnoredStats();
  1238. }
  1239. void CRuntimeStatisticCollection::reportIgnoredStats() const
  1240. {
  1241. if (values[mapping.numStatistics()].getClear())
  1242. DBGLOG("Some statistics were added but thrown away");
  1243. }
  1244. StringBuffer & CRuntimeStatisticCollection::toXML(StringBuffer &str) const
  1245. {
  1246. ForEachItem(iStat)
  1247. {
  1248. unsigned __int64 value = values[iStat].get();
  1249. if (value)
  1250. {
  1251. StatisticKind kind = getKind(iStat);
  1252. const char * name = queryStatisticName(kind);
  1253. str.appendf("<%s>%" I64F "d</%s>", name, value, name);
  1254. }
  1255. }
  1256. return str;
  1257. }
  1258. StringBuffer & CRuntimeStatisticCollection::toStr(StringBuffer &str) const
  1259. {
  1260. ForEachItem(iStat)
  1261. {
  1262. unsigned __int64 value = values[iStat].get();
  1263. if (value)
  1264. {
  1265. StatisticKind kind = getKind(iStat);
  1266. const char * name = queryStatisticName(kind);
  1267. str.append(' ').append(name).append("=");
  1268. formatStatistic(str, value, kind);
  1269. }
  1270. }
  1271. return str;
  1272. }
  1273. void CRuntimeStatisticCollection::deserialize(MemoryBuffer& in)
  1274. {
  1275. unsigned numValid;
  1276. in.read(numValid);
  1277. for (unsigned i=0; i < numValid; i++)
  1278. {
  1279. unsigned kindVal;
  1280. unsigned __int64 value;
  1281. in.read(kindVal).read(value);
  1282. StatisticKind kind = (StatisticKind)kindVal;
  1283. setStatistic(kind, value);
  1284. }
  1285. }
  1286. void CRuntimeStatisticCollection::deserializeMerge(MemoryBuffer& in)
  1287. {
  1288. unsigned numValid;
  1289. in.read(numValid);
  1290. for (unsigned i=0; i < numValid; i++)
  1291. {
  1292. unsigned kindVal;
  1293. unsigned __int64 value;
  1294. in.read(kindVal).read(value);
  1295. StatisticKind kind = (StatisticKind)kindVal;
  1296. StatsMergeAction mergeAction = queryMergeMode(kind);
  1297. mergeStatistic(kind, value, mergeAction);
  1298. }
  1299. }
  1300. bool CRuntimeStatisticCollection::serialize(MemoryBuffer& out) const
  1301. {
  1302. unsigned numValid = 0;
  1303. ForEachItem(i1)
  1304. {
  1305. if (values[i1].get())
  1306. numValid++;
  1307. }
  1308. //out.ensure(sizeof(unsigned)+numValid*(sizeof(unsigned)+sizeof(unsigned __int64)));
  1309. out.append(numValid);
  1310. ForEachItem(i2)
  1311. {
  1312. unsigned __int64 value = values[i2].get();
  1313. if (value)
  1314. {
  1315. out.append((unsigned)mapping.getKind(i2));
  1316. out.append(value);
  1317. }
  1318. }
  1319. return numValid != 0;
  1320. }
  1321. //---------------------------------------------------
  1322. bool ScopedItemFilter::matchDepth(unsigned low, unsigned high) const
  1323. {
  1324. if (maxDepth && low && maxDepth < low)
  1325. return false;
  1326. if (minDepth && high && minDepth > high)
  1327. return false;
  1328. return true;
  1329. }
  1330. bool ScopedItemFilter::match(const char * search) const
  1331. {
  1332. if (search)
  1333. {
  1334. if (value)
  1335. {
  1336. if (hasWildcard)
  1337. {
  1338. //MORE: If wildcarding ends up being used a lot then this should be replaced with something that creates a DFA
  1339. if (!WildMatch(search, value, false))
  1340. return false;
  1341. }
  1342. else
  1343. {
  1344. return streq(search, value);
  1345. }
  1346. }
  1347. if (minDepth || maxDepth)
  1348. {
  1349. unsigned searchDepth = queryStatisticsDepth(search);
  1350. if (searchDepth < minDepth)
  1351. return false;
  1352. if (maxDepth && searchDepth > maxDepth)
  1353. return false;
  1354. }
  1355. }
  1356. return true;
  1357. }
  1358. bool ScopedItemFilter::recurseChildScopes(const char * curScope) const
  1359. {
  1360. if (maxDepth == 0 || !curScope)
  1361. return true;
  1362. if (queryStatisticsDepth(curScope) >= maxDepth)
  1363. return false;
  1364. return true;
  1365. }
  1366. void ScopedItemFilter::set(const char * _value)
  1367. {
  1368. if (_value && *_value && !streq(_value, "*") )
  1369. {
  1370. value.set(_value);
  1371. minDepth = queryStatisticsDepth(_value);
  1372. if (!strchr(_value, '*'))
  1373. {
  1374. maxDepth = minDepth;
  1375. hasWildcard = strchr(_value, '?') != NULL;
  1376. }
  1377. else
  1378. hasWildcard = true;
  1379. }
  1380. else
  1381. value.clear();
  1382. }
  1383. void ScopedItemFilter::setDepth(unsigned _depth)
  1384. {
  1385. minDepth = _depth;
  1386. maxDepth = _depth;
  1387. }
  1388. void ScopedItemFilter::setDepth(unsigned _minDepth, unsigned _maxDepth)
  1389. {
  1390. minDepth = _minDepth;
  1391. maxDepth = _maxDepth;
  1392. }
  1393. StatisticsFilter::StatisticsFilter()
  1394. {
  1395. init();
  1396. }
  1397. StatisticsFilter::StatisticsFilter(const char * filter)
  1398. {
  1399. init();
  1400. setFilter(filter);
  1401. }
  1402. StatisticsFilter::StatisticsFilter(StatisticCreatorType _creatorType, StatisticScopeType _scopeType, StatisticMeasure _measure, StatisticKind _kind)
  1403. {
  1404. init();
  1405. creatorType = _creatorType;
  1406. scopeType = _scopeType;
  1407. measure = _measure;
  1408. kind = _kind;
  1409. }
  1410. StatisticsFilter::StatisticsFilter(const char * _creatorType, const char * _scopeType, const char * _kind)
  1411. {
  1412. init();
  1413. set(_creatorType, _scopeType, _kind);
  1414. }
  1415. StatisticsFilter::StatisticsFilter(const char * _creatorTypeText, const char * _creator, const char * _scopeTypeText, const char * _scope, const char * _measureText, const char * _kindText)
  1416. {
  1417. init();
  1418. set(_creatorTypeText, _creator, _scopeTypeText, _scope, _measureText, _kindText);
  1419. }
  1420. StatisticsFilter::StatisticsFilter(StatisticCreatorType _creatorType, const char * _creator, StatisticScopeType _scopeType, const char * _scope, StatisticMeasure _measure, StatisticKind _kind)
  1421. {
  1422. init();
  1423. creatorType = _creatorType;
  1424. setCreator(_creator);
  1425. scopeType = _scopeType;
  1426. setScope(_scope);
  1427. measure = _measure;
  1428. kind = _kind;
  1429. }
  1430. void StatisticsFilter::init()
  1431. {
  1432. creatorType = SCTall;
  1433. scopeType = SSTall;
  1434. measure = SMeasureAll;
  1435. kind = StKindAll;
  1436. }
  1437. bool StatisticsFilter::matches(StatisticCreatorType curCreatorType, const char * curCreator, StatisticScopeType curScopeType, const char * curScope, StatisticMeasure curMeasure, StatisticKind curKind) const
  1438. {
  1439. if ((curCreatorType != SCTall) && (creatorType != SCTall) && (creatorType != curCreatorType))
  1440. return false;
  1441. if ((curScopeType != SSTall) && (scopeType != SSTall) && (scopeType != curScopeType))
  1442. return false;
  1443. if ((curMeasure != SMeasureAll) && (measure != SMeasureAll) && (measure != curMeasure))
  1444. return false;
  1445. if ((curKind!= StKindAll) && (kind != StKindAll) && (kind != curKind))
  1446. return false;
  1447. if (!creatorFilter.match(curCreator))
  1448. return false;
  1449. if (!scopeFilter.match(curScope))
  1450. return false;
  1451. return true;
  1452. }
  1453. bool StatisticsFilter::recurseChildScopes(StatisticScopeType curScopeType, const char * curScope) const
  1454. {
  1455. return scopeFilter.recurseChildScopes(curScope);
  1456. }
  1457. void StatisticsFilter::set(const char * creatorTypeText, const char * scopeTypeText, const char * kindText)
  1458. {
  1459. StatisticCreatorType creatorType = queryCreatorType(creatorTypeText);
  1460. StatisticScopeType scopeType = queryScopeType(scopeTypeText);
  1461. if (creatorType != SCTnone)
  1462. setCreatorType(creatorType);
  1463. if (scopeType != SSTnone)
  1464. setScopeType(scopeType);
  1465. setKind(kindText);
  1466. }
  1467. void StatisticsFilter::set(const char * _creatorTypeText, const char * _creator, const char * _scopeTypeText, const char * _scope, const char * _measureText, const char * _kindText)
  1468. {
  1469. StatisticMeasure newMeasure = queryMeasure(_measureText);
  1470. if (newMeasure != SMeasureNone)
  1471. setMeasure(newMeasure);
  1472. set(_creatorTypeText, _scopeTypeText, _kindText);
  1473. setCreator(_creator);
  1474. setScope(_scope);
  1475. }
  1476. void StatisticsFilter::setCreatorDepth(unsigned _minCreatorDepth, unsigned _maxCreatorDepth)
  1477. {
  1478. creatorFilter.setDepth(_minCreatorDepth, _maxCreatorDepth);
  1479. }
  1480. void StatisticsFilter::setCreator(const char * _creator)
  1481. {
  1482. creatorFilter.set(_creator);
  1483. }
  1484. void StatisticsFilter::setCreatorType(StatisticCreatorType _creatorType)
  1485. {
  1486. creatorType = _creatorType;
  1487. }
  1488. void StatisticsFilter::setFilter(const char * filter)
  1489. {
  1490. //MORE: Process the filter from a text representation
  1491. }
  1492. void StatisticsFilter::setScopeDepth(unsigned _scopeDepth)
  1493. {
  1494. scopeFilter.setDepth(_scopeDepth);
  1495. }
  1496. void StatisticsFilter::setScopeDepth(unsigned _minScopeDepth, unsigned _maxScopeDepth)
  1497. {
  1498. scopeFilter.setDepth(_minScopeDepth, _maxScopeDepth);
  1499. }
  1500. void StatisticsFilter::setScope(const char * _scope)
  1501. {
  1502. scopeFilter.set(_scope);
  1503. }
  1504. void StatisticsFilter::setScopeType(StatisticScopeType _scopeType)
  1505. {
  1506. scopeType = _scopeType;
  1507. }
  1508. void StatisticsFilter::setMeasure(StatisticMeasure _measure)
  1509. {
  1510. measure = _measure;
  1511. }
  1512. void StatisticsFilter::setKind(StatisticKind _kind)
  1513. {
  1514. kind = _kind;
  1515. if (measure == SMeasureAll)
  1516. measure = queryMeasure(kind);
  1517. }
  1518. void StatisticsFilter::setKind(const char * _kind)
  1519. {
  1520. if (!_kind || !*_kind || streq(_kind, "*"))
  1521. {
  1522. if (measure == SMeasureNone)
  1523. measure = SMeasureAll;
  1524. kind = StKindAll;
  1525. return;
  1526. }
  1527. //Convert a kind wildcard to a measure
  1528. for (unsigned i1=SMeasureAll+1; i1 < SMeasureMax; i1++)
  1529. {
  1530. const char * prefix = queryMeasurePrefix((StatisticMeasure)i1);
  1531. size_t len = strlen(prefix);
  1532. if (strnicmp(_kind, prefix, len) == 0)
  1533. {
  1534. setMeasure((StatisticMeasure)i1);
  1535. //Treat When* and When as filters on times.
  1536. if (streq(_kind + len, "*") || !_kind[len])
  1537. return;
  1538. }
  1539. }
  1540. //Other wildcards not currently supported
  1541. kind = queryStatisticKind(_kind);
  1542. }
  1543. //---------------------------------------------------
  1544. class CStatsCategory : public CInterface
  1545. {
  1546. public:
  1547. StringAttr longName;
  1548. StringAttr shortName;
  1549. CStatsCategory(const char *_longName, const char *_shortName)
  1550. : longName(_longName), shortName(_shortName)
  1551. {
  1552. }
  1553. bool match(const char *_longName, const char *_shortName)
  1554. {
  1555. bool lm = stricmp(_longName, longName)==0;
  1556. bool sm = stricmp(_shortName, shortName)==0;
  1557. if (lm || sm)
  1558. {
  1559. if (lm && sm)
  1560. return true;
  1561. throw MakeStringException(0, "A stats category %s (%s) is already registered", shortName.get(), longName.get());
  1562. }
  1563. return false;
  1564. }
  1565. };
  1566. static CIArrayOf<CStatsCategory> statsCategories;
  1567. static CriticalSection statsCategoriesCrit;
  1568. extern int registerStatsCategory(const char *longName, const char *shortName)
  1569. {
  1570. CriticalBlock b(statsCategoriesCrit);
  1571. ForEachItemIn(idx, statsCategories)
  1572. {
  1573. if (statsCategories.item(idx).match(longName, shortName))
  1574. return idx;
  1575. }
  1576. statsCategories.append(*new CStatsCategory(longName, shortName));
  1577. return statsCategories.ordinality()-1;
  1578. }
  1579. static void checkKind(StatisticKind kind)
  1580. {
  1581. StatisticMeasure measure = queryMeasure(kind);
  1582. const char * shortName = queryStatisticName(kind);
  1583. StringBuffer longName;
  1584. queryLongStatisticName(longName, kind);
  1585. const char * tagName = queryTreeTag(kind);
  1586. const char * prefix = queryMeasurePrefix(measure);
  1587. //Check short names are all correctly prefixed.
  1588. assertex(strncmp(shortName, prefix, strlen(prefix)) == 0);
  1589. }
  1590. static void checkDistributedKind(StatisticKind kind)
  1591. {
  1592. checkKind(kind);
  1593. checkKind((StatisticKind)(kind|StMinX));
  1594. checkKind((StatisticKind)(kind|StMaxX));
  1595. checkKind((StatisticKind)(kind|StAvgX));
  1596. checkKind((StatisticKind)(kind|StSkew));
  1597. checkKind((StatisticKind)(kind|StSkewMin));
  1598. checkKind((StatisticKind)(kind|StSkewMax));
  1599. checkKind((StatisticKind)(kind|StNodeMin));
  1600. checkKind((StatisticKind)(kind|StNodeMax));
  1601. checkKind((StatisticKind)(kind|StDeltaX));
  1602. }
  1603. void verifyStatisticFunctions()
  1604. {
  1605. assertex(_elements_in(measureNames) == SMeasureMax+1 && !measureNames[SMeasureMax]);
  1606. assertex(_elements_in(creatorTypeNames) == SCTmax+1 && !creatorTypeNames[SCTmax]);
  1607. assertex(_elements_in(scopeTypeNames) == SSTmax+1 && !scopeTypeNames[SSTmax]);
  1608. //Check the various functions return values for all possible values.
  1609. for (unsigned i1=SMeasureAll; i1 < SMeasureMax; i1++)
  1610. {
  1611. const char * prefix = queryMeasurePrefix((StatisticMeasure)i1);
  1612. const char * name = queryMeasureName((StatisticMeasure)i1);
  1613. assertex(queryMeasure(name) == i1);
  1614. }
  1615. for (StatisticScopeType sst = SSTnone; sst < SSTmax; sst = (StatisticScopeType)(sst+1))
  1616. {
  1617. const char * name = queryScopeTypeName(sst);
  1618. assertex(queryScopeType(name) == sst);
  1619. }
  1620. for (StatisticCreatorType sct = SCTnone; sct < SCTmax; sct = (StatisticCreatorType)(sct+1))
  1621. {
  1622. const char * name = queryCreatorTypeName(sct);
  1623. assertex(queryCreatorType(name) == sct);
  1624. }
  1625. for (unsigned i2=StKindAll+1; i2 < StMax; i2++)
  1626. {
  1627. checkDistributedKind((StatisticKind)i2);
  1628. }
  1629. }
  1630. #if 0
  1631. MODULE_INIT(INIT_PRIORITY_STANDARD)
  1632. {
  1633. verifyStatisticFunctions();
  1634. return true;
  1635. }
  1636. #endif