jstats.cpp 108 KB

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