jstats.cpp 98 KB

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