jdebug.cpp 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jdebug.hpp"
  16. #include "jstring.hpp"
  17. #include "jhash.hpp"
  18. #include "jmisc.hpp"
  19. #include "jexcept.hpp"
  20. #include "jmutex.hpp"
  21. #include "jtime.hpp"
  22. #include <stdio.h>
  23. #include <time.h>
  24. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  25. #undef new
  26. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  27. #endif
  28. #ifdef __linux__
  29. #include <sys/time.h>
  30. #include <sys/resource.h>
  31. #include <unistd.h>
  32. #include <sys/vfs.h>
  33. #include <sys/types.h>
  34. #include <sys/stat.h>
  35. #include <sys/klog.h>
  36. #include <dirent.h>
  37. #endif
  38. //===========================================================================
  39. #ifdef _DEBUG
  40. //#define _USE_MALLOC_HOOK
  41. #else
  42. #undef _USE_MALLOC_HOOK // don't define for release - not threadsafe
  43. #endif
  44. #define _USE_RDTSC true
  45. #ifdef _USE_MALLOC_HOOK
  46. #define REPORT_LARGER_BLOCK_THAN (10*0x100000)
  47. static __int64 totalMem = 0;
  48. static __int64 hwmTotalMem = 0;
  49. #ifdef __linux__
  50. static unsigned memArea[32];
  51. #endif
  52. #endif
  53. #ifndef _WIN32
  54. #ifndef __64BIT__
  55. #define USE_OLD_PU
  56. #endif
  57. #endif
  58. /* LINUX SYS: log KEY
  59. ========================
  60. PU (%) is the percentage CPU in use (unchanged from previously).
  61. MU (%) is what percentage of total (all processes) memory is in use
  62. (ram + swap) or in 32 bit is the percentage of 3GB (address space)
  63. used (whichever larger).
  64. MAL is total memory in use (i.e malloced and not freed ) by this
  65. process (= MMP+SBK)
  66. MMP is the sum of memory mapped (large) blocks in use by this process
  67. (which will be returned to OS when freed).
  68. SBK is the sbrk'ed memory i.e. smaller blocks allocated from the
  69. arena. (note this memory is unlikely to be returned to OS while the
  70. process is still running).
  71. TOT (K) is an indication of the memory footprint of the process.
  72. This is the 'arena' size (which is how much reserved by sbrk) plus the
  73. mmap memory size (MMP).
  74. RAM (K) is how much real memory is in use by all processes - it is
  75. the same as what would be reported by the 'free' command after the
  76. caches/buffers have been subtracted.
  77. SWP (K) is the swap size in use for all processes.
  78. Extended stats
  79. DSK: disk statistics for each disk (e.g. [sda] and [sdb])
  80. r/s read i/o operations per sec (over last period)
  81. kr/s K bytes read per sec
  82. w/s write i/o operations per sec
  83. kw/s K bytes written per sec
  84. busy indication how busy the disk was during period (%)
  85. NIC: network (i.e. eth0) statistics
  86. rxp/s packets received per sec
  87. rxk/s K bytes received per sec
  88. txp/s packets transmitted per sec
  89. txk/s K bytes transmitted per sec
  90. CPU:
  91. usr % at user level
  92. sys % in kernel
  93. iow % waiting for i/o
  94. */
  95. inline void skipSp(const char *&s)
  96. {
  97. while (isspace(*s))
  98. s++;
  99. }
  100. inline offset_t readHexNum(const char *&s)
  101. {
  102. offset_t ret = 0;
  103. loop {
  104. switch (*s) {
  105. case '0':
  106. case '1':
  107. case '2':
  108. case '3':
  109. case '4':
  110. case '5':
  111. case '6':
  112. case '7':
  113. case '8':
  114. case '9': ret = ret*16+(*s-'0');
  115. break;
  116. case 'A':
  117. case 'B':
  118. case 'C':
  119. case 'D':
  120. case 'E':
  121. case 'F': ret = ret*16+(*s-'A'+10);
  122. break;
  123. case 'a':
  124. case 'b':
  125. case 'c':
  126. case 'd':
  127. case 'e':
  128. case 'f': ret = ret*16+(*s-'a'+10);
  129. break;
  130. default:
  131. return ret;
  132. }
  133. s++;
  134. }
  135. return 0;
  136. }
  137. inline offset_t readDecNum(const char *&s)
  138. {
  139. offset_t ret = 0;
  140. loop {
  141. switch (*s) {
  142. case '0':
  143. case '1':
  144. case '2':
  145. case '3':
  146. case '4':
  147. case '5':
  148. case '6':
  149. case '7':
  150. case '8':
  151. case '9': ret = ret*10+(*s-'0');
  152. break;
  153. default:
  154. return ret;
  155. }
  156. s++;
  157. }
  158. return 0;
  159. }
  160. #if defined(_WIN32)
  161. static __int64 numCyclesNTicks;
  162. static __int64 ticksPerSec;
  163. static __int64 numScaleTicks;
  164. static bool useRDTSC = _USE_RDTSC;
  165. static double cycleToNanoScale;
  166. static void calibrate_timing()
  167. {
  168. #ifndef _AMD64_
  169. if (useRDTSC)
  170. {
  171. unsigned long r;
  172. __asm {
  173. mov eax, 1 ;
  174. cpuid ;
  175. mov r, edx
  176. }
  177. if ((r&0x10)==0)
  178. useRDTSC = false;
  179. }
  180. #endif
  181. if (useRDTSC) {
  182. unsigned startu = usTick();
  183. cycle_t start = getTSC();
  184. unsigned s1 = msTick();
  185. unsigned s2;
  186. while (s1==(s2=msTick()));
  187. unsigned s3;
  188. while (s2==(s3=msTick()));
  189. unsigned elapsedu = usTick()-startu;
  190. if (elapsedu) {
  191. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  192. if (numPerUS>0)
  193. {
  194. cycleToNanoScale = 1000.0 / numPerUS;
  195. return;
  196. }
  197. }
  198. ERRLOG("calibrate_timing failed using RDTSC");
  199. useRDTSC = false;
  200. }
  201. static LARGE_INTEGER temp;
  202. QueryPerformanceFrequency(&temp);
  203. ticksPerSec = temp.QuadPart;
  204. numScaleTicks = ticksPerSec/100;
  205. LARGE_INTEGER t1;
  206. LARGE_INTEGER t2;
  207. QueryPerformanceCounter(&t1);
  208. t2.QuadPart=t1.QuadPart;
  209. while (t1.QuadPart==t2.QuadPart) QueryPerformanceCounter(&t1);
  210. cycle_t a1 = getTSC();
  211. t2.QuadPart = t1.QuadPart;
  212. while (t2.QuadPart-t1.QuadPart<numScaleTicks) QueryPerformanceCounter(&t2);
  213. cycle_t a2 = getTSC();
  214. numCyclesNTicks = (a2 - a1);
  215. cycleToNanoScale = ((double)numScaleTicks * 1000000000.0) / ((double)numCyclesNTicks * ticksPerSec);
  216. }
  217. __int64 cycle_to_nanosec(cycle_t cycles)
  218. {
  219. return (__int64)((double)cycles * cycleToNanoScale);
  220. }
  221. cycle_t nanosec_to_cycle(__int64 ns)
  222. {
  223. return (__int64)((double)ns / cycleToNanoScale);
  224. }
  225. cycle_t jlib_decl get_cycles_now()
  226. {
  227. if (useRDTSC)
  228. return getTSC();
  229. LARGE_INTEGER temp;
  230. QueryPerformanceCounter(&temp);
  231. return temp.QuadPart;
  232. }
  233. double getCycleToNanoScale()
  234. {
  235. return cycleToNanoScale;
  236. }
  237. #else
  238. static bool use_gettimeofday=false;
  239. static bool useRDTSC = _USE_RDTSC;
  240. static double cycleToNanoScale;
  241. void calibrate_timing()
  242. {
  243. if (useRDTSC) {
  244. unsigned long eax;
  245. unsigned long ebx;
  246. unsigned long ecx;
  247. unsigned long edx;
  248. #ifdef __64BIT__
  249. __asm__ ("cpuid\n\t" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "0" (1));
  250. #else
  251. // NB PIC code and ebx usage don't mix well
  252. asm volatile("pushl %%ebx \n\t"
  253. "cpuid \n\t"
  254. "movl %%ebx, %1 \n\t"
  255. "popl %%ebx \n\t"
  256. : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx)
  257. : "a"(1)
  258. : "cc");
  259. #endif
  260. if ((edx&0x10)==0)
  261. useRDTSC = false;
  262. }
  263. if (useRDTSC) {
  264. unsigned startu = usTick();
  265. cycle_t start = getTSC();
  266. unsigned s1 = msTick();
  267. unsigned s2;
  268. while (s1==(s2=msTick()));
  269. unsigned s3;
  270. while (s2==(s3=msTick()));
  271. unsigned elapsedu = usTick()-startu;
  272. if (elapsedu) {
  273. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  274. if (numPerUS>0)
  275. {
  276. cycleToNanoScale = 1000.0 / numPerUS;
  277. return;
  278. }
  279. }
  280. ERRLOG("calibrate_timing failed using RDTSC");
  281. useRDTSC = false;
  282. }
  283. cycleToNanoScale = 1.0;
  284. }
  285. cycle_t jlib_decl get_cycles_now()
  286. {
  287. if (useRDTSC)
  288. return getTSC();
  289. #ifndef __APPLE__
  290. if (!use_gettimeofday) {
  291. timespec tm;
  292. if (clock_gettime(CLOCK_MONOTONIC, &tm)>=0)
  293. return ((cycle_t)tm.tv_sec)*1000000000L+(tm.tv_nsec);
  294. use_gettimeofday = true;
  295. fprintf(stderr,"clock_gettime CLOCK_MONOTONIC returns %d",errno); // don't use PROGLOG
  296. }
  297. #endif
  298. struct timeval tm;
  299. gettimeofday(&tm,NULL);
  300. return ((cycle_t)tm.tv_sec)*1000000000L+(cycle_t)tm.tv_usec*1000L;
  301. }
  302. __int64 jlib_decl cycle_to_nanosec(cycle_t cycles)
  303. {
  304. if (useRDTSC)
  305. return (__int64)((double)cycles * cycleToNanoScale);
  306. return cycles;
  307. }
  308. cycle_t nanosec_to_cycle(__int64 ns)
  309. {
  310. if (useRDTSC)
  311. return (__int64)((double)ns / cycleToNanoScale);
  312. return ns;
  313. }
  314. double getCycleToNanoScale()
  315. {
  316. return cycleToNanoScale;
  317. }
  318. #endif
  319. void display_time(const char *title, cycle_t diff)
  320. {
  321. DBGLOG("Time taken for %s: %"I64F"d cycles (%"I64F"dM) = %"I64F"d msec\n", title, diff, diff/1000000, cycle_to_nanosec(diff)/1000000);
  322. }
  323. TimeSection::TimeSection(const char * _title) : title(_title)
  324. {
  325. start_time = get_cycles_now();
  326. }
  327. TimeSection::~TimeSection()
  328. {
  329. cycle_t end_time = get_cycles_now();
  330. if (title)
  331. display_time(title, end_time-start_time);
  332. }
  333. MTimeSection::MTimeSection(ITimeReporter *_master, const char * _title) : title(_title), master(_master)
  334. {
  335. start_time = get_cycles_now();
  336. }
  337. MTimeSection::~MTimeSection()
  338. {
  339. cycle_t end_time = get_cycles_now();
  340. if (master)
  341. master->addTiming(title, end_time-start_time);
  342. else
  343. display_time(title, end_time-start_time);
  344. }
  345. class TimeSectionInfo : public MappingBase
  346. {
  347. public:
  348. TimeSectionInfo(const char *_name, __int64 _time) : name(_name), totaltime(_time), count(1), maxtime(_time) {};
  349. TimeSectionInfo(const char *_name, __int64 _time, __int64 _maxtime, unsigned _count) : name(_name), totaltime(_time), count(_count), maxtime(_maxtime) {};
  350. TimeSectionInfo(MemoryBuffer &mb)
  351. {
  352. mb.read(name).read(totaltime).read(maxtime).read(count);
  353. }
  354. void serialize(MemoryBuffer &mb)
  355. {
  356. mb.append(name).append(totaltime).append(maxtime).append(count);
  357. }
  358. virtual const void * getKey() const { return name.get(); }
  359. StringAttr name;
  360. __int64 totaltime;
  361. __int64 maxtime;
  362. unsigned count;
  363. };
  364. class DefaultTimeReporter : public CInterface, implements ITimeReporter
  365. {
  366. StringMapOf<TimeSectionInfo> *sections;
  367. CriticalSection c;
  368. TimeSectionInfo &findSection(unsigned idx)
  369. {
  370. CriticalBlock b(c);
  371. HashIterator iter(*sections);
  372. for(iter.first(); iter.isValid(); iter.next())
  373. {
  374. if (!idx--)
  375. return (TimeSectionInfo &) iter.query();
  376. }
  377. throw MakeStringException(2, "Invalid index to DefaultTimeReporter");
  378. }
  379. public:
  380. IMPLEMENT_IINTERFACE
  381. DefaultTimeReporter()
  382. {
  383. sections = new StringMapOf<TimeSectionInfo>(true);
  384. }
  385. DefaultTimeReporter(MemoryBuffer &mb)
  386. {
  387. sections = new StringMapOf<TimeSectionInfo>(true);
  388. unsigned ns;
  389. mb.read(ns);
  390. while (ns--)
  391. {
  392. TimeSectionInfo &newinfo = * new TimeSectionInfo(mb);
  393. sections->replaceOwn(newinfo);
  394. }
  395. }
  396. ~DefaultTimeReporter()
  397. {
  398. // printTimings(); // Must explicitly call printTimings - no automatic print (too late here!)
  399. delete sections;
  400. }
  401. virtual void report(ITimeReportInfo &cb)
  402. {
  403. CriticalBlock b(c);
  404. HashIterator iter(*sections);
  405. for(iter.first(); iter.isValid(); iter.next())
  406. {
  407. TimeSectionInfo &ts = (TimeSectionInfo &)iter.query();
  408. cb.report(ts.name, ts.totaltime, ts.maxtime, ts.count);
  409. }
  410. }
  411. virtual void addTiming(const char *title, __int64 time)
  412. {
  413. CriticalBlock b(c);
  414. TimeSectionInfo *info = sections->find(title);
  415. if (info)
  416. {
  417. info->totaltime += time;
  418. if (time > info->maxtime) info->maxtime = time;
  419. info->count++;
  420. }
  421. else
  422. {
  423. TimeSectionInfo &newinfo = * new TimeSectionInfo(title, time);
  424. sections->replaceOwn(newinfo);
  425. }
  426. }
  427. virtual unsigned numSections()
  428. {
  429. CriticalBlock b(c);
  430. return sections->count();
  431. }
  432. virtual __int64 getTime(unsigned idx)
  433. {
  434. CriticalBlock b(c);
  435. return cycle_to_nanosec(findSection(idx).totaltime);
  436. }
  437. virtual __int64 getMaxTime(unsigned idx)
  438. {
  439. CriticalBlock b(c);
  440. return cycle_to_nanosec(findSection(idx).maxtime);
  441. }
  442. virtual unsigned getCount(unsigned idx)
  443. {
  444. CriticalBlock b(c);
  445. return findSection(idx).count;
  446. }
  447. virtual StringBuffer &getSection(unsigned idx, StringBuffer &s)
  448. {
  449. CriticalBlock b(c);
  450. return s.append(findSection(idx).name);
  451. }
  452. virtual void reset()
  453. {
  454. CriticalBlock b(c);
  455. delete sections;
  456. sections = new StringMapOf<TimeSectionInfo>(true);
  457. }
  458. virtual StringBuffer &getTimings(StringBuffer &str)
  459. {
  460. CriticalBlock b(c);
  461. if (numSections())
  462. {
  463. str.append("Timings:\n");
  464. for (unsigned i = 0; i < numSections(); i++)
  465. getSection(i, str.append(" ")).append(" total=")
  466. .append(getTime(i)/1000000)
  467. .append("ms max=")
  468. .append(getMaxTime(i)/1000)
  469. .append("us count=")
  470. .append(getCount(i))
  471. .append(" ave=")
  472. .append((getTime(i)/1000)/getCount(i))
  473. .append("us\n");
  474. }
  475. return str;
  476. }
  477. virtual void printTimings()
  478. {
  479. CriticalBlock b(c);
  480. if (numSections())
  481. {
  482. StringBuffer str;
  483. PrintLog(getTimings(str).str());
  484. }
  485. }
  486. virtual void addTiming(const char *name, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  487. {
  488. CriticalBlock b(c);
  489. TimeSectionInfo *info = sections->find(name);
  490. if (!info)
  491. {
  492. info = new TimeSectionInfo(name, totaltime, maxtime, count);
  493. sections->replaceOwn(*info);
  494. }
  495. else
  496. {
  497. info->totaltime += totaltime;
  498. if (maxtime > info->maxtime) info->maxtime = maxtime;
  499. info->count += count;
  500. }
  501. }
  502. virtual void mergeInto(ITimeReporter &other)
  503. {
  504. CriticalBlock b(c);
  505. HashIterator iter(*sections);
  506. for(iter.first(); iter.isValid(); iter.next())
  507. {
  508. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  509. other.addTiming(ts.name, ts.totaltime, ts.maxtime, ts.count);
  510. }
  511. }
  512. virtual void merge(ITimeReporter &other)
  513. {
  514. CriticalBlock b(c);
  515. other.mergeInto(*this);
  516. }
  517. virtual void serialize(MemoryBuffer &mb)
  518. {
  519. CriticalBlock b(c);
  520. mb.append(numSections());
  521. HashIterator iter(*sections);
  522. for(iter.first(); iter.isValid(); iter.next())
  523. {
  524. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  525. ts.serialize(mb);
  526. }
  527. }
  528. };
  529. ITimeReporter *defaultTimer;
  530. ITimeReporter *timer;
  531. ITimeReporter *createStdTimeReporter() { return new DefaultTimeReporter(); }
  532. ITimeReporter *createStdTimeReporter(MemoryBuffer &mb) { return new DefaultTimeReporter(mb); }
  533. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  534. {
  535. // perform v. early in process startup, ideally this would grab process exclusively for the 2 100ths of a sec it performs calc.
  536. calibrate_timing();
  537. return 1;
  538. }
  539. MODULE_INIT(INIT_PRIORITY_JDEBUG2)
  540. {
  541. timer = defaultTimer = new DefaultTimeReporter();
  542. return true;
  543. }
  544. MODULE_EXIT()
  545. {
  546. ::Release(defaultTimer);
  547. defaultTimer = NULL;
  548. }
  549. //===========================================================================
  550. // Performance Monitor
  551. #ifdef _WIN32
  552. #define SystemBasicInformation 0
  553. #define SystemPerformanceInformation 2
  554. #define SystemTimeInformation 3
  555. #define SystemProcessList 5
  556. typedef enum _PROCESSINFOCLASS {
  557. ProcessBasicInformation,
  558. ProcessQuotaLimits,
  559. ProcessIoCounters,
  560. ProcessVmCounters,
  561. ProcessTimes,
  562. ProcessBasePriority,
  563. ProcessRaisePriority,
  564. ProcessDebugPort,
  565. ProcessExceptionPort,
  566. ProcessAccessToken,
  567. ProcessLdtInformation,
  568. ProcessLdtSize,
  569. ProcessDefaultHardErrorMode,
  570. ProcessIoPortHandlers, // Note: this is kernel mode only
  571. ProcessPooledUsageAndLimits,
  572. ProcessWorkingSetWatch,
  573. ProcessUserModeIOPL,
  574. ProcessEnableAlignmentFaultFixup,
  575. ProcessPriorityClass,
  576. ProcessWx86Information,
  577. ProcessHandleCount,
  578. ProcessAffinityMask,
  579. ProcessPriorityBoost,
  580. ProcessDeviceMap,
  581. ProcessSessionInformation,
  582. ProcessForegroundInformation,
  583. ProcessWow64Information,
  584. MaxProcessInfoClass
  585. } PROCESSINFOCLASS;
  586. typedef LONG NTSTATUS;
  587. #define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
  588. typedef struct
  589. {
  590. DWORD dwUnknown1;
  591. ULONG uKeMaximumIncrement;
  592. ULONG uPageSize;
  593. ULONG uMmNumberOfPhysicalPages;
  594. ULONG uMmLowestPhysicalPage;
  595. ULONG uMmHighestPhysicalPage;
  596. ULONG uAllocationGranularity;
  597. PVOID pLowestUserAddress;
  598. PVOID pMmHighestUserAddress;
  599. ULONG uKeActiveProcessors;
  600. BYTE bKeNumberProcessors;
  601. BYTE bUnknown2;
  602. WORD wUnknown3;
  603. } SYSTEM_BASIC_INFORMATION;
  604. typedef struct
  605. {
  606. LARGE_INTEGER liIdleTime;
  607. DWORD dwSpare[76];
  608. } SYSTEM_PERFORMANCE_INFORMATION;
  609. typedef struct
  610. {
  611. LARGE_INTEGER liKeBootTime;
  612. LARGE_INTEGER liKeSystemTime;
  613. LARGE_INTEGER liExpTimeZoneBias;
  614. ULONG uCurrentTimeZoneId;
  615. DWORD dwReserved;
  616. } SYSTEM_TIME_INFORMATION;
  617. struct PROCESS_BASIC_INFORMATION {
  618. long ExitStatus;
  619. void * PebBaseAddress;
  620. unsigned long AffinityMask;
  621. long BasePriority;
  622. unsigned long UniqueProcessId;
  623. unsigned long InheritedFromUniqueProcessId;
  624. };
  625. // QUOTA_LIMITS
  626. struct __IO_COUNTERS { // defined in SDK
  627. ULONGLONG ReadOperationCount;
  628. ULONGLONG WriteOperationCount;
  629. ULONGLONG OtherOperationCount;
  630. ULONGLONG ReadTransferCount;
  631. ULONGLONG WriteTransferCount;
  632. ULONGLONG OtherTransferCount;
  633. };
  634. struct VM_COUNTERS {
  635. unsigned long PeakVirtualSize;
  636. unsigned long VirtualSize;
  637. unsigned long PageFaultCount;
  638. unsigned long PeakWorkingSetSize;
  639. unsigned long WorkingSetSize;
  640. unsigned long QuotaPeakPagedPoolUsage;
  641. unsigned long QuotaPagedPoolUsage;
  642. unsigned long QuotaPeakNonPagedPoolUsage;
  643. unsigned long QuotaNonPagedPoolUsage;
  644. unsigned long PagefileUsage;
  645. unsigned long PeakPagefileUsage;
  646. };
  647. struct POOLED_USAGE_AND_LIMITS {
  648. unsigned long PeakPagedPoolUsage;
  649. unsigned long PagedPoolUsage;
  650. unsigned long PagedPoolLimit;
  651. unsigned long PeakNonPagedPoolUsage;
  652. unsigned long NonPagedPoolUsage;
  653. unsigned long NonPagedPoolLimit;
  654. unsigned long PeakPagefileUsage;
  655. unsigned long PagefileUsage;
  656. unsigned long PagefileLimit;
  657. };
  658. struct KERNEL_USER_TIMES {
  659. __int64 CreateTime;
  660. __int64 ExitTime;
  661. __int64 KernelTime;
  662. __int64 UserTime;
  663. //__int64 EllapsedTime;
  664. };
  665. // ntdll!NtQuerySystemInformation (NT specific!)
  666. //
  667. // The function copies the system information of the
  668. // specified type into a buffer
  669. //
  670. // NTSYSAPI
  671. // NTSTATUS
  672. // NTAPI
  673. // NtQuerySystemInformation(
  674. // IN UINT SystemInformationClass, // information type
  675. // OUT PVOID SystemInformation, // pointer to buffer
  676. // IN ULONG SystemInformationLength, // buffer size in bytes
  677. // OUT PULONG ReturnLength OPTIONAL // pointer to a 32-bit
  678. // // variable that receives
  679. // // the number of bytes
  680. // // written to the buffer
  681. // );
  682. //
  683. //NTSYSCALLAPI
  684. //NTSTATUS
  685. //NTAPI
  686. //NtQueryInformationProcess(
  687. // IN HANDLE ProcessHandle,
  688. // IN PROCESSINFOCLASS ProcessInformationClass,
  689. // OUT PVOID ProcessInformation,
  690. // IN ULONG ProcessInformationLength,
  691. // OUT PULONG ReturnLength OPTIONAL
  692. // );
  693. typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
  694. typedef LONG (WINAPI *PROCNTQIP)(HANDLE,UINT,PVOID,ULONG,PULONG);
  695. typedef LONG (WINAPI *PROCNTGST)(LARGE_INTEGER*, LARGE_INTEGER*, LARGE_INTEGER*);
  696. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  697. {
  698. // MORE: Might be a better way to get CPU speed (actual) than the one stored in Registry
  699. LONG lRet;
  700. HKEY hKey;
  701. DWORD keyValue;
  702. DWORD valueLen = sizeof(keyValue);
  703. if ((lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0L, KEY_READ , &hKey)) != ERROR_SUCCESS)
  704. {
  705. DBGLOG("RegOpenKeyEx(HKEY_LOCAL_MACHINE, ...) failed to open CentralProcessor\\0 - SysErrorCode=%d", lRet);
  706. }
  707. else if ((lRet = RegQueryValueEx(hKey, TEXT("~MHz"), NULL, NULL, (LPBYTE) &keyValue, &valueLen)) != ERROR_SUCCESS)
  708. {
  709. DBGLOG("RegQueryValueEx() failed to get CPU speed - errorCode=%d", lRet);
  710. RegCloseKey(hKey);
  711. }
  712. else
  713. {
  714. CPUSpeed = keyValue;
  715. RegCloseKey(hKey);
  716. }
  717. SYSTEM_INFO sysInfo;
  718. GetSystemInfo(&sysInfo);
  719. numCPUs = sysInfo.dwNumberOfProcessors;
  720. }
  721. #else // linux
  722. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  723. {
  724. int cpufd = open("/proc/cpuinfo",O_RDONLY);
  725. if (cpufd==-1)
  726. return;
  727. MemoryAttr ma;
  728. char *buf = (char *)ma.allocate(0x10000);
  729. size32_t l=0;
  730. loop {
  731. size32_t rd = read(cpufd, buf+l, 0x10000-1-l);
  732. if ((int)rd<=0)
  733. break;
  734. l += rd;
  735. }
  736. buf[l] = 0;
  737. const char *bufptr = buf;
  738. char * tail;
  739. numCPUs = CPUSpeed = 0;
  740. // MORE: It is a shame that the info in this file (/proc/cpuinfo) are formatted (ie tabs .. etc)
  741. const char *cpuNumTag = "processor\t:";
  742. const char *cpuSpeedTag = "cpu MHz\t\t:";
  743. while (bufptr) {
  744. if (*bufptr =='\n')
  745. bufptr++;
  746. if (strncmp(cpuNumTag, bufptr, strlen(cpuNumTag))==0)
  747. numCPUs++;
  748. else if (strncmp(cpuSpeedTag, bufptr, strlen(cpuSpeedTag))==0)
  749. CPUSpeed = (unsigned)strtol(bufptr+strlen(cpuSpeedTag), &tail, 10);
  750. bufptr = strchr(bufptr, '\n');
  751. }
  752. close(cpufd);
  753. }
  754. static void getMemUsage(unsigned &inuse,unsigned &active,unsigned &total,unsigned &swaptotal,unsigned &swapinuse)
  755. {
  756. unsigned free=0;
  757. unsigned swapfree=0;
  758. active = 0;
  759. inuse = 0;
  760. static int memfd = -1;
  761. if (memfd==-1)
  762. memfd = open("/proc/meminfo",O_RDONLY);
  763. if (memfd==-1)
  764. return;
  765. lseek(memfd, 0L, 0);
  766. char buf[1024];
  767. size32_t l = read(memfd, buf, sizeof(buf)-1);
  768. if ((int)l<=0)
  769. return;
  770. buf[l] = 0;
  771. const char *bufptr = buf;
  772. char * tail;
  773. unsigned i = 7; // supposed to match max number of items extract below
  774. total = swaptotal = free = active = swapfree = 0;
  775. unsigned swapcached = 0;
  776. unsigned cached = 0;
  777. while (bufptr&&i) {
  778. if (*bufptr =='\n')
  779. bufptr++;
  780. i--;
  781. if (strncmp("MemTotal:", bufptr, 9)==0)
  782. total = (unsigned)strtol(bufptr+9, &tail, 10);
  783. else if (strncmp("SwapTotal:", bufptr, 10)==0)
  784. swaptotal = (unsigned)strtol(bufptr+10, &tail, 10);
  785. else if (strncmp("MemFree:", bufptr, 8)==0)
  786. free = (unsigned)strtol(bufptr+8, &tail, 10);
  787. else if (strncmp("Active:", bufptr, 7)==0)
  788. active = (unsigned)strtol(bufptr+7, &tail, 10);
  789. else if (strncmp("SwapFree:", bufptr, 9)==0)
  790. swapfree = (unsigned)strtol(bufptr+9, &tail, 10);
  791. else if (strncmp("Cached:", bufptr, 7)==0)
  792. cached = (unsigned)strtol(bufptr+7, &tail, 10);
  793. else if (strncmp("SwapCached:", bufptr, 11)==0)
  794. swapcached = (unsigned)strtol(bufptr+11, &tail, 10);
  795. else
  796. i++;
  797. bufptr = strchr(bufptr, '\n');
  798. }
  799. inuse = total-free-cached;
  800. swapinuse = swaptotal-swapfree-swapcached;
  801. }
  802. class CInt64fix
  803. {
  804. __int64 val;
  805. public:
  806. CInt64fix()
  807. {
  808. val = 0;
  809. }
  810. void set(int v)
  811. {
  812. __int64 ret = (unsigned)v;
  813. while (val-ret>0x80000000LL)
  814. ret += 0x100000000LL;
  815. val = ret;
  816. }
  817. __int64 get()
  818. {
  819. return val;
  820. }
  821. };
  822. void getMemStats(StringBuffer &out, unsigned &memused, unsigned &memtot)
  823. {
  824. #ifdef __linux__
  825. struct mallinfo mi = mallinfo();
  826. static CInt64fix fixuordblks;
  827. fixuordblks.set(mi.uordblks);
  828. static CInt64fix fixusmblks;
  829. fixusmblks.set(mi.usmblks);
  830. static CInt64fix fixhblkhd;
  831. fixhblkhd.set(mi.hblkhd);
  832. static CInt64fix fixarena;
  833. fixarena.set(mi.arena);
  834. __int64 sbrkmem = fixuordblks.get()+fixusmblks.get();
  835. __int64 mmapmem = fixhblkhd.get();
  836. __int64 arena = fixarena.get();
  837. __int64 total = mmapmem+sbrkmem;
  838. unsigned mu;
  839. unsigned ma;
  840. unsigned mt;
  841. unsigned st;
  842. unsigned su;
  843. getMemUsage(mu,ma,mt,st,su);
  844. unsigned muval = (unsigned)(((__int64)mu+(__int64)su)*100/((__int64)mt+(__int64)st));
  845. __int64 proctot = arena+mmapmem;
  846. if (sizeof(memsize_t)==4) {
  847. unsigned muval2 = (proctot*100)/(3*(__int64)0x40000000);
  848. if (muval2>muval)
  849. muval = muval2;
  850. }
  851. if (muval>100)
  852. muval = 100; // !
  853. unsigned sum = (unsigned)((arena+mmapmem)/1024);
  854. out.appendf("MU=%3u%% MAL=%"I64F"d MMP=%"I64F"d SBK=%"I64F"d TOT=%uK RAM=%uK SWP=%uK",
  855. muval, total, mmapmem, sbrkmem, (unsigned)(proctot/1024), mu, su);
  856. #ifdef _USE_MALLOC_HOOK
  857. if (totalMem)
  858. out.appendf(" TM=%"I64F"d",totalMem);
  859. #endif
  860. memused = mu+su;
  861. memtot = mt+st;
  862. #endif
  863. #if defined (__FreeBSD__) || defined (__APPLE__)
  864. UNIMPLEMENTED;
  865. #endif
  866. }
  867. void getDiskUsage(char const * path, unsigned __int64 & total, unsigned __int64 & inUse)
  868. {
  869. #ifdef __linux__
  870. struct statfs stfs;
  871. if(statfs(path, &stfs) < 0)
  872. {
  873. //PrintLog("statfs error for filesystem '%s'", path);
  874. total = inUse = 0;
  875. }
  876. else
  877. {
  878. struct stat st;
  879. if(stat(path, &st) < 0)
  880. {
  881. //PrintLog("stat error for filesystem '%s'", path);
  882. total = inUse = 0;
  883. }
  884. else
  885. {
  886. total = (unsigned __int64)stfs.f_blocks * st.st_blksize;
  887. inUse = total - (unsigned __int64)stfs.f_bfree * st.st_blksize;
  888. }
  889. }
  890. #endif
  891. #if defined (__FreeBSD__) || defined (__APPLE__)
  892. UNIMPLEMENTED;
  893. #endif
  894. }
  895. #endif
  896. #define RXMAX 1000000 // can be 10x bigger but this produces reasonable amounts
  897. unsigned packetsLasttime;
  898. __int64 packetsLastrx = -1;
  899. __int64 packetsLasttx;
  900. bool getPacketStats(unsigned & tx, unsigned & rx)
  901. {
  902. unsigned thistime = msTick();
  903. JSocketStatistics jstats;
  904. getSocketStatistics(jstats);
  905. bool ret = true;
  906. if(packetsLastrx!=-1)
  907. {
  908. tx = (unsigned) ((jstats.writesize-packetsLasttx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  909. rx = (unsigned) ((jstats.readsize-packetsLastrx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  910. }
  911. else
  912. ret = false;
  913. packetsLastrx = jstats.readsize;
  914. packetsLasttx = jstats.writesize;
  915. packetsLasttime = thistime;
  916. return ret;
  917. }
  918. #ifndef _WIN32
  919. struct CProcInfo: extends CInterface
  920. {
  921. IMPLEMENT_IINTERFACE;
  922. int pid;
  923. char cmd[16];
  924. unsigned tot_utime;
  925. unsigned tot_stime;
  926. unsigned utime;
  927. unsigned stime;
  928. bool active;
  929. bool first;
  930. CProcInfo(int _pid)
  931. {
  932. pid = _pid;
  933. tot_utime = 0;
  934. tot_stime = 0;
  935. utime = 0;
  936. stime = 0;
  937. active = false;
  938. first = true;
  939. }
  940. char *skipnumfld(char *s, const char *&num)
  941. {
  942. while (*s&&isspace(*s))
  943. s++;
  944. num = s;
  945. if ((*s=='-')||(*s=='+'))
  946. s++;
  947. while (*s&&isdigit(*s))
  948. s++;
  949. if (*s==' ')
  950. *(s++)= 0; // terminate num
  951. while (*s&&isspace(*s))
  952. s++;
  953. return s;
  954. }
  955. bool load()
  956. {
  957. StringBuffer fn;
  958. fn.appendf("/proc/%d/stat", pid);
  959. char buf[800]; /* about 40 fields, 64-bit decimal is about 20 chars */
  960. int fd = open(fn.str(), O_RDONLY, 0);
  961. if (fd==-1)
  962. return false;
  963. int rd = read(fd, buf, sizeof(buf)-1);
  964. close(fd);
  965. if (rd<80)
  966. return false;
  967. buf[rd] = 0;
  968. char *s = strchr(buf,'(');
  969. if (!s)
  970. return false;
  971. s++;
  972. unsigned i = 0;
  973. while (*s&&(*s!=')')&&(i<15))
  974. cmd[i++] = *(s++);
  975. if (!*s)
  976. return false;
  977. cmd[i] = 0;
  978. s+=2;
  979. char state = *(s++);
  980. //printf("**'%s'\n",s);
  981. const char *num;
  982. s = skipnumfld(s,num);
  983. int ppid = atoi(num);
  984. // skip pgrp, session, tty_num, tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt
  985. for (i=0;i<9;i++)
  986. s = skipnumfld(s,num);
  987. unsigned prev_utime = tot_utime;
  988. unsigned prev_stime = tot_stime;
  989. s = skipnumfld(s,num);
  990. //printf("**N'%s'\n",num);
  991. tot_utime = (unsigned)atoi64_l(num,strlen(num));
  992. s = skipnumfld(s,num);
  993. //printf("**N'%s'\n",num);
  994. tot_stime = (unsigned)atoi64_l(num,strlen(num));
  995. if (first)
  996. first = false;
  997. else {
  998. stime = tot_stime-prev_stime;
  999. utime = tot_utime-prev_utime;
  1000. }
  1001. active = true;
  1002. return true;
  1003. }
  1004. };
  1005. class CProcessMonitor
  1006. {
  1007. CIArrayOf<CProcInfo> processes;
  1008. unsigned tot_time;
  1009. bool busy;
  1010. static int compare(CInterface **i1, CInterface **i2)
  1011. {
  1012. CProcInfo *pi1 = QUERYINTERFACE(*i1,CProcInfo);
  1013. CProcInfo *pi2 = QUERYINTERFACE(*i2,CProcInfo);
  1014. return pi2->stime+pi2->utime-pi1->stime-pi1->utime;
  1015. }
  1016. public:
  1017. CProcessMonitor()
  1018. {
  1019. busy = false;
  1020. }
  1021. void scan()
  1022. {
  1023. #ifdef __linux__
  1024. ForEachItemIn(i1,processes)
  1025. processes.item(i1).active = false;
  1026. DIR *dir = opendir("/proc");
  1027. loop {
  1028. struct dirent *ent;
  1029. struct dirent entryMem;
  1030. readdir_r(dir, &entryMem, &ent);
  1031. if (!ent)
  1032. break;
  1033. if ((ent->d_name[0]>='0')&&(ent->d_name[0]<='9')) {
  1034. int pid = atoi(ent->d_name);
  1035. if (pid) {
  1036. CProcInfo *pi = NULL;
  1037. ForEachItemIn(i2,processes) {
  1038. if (processes.item(i2).pid == pid) {
  1039. pi = &processes.item(i2);
  1040. break;
  1041. }
  1042. }
  1043. if (!pi) {
  1044. pi = new CProcInfo(pid);
  1045. processes.append(*pi);
  1046. }
  1047. pi->load();
  1048. }
  1049. }
  1050. }
  1051. closedir(dir);
  1052. tot_time = 0;
  1053. ForEachItemInRev(i3,processes) {
  1054. CProcInfo &pi = processes.item(i3);
  1055. if (pi.active)
  1056. tot_time += pi.stime+pi.utime;
  1057. else
  1058. processes.remove(i3);
  1059. }
  1060. #endif
  1061. #if defined (__FreeBSD__) || defined (__APPLE__)
  1062. UNIMPLEMENTED;
  1063. #endif
  1064. }
  1065. void print(unsigned n,StringBuffer &str)
  1066. {
  1067. if (!tot_time)
  1068. return;
  1069. assertex(n);
  1070. processes.sort(compare);
  1071. StringBuffer name;
  1072. ForEachItemIn(i1,processes) {
  1073. CProcInfo &pi = processes.item(i1);
  1074. if ((pi.stime==0)&&(pi.utime==0))
  1075. break;
  1076. getThreadName(pi.pid,0,name.clear());
  1077. str.appendf("\n TT: PI=%d PN=%s PC=%d ST=%d UT=%d%s%s",pi.pid,pi.cmd,(pi.stime+pi.utime)*100/tot_time,pi.stime,pi.utime,name.length()?" TN=":"",name.str());
  1078. if (--n==0)
  1079. break;
  1080. }
  1081. }
  1082. void printBusy(unsigned pc,StringBuffer &str)
  1083. {
  1084. if (pc>90) {
  1085. scan();
  1086. if (busy)
  1087. print(3,str); // print top 3
  1088. else
  1089. busy = true;
  1090. }
  1091. else {
  1092. busy = false;
  1093. processes.kill();
  1094. }
  1095. }
  1096. };
  1097. #ifndef HZ
  1098. #define HZ 100
  1099. #endif
  1100. #define IDE0_MAJOR 3
  1101. #define SCSI_DISK0_MAJOR 8
  1102. #define SCSI_DISK1_MAJOR 65
  1103. #define SCSI_DISK7_MAJOR 71
  1104. #define SCSI_DISK10_MAJOR 128
  1105. #define SCSI_DISK17_MAJOR 135
  1106. #define IDE1_MAJOR 22
  1107. #define IDE2_MAJOR 33
  1108. #define IDE3_MAJOR 34
  1109. #define IDE4_MAJOR 56
  1110. #define IDE5_MAJOR 57
  1111. #define IDE6_MAJOR 88
  1112. #define IDE7_MAJOR 89
  1113. #define IDE8_MAJOR 90
  1114. #define IDE9_MAJOR 91
  1115. #define COMPAQ_SMART2_MAJOR 72
  1116. #define IDE_DISK_MAJOR(M) ((M) == IDE0_MAJOR || (M) == IDE1_MAJOR || \
  1117. (M) == IDE2_MAJOR || (M) == IDE3_MAJOR || \
  1118. (M) == IDE4_MAJOR || (M) == IDE5_MAJOR || \
  1119. (M) == IDE6_MAJOR || (M) == IDE7_MAJOR || \
  1120. (M) == IDE8_MAJOR || (M) == IDE9_MAJOR)
  1121. #define SCSI_DISK_MAJOR(M) ((M) == SCSI_DISK0_MAJOR || \
  1122. ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) || \
  1123. ((M) >= SCSI_DISK10_MAJOR && (M) <= SCSI_DISK17_MAJOR))
  1124. #define OTHER_DISK_MAJOR(M) ((M) == COMPAQ_SMART2_MAJOR) // by investigation!
  1125. class CExtendedStats // Disk network and cpu stats
  1126. {
  1127. struct blkio_info
  1128. {
  1129. unsigned rd_ios; // Read I/O operations
  1130. unsigned rd_merges; // Reads merged
  1131. __uint64 rd_sectors; // Sectors read
  1132. unsigned rd_ticks; // Time in queue + service for read
  1133. unsigned wr_ios; // Write I/O operations
  1134. unsigned wr_merges; // Writes merged
  1135. __uint64 wr_sectors; // Sectors written
  1136. unsigned wr_ticks; // Time in queue + service for write
  1137. unsigned ticks; // Time of requests in queue
  1138. unsigned aveq; // Average queue length
  1139. };
  1140. struct cpu_info
  1141. {
  1142. __uint64 user;
  1143. __uint64 system;
  1144. __uint64 idle;
  1145. __uint64 iowait;
  1146. };
  1147. struct net_info
  1148. {
  1149. __uint64 rxbytes;
  1150. __uint64 rxpackets;
  1151. __uint64 rxerrors;
  1152. __uint64 rxdrops;
  1153. __uint64 txbytes;
  1154. __uint64 txpackets;
  1155. __uint64 txerrors;
  1156. __uint64 txdrops;
  1157. };
  1158. struct part_info
  1159. {
  1160. unsigned int major;
  1161. unsigned int minor;
  1162. char name[32];
  1163. };
  1164. part_info *partition;
  1165. unsigned nparts;
  1166. blkio_info *newblkio;
  1167. blkio_info *oldblkio;
  1168. cpu_info newcpu;
  1169. unsigned numcpu;
  1170. cpu_info oldcpu;
  1171. cpu_info cpu;
  1172. net_info oldnet;
  1173. net_info newnet;
  1174. unsigned ncpu;
  1175. bool first;
  1176. char *kbuf;
  1177. size32_t kbufsz;
  1178. size32_t kbufmax;
  1179. unsigned short kbufcrc;
  1180. __uint64 totalcpu;
  1181. unsigned ndisks;
  1182. int isdisk(unsigned int major, unsigned int minor)
  1183. {
  1184. if (IDE_DISK_MAJOR(major))
  1185. return ((minor&0x3F)==0);
  1186. if (SCSI_DISK_MAJOR(major))
  1187. return ((minor&0x0F)==0);
  1188. if (OTHER_DISK_MAJOR(major))
  1189. return ((minor&0x0F)==0);
  1190. return 0;
  1191. }
  1192. bool getNextCPU()
  1193. {
  1194. oldcpu = newcpu;
  1195. if (!ncpu) {
  1196. unsigned speed;
  1197. getCpuInfo(ncpu, speed);
  1198. if (!ncpu)
  1199. ncpu = 1;
  1200. }
  1201. FILE* cpufp = fopen("/proc/stat", "r");
  1202. if (!cpufp) {
  1203. memset(&cpu,0,sizeof(cpu));
  1204. totalcpu = 0;
  1205. return false;
  1206. }
  1207. char ln[256];
  1208. while (fgets(ln, sizeof(ln), cpufp)) {
  1209. if (strncmp(ln, "cpu ", 4)==0) {
  1210. int items;
  1211. __uint64 nice, irq, softirq;
  1212. items = sscanf(ln,
  1213. "cpu %llu %llu %llu %llu %llu %llu %llu",
  1214. &newcpu.user, &nice,
  1215. &newcpu.system,
  1216. &newcpu.idle,
  1217. &newcpu.iowait,
  1218. &irq, &softirq);
  1219. newcpu.user += nice;
  1220. if (items == 4)
  1221. newcpu.iowait = 0;
  1222. if (items == 7)
  1223. newcpu.system += irq + softirq;
  1224. break;
  1225. }
  1226. }
  1227. fclose(cpufp);
  1228. cpu.user = newcpu.user - oldcpu.user;
  1229. cpu.system = newcpu.system - oldcpu.system;
  1230. cpu.idle = newcpu.idle - oldcpu.idle;
  1231. cpu.iowait = newcpu.iowait - oldcpu.iowait;
  1232. totalcpu = (cpu.user + cpu.system + cpu.idle + cpu.iowait);
  1233. return true;
  1234. }
  1235. bool getDiskInfo()
  1236. {
  1237. char ln[256];
  1238. part_info pi;
  1239. FILE* diskfp = fopen("/proc/diskstats", "r");
  1240. if (!diskfp)
  1241. return false;
  1242. if (!newblkio) {
  1243. nparts = 0;
  1244. while (fgets(ln, sizeof(ln), diskfp)) {
  1245. unsigned reads = 0;
  1246. if (sscanf(ln, "%4d %4d %31s %u", &pi.major, &pi.minor, pi.name, &reads) == 4) {
  1247. unsigned p = 0;
  1248. while ((p<nparts) && (partition[p].major != pi.major || partition[p].minor != pi.minor))
  1249. p++;
  1250. if ((p==nparts) && reads && isdisk(pi.major,pi.minor)) {
  1251. nparts++;
  1252. partition = (part_info *)realloc(partition,nparts*sizeof(part_info));
  1253. partition[p] = pi;
  1254. }
  1255. }
  1256. }
  1257. free(newblkio);
  1258. free(oldblkio);
  1259. newblkio = (blkio_info *)calloc(sizeof(blkio_info),nparts);
  1260. oldblkio = (blkio_info* )calloc(sizeof(blkio_info),nparts);
  1261. }
  1262. rewind(diskfp);
  1263. // could skip lines we know aren't significant here
  1264. while (fgets(ln, sizeof(ln), diskfp)) {
  1265. blkio_info blkio;
  1266. unsigned items = sscanf(ln, "%4d %4d %*s %u %u %llu %u %u %u %llu %u %*u %u %u",
  1267. &pi.major, &pi.minor,
  1268. &blkio.rd_ios, &blkio.rd_merges,
  1269. &blkio.rd_sectors, &blkio.rd_ticks,
  1270. &blkio.wr_ios, &blkio.wr_merges,
  1271. &blkio.wr_sectors, &blkio.wr_ticks,
  1272. &blkio.ticks, &blkio.aveq);
  1273. if (items == 6) {
  1274. // hopefully not this branch!
  1275. blkio.rd_sectors = blkio.rd_merges;
  1276. blkio.wr_sectors = blkio.rd_ticks;
  1277. blkio.rd_ios = 0;
  1278. blkio.rd_merges = 0;
  1279. blkio.rd_ticks = 0;
  1280. blkio.wr_ios = 0;
  1281. blkio.wr_merges = 0;
  1282. blkio.wr_ticks = 0;
  1283. blkio.ticks = 0;
  1284. blkio.aveq = 0;
  1285. items = 12;
  1286. }
  1287. if (items == 12) {
  1288. for (unsigned p = 0; p < nparts; p++) {
  1289. if (partition[p].major == pi.major && partition[p].minor == pi.minor) {
  1290. newblkio[p] = blkio;
  1291. break;
  1292. }
  1293. }
  1294. }
  1295. }
  1296. fclose(diskfp);
  1297. return true;
  1298. }
  1299. bool getNetInfo()
  1300. {
  1301. FILE *netfp = fopen("/proc/net/dev", "r");
  1302. if (!netfp)
  1303. return false;
  1304. char ln[512];
  1305. fgets(ln, sizeof(ln), netfp);
  1306. fgets(ln, sizeof(ln), netfp);
  1307. unsigned txskip = 2;
  1308. bool hasbyt = false;
  1309. if (strstr(ln,"compressed")) {
  1310. txskip = 4;
  1311. hasbyt = true;
  1312. }
  1313. else if (strstr(ln,"bytes"))
  1314. hasbyt = true;
  1315. while (fgets(ln, sizeof(ln), netfp)) {
  1316. const char *s = ln;
  1317. skipSp(s);
  1318. if (strncmp(s, "eth0:", 5)==0) { // may want eth1 at some point!
  1319. s+=5;
  1320. if (hasbyt) {
  1321. newnet.rxbytes = readDecNum(s);
  1322. skipSp(s);
  1323. }
  1324. else
  1325. newnet.rxbytes = 0;
  1326. newnet.rxpackets = readDecNum(s);
  1327. skipSp(s);
  1328. newnet.rxerrors = readDecNum(s);
  1329. skipSp(s);
  1330. newnet.rxdrops = readDecNum(s);
  1331. skipSp(s);
  1332. while (txskip--) {
  1333. readDecNum(s);
  1334. skipSp(s);
  1335. }
  1336. if (hasbyt) {
  1337. newnet.txbytes = readDecNum(s);
  1338. skipSp(s);
  1339. }
  1340. else
  1341. newnet.txbytes = 0;
  1342. newnet.txpackets = readDecNum(s);
  1343. skipSp(s);
  1344. newnet.txerrors = readDecNum(s);
  1345. skipSp(s);
  1346. newnet.txdrops = readDecNum(s);
  1347. break;
  1348. }
  1349. }
  1350. fclose(netfp);
  1351. return true;
  1352. }
  1353. size32_t getKLog(const char *&data)
  1354. {
  1355. #ifdef __linux__
  1356. if (kbufmax) {
  1357. loop {
  1358. char *newkbuf = (char *)malloc(kbufmax);
  1359. if (!newkbuf)
  1360. break; // OOM - abort logging
  1361. size32_t newkbufsz = klogctl(3,newkbuf,kbufmax);
  1362. if ((int)newkbufsz<0) {
  1363. ERRLOG("klogctl error %d",errno);
  1364. free(newkbuf);
  1365. data = NULL;
  1366. return 0;
  1367. }
  1368. if (newkbufsz<kbufmax) {
  1369. unsigned short crc = chksum16(newkbuf,newkbufsz);
  1370. if (kbuf) {
  1371. if (crc!=kbufcrc) {
  1372. unsigned ofs = 0;
  1373. if ((newkbufsz>=kbufsz)) {
  1374. for (unsigned i=0;i+3<kbufsz;i++) { // not very quick!
  1375. if (memcmp(kbuf+i,newkbuf,kbufsz-i)==0) {
  1376. ofs = kbufsz-i;
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. size32_t ret = newkbufsz-ofs;
  1382. if (ret>3) {
  1383. kbufcrc = crc;
  1384. free(kbuf);
  1385. kbuf = newkbuf;
  1386. kbufsz = newkbufsz;
  1387. data = kbuf+ofs;
  1388. return ret;
  1389. }
  1390. }
  1391. }
  1392. else { // first time {
  1393. kbuf = newkbuf;
  1394. newkbuf = NULL;
  1395. kbufsz = newkbufsz;
  1396. }
  1397. free(newkbuf);
  1398. data = NULL;
  1399. return 0;
  1400. }
  1401. if (kbufmax>0x100000) {
  1402. // don't believe!
  1403. ERRLOG("klogctl buffer too big!");
  1404. free(newkbuf);
  1405. break;
  1406. }
  1407. kbufmax += 0x1000;
  1408. free(newkbuf);
  1409. }
  1410. kbufmax = 0;
  1411. kbufsz = 0;
  1412. free(kbuf);
  1413. kbuf = NULL;
  1414. }
  1415. #endif
  1416. #if defined (__FreeBSD__) || defined (__APPLE__)
  1417. UNIMPLEMENTED;
  1418. #endif
  1419. data = NULL;
  1420. return 0;
  1421. }
  1422. inline double perSec(double v,double deltams)
  1423. {
  1424. return 1000.0*v/deltams;
  1425. }
  1426. public:
  1427. unsigned getCPU()
  1428. {
  1429. if (!getNextCPU())
  1430. return (unsigned)-1;
  1431. if (totalcpu==0)
  1432. return 0;
  1433. unsigned ret = (unsigned)((totalcpu-cpu.idle)*100/totalcpu);
  1434. if (ret>100)
  1435. ret = 100;
  1436. return ret;
  1437. }
  1438. CExtendedStats(bool printklog)
  1439. {
  1440. partition = (part_info *)malloc(sizeof(part_info));
  1441. nparts = 0;
  1442. newblkio = NULL;
  1443. oldblkio = NULL;
  1444. first = true;
  1445. ncpu = 0;
  1446. kbuf = NULL;
  1447. kbufsz = 0;
  1448. kbufcrc = 0;
  1449. memset(&oldcpu, 0, sizeof(oldcpu));
  1450. memset(&newcpu, 0, sizeof(newcpu));
  1451. memset(&cpu, 0, sizeof(cpu));
  1452. totalcpu = 0;
  1453. numcpu = 0;
  1454. memset(&oldnet, 0, sizeof(oldnet));
  1455. memset(&newnet, 0, sizeof(newnet));
  1456. ndisks = 0;
  1457. if (printklog)
  1458. kbufmax = 0x1000;
  1459. else
  1460. kbufmax = 0;
  1461. }
  1462. ~CExtendedStats()
  1463. {
  1464. free(partition);
  1465. free(kbuf);
  1466. }
  1467. bool getLine(StringBuffer &out)
  1468. {
  1469. blkio_info *t = oldblkio;
  1470. oldblkio = newblkio;
  1471. newblkio = t;
  1472. oldnet = newnet;
  1473. #ifdef USE_OLD_PU
  1474. if (!getNextCPU())
  1475. return false; // required
  1476. #endif
  1477. bool gotdisk = getDiskInfo()&&nparts;
  1478. bool gotnet = getNetInfo();
  1479. if (first) {
  1480. first = false;
  1481. return false;
  1482. }
  1483. double deltams = ((double)totalcpu*1000) / ncpu / HZ;
  1484. if (deltams<10)
  1485. return false;
  1486. if (gotdisk) {
  1487. if (out.length()&&(out.charAt(out.length()-1)!=' '))
  1488. out.append(' ');
  1489. out.append("DSK: ");
  1490. for (unsigned p = 0; p < nparts; p++) {
  1491. unsigned rd_ios = newblkio[p].rd_ios - oldblkio[p].rd_ios;
  1492. __uint64 rd_sectors = newblkio[p].rd_sectors - oldblkio[p].rd_sectors;
  1493. unsigned wr_ios = newblkio[p].wr_ios - oldblkio[p].wr_ios;
  1494. __uint64 wr_sectors = newblkio[p].wr_sectors - oldblkio[p].wr_sectors;
  1495. unsigned ticks = newblkio[p].ticks - oldblkio[p].ticks;
  1496. unsigned busy = (unsigned)(100*ticks/deltams);
  1497. if (busy>100)
  1498. busy = 100;
  1499. out.appendf("[%s] r/s=%0.1f kr/s=%0.1f w/s=%0.1f kw/s=%0.1f bsy=%d",
  1500. partition[p].name,
  1501. perSec(rd_ios,deltams),
  1502. perSec(rd_sectors,deltams)/2.0,
  1503. perSec(wr_ios,deltams),
  1504. perSec(wr_sectors,deltams)/2.0,
  1505. busy);
  1506. out.append(' ');
  1507. }
  1508. }
  1509. if (gotnet) {
  1510. out.append("NIC: ");
  1511. __uint64 rxbytes = newnet.rxbytes-oldnet.rxbytes;
  1512. __uint64 rxpackets = newnet.rxpackets-oldnet.rxpackets;
  1513. __uint64 txbytes = newnet.txbytes-oldnet.txbytes;
  1514. __uint64 txpackets = newnet.txpackets-oldnet.txpackets;
  1515. out.appendf("rxp/s=%0.1f rxk/s=%0.1f txp/s=%0.1f txk/s=%0.1f",
  1516. perSec(rxpackets,deltams),
  1517. perSec(rxbytes/1024.0,deltams),
  1518. perSec(txpackets,deltams),
  1519. perSec(txbytes/1024.0,deltams));
  1520. out.append(' ');
  1521. }
  1522. if (totalcpu)
  1523. out.appendf("CPU: usr=%d sys=%d iow=%d idle=%d", (unsigned)(cpu.user*100/totalcpu), (unsigned)(cpu.system*100/totalcpu), (unsigned)(cpu.iowait*100/totalcpu), (unsigned)(cpu.idle*100/totalcpu));
  1524. return true;
  1525. }
  1526. #define KERN_EMERG "<0>" // system is unusable
  1527. #define KERN_ALERT "<1>" // action must be taken immediately
  1528. #define KERN_CRIT "<2>" // critical conditions
  1529. #define KERN_ERR "<3>" // error conditions
  1530. #define KERN_WARNING "<4>" // warning conditions
  1531. #define KERN_NOTICE "<5>" // normal but significant condition
  1532. #define KERN_INFO "<6>" // informational
  1533. #define KERN_DEBUG "<7>" // debug-level messages
  1534. #define KMSGTEST(S) if (memcmp(p,S,3)==0) ln.append(#S)
  1535. void printKLog()
  1536. {
  1537. const char *p;
  1538. size32_t sz = getKLog(p);
  1539. StringBuffer ln;
  1540. const char *e = p+sz;
  1541. while (p!=e) {
  1542. if (*p=='<') {
  1543. ln.clear();
  1544. KMSGTEST(KERN_EMERG);
  1545. else KMSGTEST(KERN_ALERT);
  1546. else KMSGTEST(KERN_CRIT);
  1547. else KMSGTEST(KERN_ERR);
  1548. else KMSGTEST(KERN_WARNING);
  1549. else KMSGTEST(KERN_NOTICE);
  1550. else KMSGTEST(KERN_INFO);
  1551. else KMSGTEST(KERN_DEBUG);
  1552. else {
  1553. ln.append("KERN_UNKNOWN");
  1554. p -= 3;
  1555. }
  1556. p += 3;
  1557. ln.append(": ");
  1558. while ((p!=e)&&(*p!='\n'))
  1559. ln.append(*(p++));
  1560. PROGLOG("%s",ln.str());
  1561. }
  1562. while ((p!=e)&&(*p!='\n'))
  1563. p++;
  1564. if (p!=e)
  1565. p++;
  1566. }
  1567. }
  1568. };
  1569. #endif
  1570. static class CMemoryUsageReporter: public Thread
  1571. {
  1572. bool term;
  1573. unsigned interval;
  1574. Semaphore sem;
  1575. PerfMonMode traceMode;
  1576. IPerfMonHook * hook;
  1577. unsigned latestCPU;
  1578. double dbIdleTime;
  1579. double dbSystemTime;
  1580. #ifdef _WIN32
  1581. PROCNTQSI NtQuerySystemInformation;
  1582. PROCNTQIP NtQueryInformationProcess;
  1583. PROCNTGST pGetSystemTimes;
  1584. SYSTEM_BASIC_INFORMATION SysBaseInfo;
  1585. LONG status;
  1586. LARGE_INTEGER liOldIdleTime;
  1587. LARGE_INTEGER liOldSystemTime;
  1588. #else
  1589. double OldIdleTime;
  1590. double OldSystemTime;
  1591. CProcessMonitor procmon;
  1592. CExtendedStats extstats;
  1593. #endif
  1594. StringBuffer primaryfs;
  1595. StringBuffer secondaryfs;
  1596. CriticalSection sect; // for getSystemTraceInfo
  1597. public:
  1598. CMemoryUsageReporter(unsigned _interval, PerfMonMode _traceMode, IPerfMonHook * _hook, bool printklog)
  1599. : Thread("CMemoryUsageReporter"), traceMode(_traceMode)
  1600. #ifndef _WIN32
  1601. , extstats(printklog)
  1602. #endif
  1603. {
  1604. interval = _interval;
  1605. hook = _hook;
  1606. term = false;
  1607. latestCPU = 0;
  1608. #ifdef _WIN32
  1609. memset(&liOldIdleTime,0,sizeof(liOldIdleTime));
  1610. memset(&liOldSystemTime,0,sizeof(liOldSystemTime));
  1611. NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
  1612. GetModuleHandle("ntdll"),
  1613. "NtQuerySystemInformation"
  1614. );
  1615. NtQueryInformationProcess = (PROCNTQIP)GetProcAddress(
  1616. GetModuleHandle("ntdll"),
  1617. "NtQueryInformationProcess"
  1618. );
  1619. // GetSystemTimes not available on earlier versions of Windows - NtQuerySystemInformation not consistent on later ones. So use GetSystemTimes if available
  1620. pGetSystemTimes = (PROCNTGST)GetProcAddress(
  1621. GetModuleHandle("kernel32"),
  1622. "GetSystemTimes"
  1623. );
  1624. NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
  1625. dbIdleTime = 0;
  1626. primaryfs.append("C:");
  1627. #else
  1628. FILE* procfp;
  1629. procfp = fopen("/proc/uptime", "r");
  1630. if (procfp) {
  1631. fscanf(procfp, "%lf %lf\n", &OldSystemTime, &OldIdleTime);
  1632. fclose(procfp);
  1633. }
  1634. else
  1635. OldSystemTime = 0;
  1636. primaryfs.append("/");
  1637. #endif
  1638. }
  1639. void setPrimaryFileSystem(char const * _primaryfs)
  1640. {
  1641. primaryfs.clear();
  1642. if(_primaryfs)
  1643. primaryfs.append(_primaryfs);
  1644. }
  1645. void setSecondaryFileSystem(char const * _secondaryfs)
  1646. {
  1647. secondaryfs.clear();
  1648. if(_secondaryfs)
  1649. secondaryfs.append(_secondaryfs);
  1650. }
  1651. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  1652. {
  1653. CriticalBlock block(sect);
  1654. #ifdef _WIN32
  1655. if (pGetSystemTimes) {
  1656. LARGE_INTEGER idle, kernel, user;
  1657. pGetSystemTimes(&idle, &kernel, &user);
  1658. // note - kernel time seems to include idle time
  1659. if(liOldIdleTime.QuadPart != 0) {
  1660. // CurrentValue = NewValue - OldValue
  1661. dbIdleTime = Li2Double(idle) - Li2Double(liOldIdleTime);
  1662. dbSystemTime = (Li2Double(kernel) + Li2Double(user)) - Li2Double(liOldSystemTime);
  1663. // CurrentCpuIdle = IdleTime / SystemTime
  1664. dbIdleTime = dbIdleTime / dbSystemTime;
  1665. // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
  1666. latestCPU = (unsigned) (100.0 - dbIdleTime * 100.0 + 0.5);
  1667. }
  1668. liOldIdleTime = idle;
  1669. liOldSystemTime.QuadPart = user.QuadPart + kernel.QuadPart;
  1670. } else {
  1671. SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
  1672. SYSTEM_TIME_INFORMATION SysTimeInfo;
  1673. NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
  1674. NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
  1675. if(liOldIdleTime.QuadPart != 0) {
  1676. // CurrentValue = NewValue - OldValue
  1677. dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
  1678. dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
  1679. // CurrentCpuIdle = IdleTime / SystemTime
  1680. dbIdleTime = dbIdleTime / dbSystemTime;
  1681. // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
  1682. latestCPU = (unsigned) (100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5);
  1683. }
  1684. liOldIdleTime = SysPerfInfo.liIdleTime;
  1685. liOldSystemTime = SysTimeInfo.liKeSystemTime;
  1686. }
  1687. MEMORYSTATUSEX memstatus;
  1688. memstatus.dwLength = sizeof(memstatus);
  1689. GlobalMemoryStatusEx(&memstatus);
  1690. DWORDLONG vmTotal = memstatus.ullTotalVirtual;
  1691. DWORDLONG vmAvail = memstatus.ullAvailVirtual;
  1692. DWORDLONG vmInUse = vmTotal - vmAvail;
  1693. DWORDLONG physTotal = memstatus.ullAvailPhys;
  1694. DWORDLONG physAvail = memstatus.ullTotalPhys;
  1695. DWORDLONG physInUse = physTotal - physAvail;
  1696. ULARGE_INTEGER diskAvailStruct;
  1697. ULARGE_INTEGER diskTotalStruct;
  1698. unsigned __int64 firstDriveTotal = 0;
  1699. unsigned __int64 firstDriveInUse = 0;
  1700. unsigned __int64 secondDriveTotal = 0;
  1701. unsigned __int64 secondDriveInUse = 0;
  1702. if(primaryfs.length())
  1703. {
  1704. diskAvailStruct.QuadPart = 0;
  1705. diskTotalStruct.QuadPart = 0;
  1706. GetDiskFreeSpaceEx(primaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  1707. firstDriveTotal = diskTotalStruct.QuadPart;
  1708. firstDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  1709. }
  1710. if(secondaryfs.length())
  1711. {
  1712. diskAvailStruct.QuadPart = 0;
  1713. diskTotalStruct.QuadPart = 0;
  1714. GetDiskFreeSpaceEx(secondaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  1715. secondDriveTotal = diskTotalStruct.QuadPart;
  1716. secondDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  1717. }
  1718. if(hook)
  1719. hook->processPerfStats(latestCPU, (unsigned)(vmInUse/1024), (unsigned)(vmTotal/1024), firstDriveInUse, firstDriveTotal, secondDriveInUse, secondDriveTotal, getThreadCount());
  1720. if(!mode)
  1721. return;
  1722. if(mode & PerfMonProcMem)
  1723. {
  1724. str.appendf("PU=%3d%%",latestCPU);
  1725. #if 0
  1726. VM_COUNTERS vmc;
  1727. DWORD dwSize = 0;
  1728. NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  1729. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmc.WorkingSetSize*100/(__int64)vmTotal));
  1730. #else
  1731. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmInUse*100/(__int64)vmTotal));
  1732. str.appendf(" PY=%3u%%",(unsigned)((__int64)physInUse*100/(__int64)physTotal));
  1733. if (hook)
  1734. hook->extraLogging(str);
  1735. #ifdef _USE_MALLOC_HOOK
  1736. if (totalMem)
  1737. str.appendf(" TM=%"I64F"d",totalMem);
  1738. #endif
  1739. #endif
  1740. }
  1741. if(mode & PerfMonPackets)
  1742. {
  1743. unsigned tx, rx;
  1744. if(getPacketStats(tx, rx))
  1745. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  1746. else
  1747. str.appendf(" ");
  1748. }
  1749. if(mode & PerfMonDiskUsage)
  1750. {
  1751. if(firstDriveTotal) str.appendf(" D1=%3u%%", (unsigned)(firstDriveInUse*100/firstDriveTotal));
  1752. if(secondDriveTotal) str.appendf(" D2=%3u%%", (unsigned)(secondDriveInUse*100/secondDriveTotal));
  1753. }
  1754. if(mode & PerfMonExtended)
  1755. {
  1756. __IO_COUNTERS ioc;
  1757. KERNEL_USER_TIMES kut;
  1758. POOLED_USAGE_AND_LIMITS put;
  1759. VM_COUNTERS vmc;
  1760. DWORD dwSize;
  1761. DWORD dwHandles;
  1762. dwSize = 0;
  1763. NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  1764. dwHandles = 0;
  1765. dwSize = 0;
  1766. NtQueryInformationProcess(GetCurrentProcess(), ProcessHandleCount, &dwHandles, sizeof(dwHandles), &dwSize);
  1767. dwSize = 0;
  1768. NtQueryInformationProcess(GetCurrentProcess(), ProcessIoCounters, &ioc, sizeof(ioc), &dwSize);
  1769. dwSize = 0;
  1770. NtQueryInformationProcess(GetCurrentProcess(), ProcessTimes, &kut, sizeof(kut), &dwSize);
  1771. dwSize = 0;
  1772. NtQueryInformationProcess(GetCurrentProcess(), ProcessPooledUsageAndLimits, &put, sizeof(put), &dwSize);
  1773. str.appendf(" WS=%10u ",vmc.WorkingSetSize);
  1774. str.appendf("PP=%10u ",put.PagedPoolUsage);
  1775. str.appendf("NP=%10u ",put.NonPagedPoolUsage);
  1776. str.appendf("HC=%5u ",dwHandles);
  1777. str.appendf("TC=%5u ",getThreadCount());
  1778. str.appendf("IR=%10u ",(unsigned)(ioc.ReadTransferCount/1024));
  1779. str.appendf("IW=%10u ",(unsigned)(ioc.WriteTransferCount/1024));
  1780. str.appendf("IO=%10u ",(unsigned)(ioc.OtherTransferCount/1024));
  1781. str.appendf("KT=%16"I64F"u ",kut.KernelTime);
  1782. str.appendf("UT=%16"I64F"u ",kut.UserTime);
  1783. }
  1784. #else
  1785. bool outofhandles = false;
  1786. #ifdef USE_OLD_PU
  1787. FILE* procfp = fopen("/proc/uptime", "r");
  1788. if (procfp) {
  1789. fscanf(procfp, "%lf %lf\n", &dbSystemTime, &dbIdleTime);
  1790. fclose(procfp);
  1791. outofhandles = false;
  1792. }
  1793. latestCPU = unsigned(100.0 - (dbIdleTime - OldIdleTime)*100.0/(dbSystemTime - OldSystemTime) + 0.5);
  1794. OldSystemTime = dbSystemTime;
  1795. OldIdleTime = dbIdleTime;
  1796. #else
  1797. latestCPU = extstats.getCPU();
  1798. if (latestCPU==(unsigned)-1) {
  1799. outofhandles = true;
  1800. latestCPU = 0;
  1801. }
  1802. #endif
  1803. unsigned __int64 primaryfsTotal = 0;
  1804. unsigned __int64 primaryfsInUse = 0;
  1805. unsigned __int64 secondaryfsTotal = 0;
  1806. unsigned __int64 secondaryfsInUse = 0;
  1807. if(primaryfs.length())
  1808. getDiskUsage(primaryfs.str(), primaryfsTotal, primaryfsInUse);
  1809. if(secondaryfs.length())
  1810. getDiskUsage(secondaryfs.str(), secondaryfsTotal, secondaryfsInUse);
  1811. if(!mode) return;
  1812. unsigned memused=0;
  1813. unsigned memtot=0;
  1814. if(mode & PerfMonProcMem)
  1815. {
  1816. if (!outofhandles)
  1817. str.appendf("PU=%3d%% ", latestCPU);
  1818. else
  1819. str.appendf("PU=OOH ");
  1820. getMemStats(str,memused,memtot);
  1821. if (hook)
  1822. hook->extraLogging(str);
  1823. procmon.printBusy(latestCPU,str);
  1824. }
  1825. if (hook) {
  1826. if (!memtot) {
  1827. unsigned mu;
  1828. unsigned ma;
  1829. unsigned mt;
  1830. unsigned st;
  1831. unsigned su;
  1832. getMemUsage(mu,ma,mt,st,su);
  1833. memused = mu+su;
  1834. memtot = mt+st;
  1835. }
  1836. hook->processPerfStats(latestCPU, memused, memtot, primaryfsInUse, primaryfsTotal, secondaryfsInUse, secondaryfsTotal, getThreadCount());
  1837. }
  1838. if(mode & PerfMonPackets)
  1839. {
  1840. unsigned tx, rx;
  1841. if(getPacketStats(tx, rx))
  1842. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  1843. else
  1844. str.appendf(" ");
  1845. }
  1846. if(mode & PerfMonDiskUsage)
  1847. {
  1848. if(primaryfsTotal) str.appendf(" D1=%3u%%", (unsigned)(primaryfsInUse*100/primaryfsTotal));
  1849. if(secondaryfsTotal) str.appendf(" D2=%3u%%", (unsigned)(secondaryfsInUse*100/secondaryfsTotal));
  1850. }
  1851. if(mode & PerfMonExtended)
  1852. {
  1853. extstats.getLine(str);
  1854. }
  1855. #endif
  1856. }
  1857. #define NAMEDCOUNTPERIOD 60*30
  1858. int run()
  1859. {
  1860. StringBuffer str;
  1861. getSystemTraceInfo(str, traceMode&~PerfMonExtended); // initializes the values so that first one we print is meaningful rather than always saying PU=0%
  1862. CTimeMon tm(NAMEDCOUNTPERIOD*1000);
  1863. while (!term) {
  1864. if (sem.wait(interval))
  1865. break;
  1866. str.clear();
  1867. getSystemTraceInfo(str, traceMode&~PerfMonExtended);
  1868. #ifdef NAMEDCOUNTS
  1869. if (tm.timedout())
  1870. {
  1871. dumpNamedCounts(str.newline());
  1872. tm.reset(NAMEDCOUNTPERIOD*1000);
  1873. }
  1874. #endif
  1875. if(traceMode&&str.length()) {
  1876. LOG(MCdebugInfo, unknownJob, "SYS: %s", str.str());
  1877. #ifndef _WIN32
  1878. if (traceMode&PerfMonExtended) {
  1879. if (extstats.getLine(str.clear()))
  1880. LOG(MCdebugInfo, unknownJob, "%s", str.str());
  1881. extstats.printKLog();
  1882. }
  1883. #endif
  1884. }
  1885. }
  1886. return 0;
  1887. }
  1888. void stop()
  1889. {
  1890. term = true;
  1891. sem.signal();
  1892. join();
  1893. }
  1894. unsigned queryLatestCPU() const
  1895. {
  1896. return latestCPU;
  1897. }
  1898. } *MemoryUsageReporter=NULL;
  1899. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  1900. {
  1901. if (!MemoryUsageReporter)
  1902. MemoryUsageReporter = new CMemoryUsageReporter(1000, mode, 0, false);
  1903. MemoryUsageReporter->getSystemTraceInfo(str, mode);
  1904. }
  1905. void startPerformanceMonitor(unsigned interval, PerfMonMode traceMode, IPerfMonHook * hook)
  1906. {
  1907. stopPerformanceMonitor();
  1908. if (!MemoryUsageReporter) {
  1909. MemoryUsageReporter = new CMemoryUsageReporter(interval, traceMode, hook, (traceMode&PerfMonExtended)!=0);
  1910. MemoryUsageReporter->start();
  1911. }
  1912. }
  1913. void stopPerformanceMonitor()
  1914. {
  1915. if (MemoryUsageReporter) {
  1916. MemoryUsageReporter->stop();
  1917. delete MemoryUsageReporter;
  1918. MemoryUsageReporter = NULL;
  1919. }
  1920. }
  1921. void setPerformanceMonitorPrimaryFileSystem(char const * fs)
  1922. {
  1923. if(MemoryUsageReporter)
  1924. MemoryUsageReporter->setPrimaryFileSystem(fs);
  1925. }
  1926. void setPerformanceMonitorSecondaryFileSystem(char const * fs)
  1927. {
  1928. if(MemoryUsageReporter)
  1929. MemoryUsageReporter->setSecondaryFileSystem(fs);
  1930. }
  1931. unsigned getLatestCPUUsage()
  1932. {
  1933. if (MemoryUsageReporter)
  1934. return MemoryUsageReporter->queryLatestCPU();
  1935. else
  1936. return 0;
  1937. }
  1938. void getHardwareInfo(HardwareInfo &hdwInfo, const char *primDiskPath, const char *secDiskPath)
  1939. {
  1940. memset(&hdwInfo, 0, sizeof(HardwareInfo));
  1941. getCpuInfo(hdwInfo.numCPUs, hdwInfo.CPUSpeed);
  1942. #ifdef _WIN32
  1943. MEMORYSTATUS memstatus;
  1944. GlobalMemoryStatus(&memstatus);
  1945. hdwInfo.totalMemory = memstatus.dwTotalPhys / (1024*1024); // in MB
  1946. ULARGE_INTEGER diskAvailStruct;
  1947. ULARGE_INTEGER diskTotalStruct;
  1948. diskTotalStruct.QuadPart = 0;
  1949. GetDiskFreeSpaceEx(primDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  1950. hdwInfo.primDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  1951. hdwInfo.primFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  1952. if (secDiskPath)
  1953. {
  1954. diskTotalStruct.QuadPart = 0;
  1955. GetDiskFreeSpaceEx(secDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  1956. hdwInfo.secDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  1957. hdwInfo.secFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  1958. }
  1959. // MORE: Find win32 call for NIC speed
  1960. #else // linux
  1961. unsigned memUsed, memActive, memSwap, memSwapUsed;
  1962. unsigned __int64 diskSize;
  1963. unsigned __int64 diskUsed;
  1964. getMemUsage(memUsed, memActive, hdwInfo.totalMemory, memSwap, memSwapUsed);
  1965. hdwInfo.totalMemory /= 1024; // in MB
  1966. getDiskUsage(primDiskPath, diskSize, diskUsed);
  1967. hdwInfo.primDiskSize = diskSize / (1024*1024*1024); // in GB
  1968. hdwInfo.primFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  1969. if (secDiskPath)
  1970. {
  1971. getDiskUsage(secDiskPath, diskSize, diskUsed);
  1972. hdwInfo.secDiskSize = diskSize / (1024*1024*1024); // in GB
  1973. hdwInfo.secFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  1974. }
  1975. // MORE: Find linux call for NIC speed -- mii-tool does not seem to work on our roxie clusters?
  1976. #endif
  1977. }
  1978. //===========================================================================
  1979. enum SegTypes {
  1980. segtype_free, //
  1981. segtype_heap, // rw-p named [heap]
  1982. segtype_data, // rw-p unnamed
  1983. segtype_guard, // ---p unnamed/named
  1984. segtype_stack, // rwxp
  1985. segtype_qlibcode, // r-xp named */lib200
  1986. segtype_qlibdata, // rw-p named */lib200
  1987. segtype_libcode, // r-xp named *
  1988. segtype_libdata, // rw-p named *
  1989. segtype_pstack, // rwxp named [stack]
  1990. segtype_const, // r--p
  1991. segtype_null // must be last
  1992. };
  1993. struct SegTypeRec
  1994. {
  1995. offset_t total;
  1996. unsigned n;
  1997. offset_t largest;
  1998. };
  1999. const char *PROCMAPHEADER =
  2000. "FREE,NFREE,MAXFREE,HEAP,STACK,NSTACKS,DATA,NDATA,MAXDATA,LIBDATA,QUERYDATA,MAXQUERYDATA,LIBCODE,QUERYCODE,MAXQLIBCODE";
  2001. class CProcReader
  2002. {
  2003. // Cant use JFile for /proc filesystem as seek doesn't work
  2004. public:
  2005. char ln [512];
  2006. FILE *file;
  2007. const char *buf;
  2008. size32_t bufsize;
  2009. CProcReader(const char *filename,const void *_buf,size32_t _buflen)
  2010. {
  2011. buf = (const char *)_buf;
  2012. bufsize = buf?_buflen:0;
  2013. file = buf?NULL:fopen(filename,"r");
  2014. }
  2015. ~CProcReader()
  2016. {
  2017. if (file)
  2018. fclose(file);
  2019. }
  2020. bool nextln()
  2021. {
  2022. if (buf) {
  2023. if (bufsize&&*buf) {
  2024. unsigned i = 0;
  2025. while (bufsize&&(i<sizeof(ln)-1)&&*buf&&(*buf!=10)&&(*buf!=13)) {
  2026. ln[i++] = *(buf++);
  2027. bufsize--;
  2028. }
  2029. ln[i] = 0;
  2030. while (bufsize&&*buf&&((*buf==10)||(*buf==13))) {
  2031. buf++;
  2032. bufsize--;
  2033. }
  2034. return true;
  2035. }
  2036. }
  2037. else if (file&&fgets (ln, sizeof(ln), file)) {
  2038. unsigned i = strlen(ln);
  2039. while (i&&((ln[i-1]==10)||(ln[i-1]==13)))
  2040. i--;
  2041. ln[i] = 0;
  2042. return true;
  2043. }
  2044. if (file) {
  2045. fclose(file);
  2046. file = NULL;
  2047. }
  2048. return false;
  2049. }
  2050. void dump(bool useprintf)
  2051. {
  2052. while (nextln()) {
  2053. if (useprintf)
  2054. printf("%s\n",ln);
  2055. else
  2056. PROGLOG("%s",ln);
  2057. }
  2058. }
  2059. };
  2060. void printProcMap(const char *fn, bool printbody, bool printsummary, StringBuffer *lnout, MemoryBuffer *mb, bool useprintf)
  2061. {
  2062. CProcReader reader(fn,mb?mb->toByteArray():NULL,mb?mb->length():0);
  2063. unsigned i;
  2064. SegTypeRec recs[segtype_null];
  2065. memset(&recs,0,sizeof(recs));
  2066. offset_t last=0;
  2067. if (printbody) {
  2068. if (useprintf)
  2069. printf("START,END,SIZE,OFFSET,PERMS,PATH\n");
  2070. else
  2071. PROGLOG("START,END,SIZE,OFFSET,PERMS,PATH");
  2072. }
  2073. while (reader.nextln()) {
  2074. const char *ln = reader.ln;
  2075. unsigned n=0;
  2076. if (*ln) {
  2077. offset_t start = readHexNum(ln);
  2078. if (last&&(last!=start)) {
  2079. recs[segtype_free].n++;
  2080. offset_t ssz = start-last;
  2081. recs[segtype_free].total += ssz;
  2082. if (ssz>recs[segtype_free].largest)
  2083. recs[segtype_free].largest = ssz;
  2084. }
  2085. if (*ln=='-') {
  2086. ln++;
  2087. offset_t end = readHexNum(ln);
  2088. char perms[5];
  2089. skipSp(ln);
  2090. for (i=0;i<4;)
  2091. if (*ln)
  2092. perms[i++] = *(ln++);
  2093. perms[i] = 0;
  2094. skipSp(ln);
  2095. offset_t offset = readHexNum(ln);
  2096. skipSp(ln);
  2097. char dev[6];
  2098. for (i=0;i<5;)
  2099. if (*ln)
  2100. dev[i++] = *(ln++);
  2101. dev[i] = 0;
  2102. skipSp(ln);
  2103. unsigned inode = (unsigned)readDecNum(ln);
  2104. skipSp(ln);
  2105. const char *path = ln;
  2106. if (printbody) {
  2107. if (useprintf)
  2108. printf("%08"I64F"x,%08"I64F"x,%"I64F"d,%08"I64F"x,%s,%s\n",start,end,(offset_t)(end-start),offset,perms,path);
  2109. else
  2110. PROGLOG("%08"I64F"x,%08"I64F"x,%"I64F"d,%08"I64F"x,%s,%s",start,end,(offset_t)(end-start),offset,perms,path);
  2111. }
  2112. SegTypes t;
  2113. if (strcmp(perms,"---p")==0)
  2114. t = segtype_guard;
  2115. else if (strcmp(perms,"rwxp")==0) {
  2116. if (memicmp(ln,"[stack]",7)==0)
  2117. t = segtype_pstack;
  2118. else
  2119. t = segtype_stack;
  2120. }
  2121. else if (strcmp(perms,"rw-p")==0) {
  2122. if (memicmp(ln,"[heap]",6)==0)
  2123. t = segtype_heap;
  2124. else if (strstr(ln,"/libW200"))
  2125. t = segtype_qlibdata;
  2126. else if (*ln)
  2127. t = segtype_libdata;
  2128. else
  2129. t = segtype_data;
  2130. }
  2131. else if (strcmp(perms,"r-xp")==0) {
  2132. if (strstr(ln,"/libW200"))
  2133. t = segtype_qlibcode;
  2134. else if (*ln)
  2135. t = segtype_libcode;
  2136. }
  2137. else if (strcmp(perms,"r--p")==0)
  2138. t = segtype_const;
  2139. else {
  2140. ERRLOG("%s - unknown perms",perms);
  2141. continue;
  2142. }
  2143. recs[t].n++;
  2144. offset_t ssz = end-start;
  2145. recs[t].total += ssz;
  2146. if (ssz>recs[t].largest)
  2147. recs[t].largest = ssz;
  2148. n++;
  2149. last = end;
  2150. #ifndef __64BIT__
  2151. if ((end<0xffffffff)&&(end>=0xc0000000)) // rest is OS (32-bit only)
  2152. break;
  2153. #endif
  2154. }
  2155. }
  2156. }
  2157. if (printsummary||lnout) {
  2158. StringBuffer tln;
  2159. if (lnout==NULL)
  2160. lnout = &tln;
  2161. lnout->appendf("%"I64F"u," // total
  2162. "%u," // n
  2163. "%"I64F"u," // largest
  2164. "%"I64F"u," // total
  2165. "%"I64F"u," // total
  2166. "%u," // n
  2167. "%"I64F"u," // total
  2168. "%u," // n
  2169. "%"I64F"u," // largest
  2170. "%"I64F"u," // total
  2171. "%"I64F"u," // total
  2172. "%"I64F"u," // largest
  2173. "%"I64F"u," // total
  2174. "%"I64F"u," // total
  2175. "%"I64F"u" // largest
  2176. ,
  2177. recs[segtype_free].total,
  2178. recs[segtype_free].n,
  2179. recs[segtype_free].largest,
  2180. recs[segtype_heap].total,
  2181. recs[segtype_stack].total,
  2182. recs[segtype_stack].n,
  2183. recs[segtype_data].total,
  2184. recs[segtype_data].n,
  2185. recs[segtype_data].largest,
  2186. recs[segtype_libdata].total,
  2187. recs[segtype_qlibdata].total,
  2188. recs[segtype_qlibdata].largest,
  2189. recs[segtype_libcode].total,
  2190. recs[segtype_qlibcode].total,
  2191. recs[segtype_qlibcode].largest
  2192. );
  2193. if (printsummary) {
  2194. if (useprintf)
  2195. printf("%s\n%s\n",PROCMAPHEADER,tln.str());
  2196. else {
  2197. PROGLOG("%s",PROCMAPHEADER);
  2198. PROGLOG("%s",tln.str());
  2199. }
  2200. }
  2201. }
  2202. }
  2203. #ifdef _WIN32
  2204. // stubs
  2205. void PrintMemoryReport(bool full)
  2206. {
  2207. StringBuffer s;
  2208. getSystemTraceInfo(s,PerfMonProcMem);
  2209. PROGLOG("%s",s.str());
  2210. }
  2211. #else
  2212. void PrintMemoryReport(bool full)
  2213. {
  2214. // may be very close to oom so protect against re-entry
  2215. static int recurse=0;
  2216. if (recurse++==0) {
  2217. try {
  2218. printProcMap("/proc/self/maps",full,true,NULL,NULL,false);
  2219. }
  2220. catch (IException *e) {
  2221. e->Release();
  2222. }
  2223. catch (...) {
  2224. }
  2225. try {
  2226. PROGLOG("/proc/meminfo:");
  2227. CProcReader reader("/proc/meminfo",NULL,0);
  2228. reader.dump(false);
  2229. }
  2230. catch (IException *e) {
  2231. e->Release();
  2232. }
  2233. catch (...) {
  2234. }
  2235. try {
  2236. PROGLOG("/proc/self/status:");
  2237. CProcReader reader("/proc/self/status",NULL,0);
  2238. reader.dump(false);
  2239. }
  2240. catch (IException *e) {
  2241. e->Release();
  2242. }
  2243. catch (...) {
  2244. }
  2245. try {
  2246. StringBuffer s;
  2247. getSystemTraceInfo(s,PerfMonProcMem);
  2248. PROGLOG("%s",s.str());
  2249. PROGLOG("===============================================================");
  2250. }
  2251. catch (IException *e) {
  2252. e->Release();
  2253. }
  2254. catch (...) {
  2255. }
  2256. }
  2257. recurse--;
  2258. }
  2259. #endif
  2260. //===========================================================================
  2261. #ifdef LEAK_CHECK
  2262. #ifdef _WIN32
  2263. LeakChecker::LeakChecker(const char * _title) : title(_title)
  2264. {
  2265. _CrtMemCheckpoint(&oldMemState);
  2266. }
  2267. LeakChecker::~LeakChecker()
  2268. {
  2269. _CrtMemState newMemState, diffMemState;
  2270. _CrtMemCheckpoint(&newMemState);
  2271. if(_CrtMemDifference(&diffMemState, &oldMemState, &newMemState))
  2272. {
  2273. _RPT1(_CRT_WARN, "----- Memory leaks in '%s' -----\n", title);
  2274. _CrtMemDumpStatistics(&diffMemState);
  2275. _CrtMemDumpAllObjectsSince(&oldMemState);
  2276. _RPT0(_CRT_WARN, "----- End of leaks -----\n");
  2277. }
  2278. }
  2279. static char _logFile[255]; // used to hold last file name of log file for memory leak logging
  2280. static FILE *_logHandle = NULL;
  2281. _CRT_REPORT_HOOK oldReport;
  2282. static int MemoryLeakReportHook(int nRptType,char *szMsg,int *retVal)
  2283. {
  2284. if (szMsg && *szMsg)
  2285. {
  2286. if (_logHandle)
  2287. fprintf(_logHandle, szMsg);
  2288. if (*_logFile)
  2289. {
  2290. #if 1
  2291. // this works better in VS 2008 libraries (which fault in fopen)
  2292. int handle = _open(_logFile, O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);
  2293. _lseek(handle,0,SEEK_END);
  2294. _write(handle,szMsg,strlen(szMsg));
  2295. _close(handle);
  2296. #else
  2297. FILE *handle = fopen(_logFile, "a");
  2298. fprintf(handle, szMsg);
  2299. fclose(handle);
  2300. #endif
  2301. }
  2302. }
  2303. if (oldReport)
  2304. return oldReport(nRptType,szMsg,retVal);
  2305. else
  2306. return false;
  2307. }
  2308. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  2309. {
  2310. oldReport = _CrtSetReportHook(MemoryLeakReportHook);
  2311. return 1;
  2312. }
  2313. void logLeaks (const char *logFile)
  2314. {
  2315. if (logFile)
  2316. strncpy(_logFile, logFile, sizeof(_logFile));
  2317. else
  2318. _logFile[0] = 0;
  2319. }
  2320. void logLeaks (FILE *logHandle)
  2321. {
  2322. _logHandle = logHandle;
  2323. }
  2324. #else
  2325. #endif
  2326. #endif
  2327. #if !defined(USING_MPATROL) && defined(WIN32) && defined(_DEBUG)
  2328. void jlib_decl enableMemLeakChecking(bool enable)
  2329. {
  2330. int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  2331. if (enable)
  2332. tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
  2333. else
  2334. tmpFlag &= ~_CRTDBG_LEAK_CHECK_DF;
  2335. _CrtSetDbgFlag( tmpFlag );
  2336. }
  2337. #endif
  2338. #if defined(_WIN32) && defined(_DEBUG)
  2339. //#include <dbgint.h>
  2340. const unsigned maxUnique = 10000;
  2341. typedef struct _CrtMemBlockHeader
  2342. {
  2343. // Pointer to the block allocated just before this one:
  2344. struct _CrtMemBlockHeader *pBlockHeaderNext;
  2345. // Pointer to the block allocated just after this one:
  2346. struct _CrtMemBlockHeader *pBlockHeaderPrev;
  2347. char *szFileName; // File name
  2348. int nLine; // Line number
  2349. size_t nDataSize; // Size of user block
  2350. int nBlockUse; // Type of block
  2351. long lRequest; // Allocation number
  2352. } _CrtMemBlockHeader;
  2353. int compareFile(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2354. {
  2355. int compare;
  2356. if (left->szFileName && right->szFileName)
  2357. compare = strcmp(left->szFileName, right->szFileName);
  2358. else if (left->szFileName)
  2359. compare = -1;
  2360. else if (right->szFileName)
  2361. compare = +1;
  2362. else
  2363. compare = 0;
  2364. return compare;
  2365. }
  2366. int compareLocation(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2367. {
  2368. int compare = compareFile(left, right);
  2369. if (compare != 0)
  2370. return compare;
  2371. return left->nLine - right->nLine;
  2372. }
  2373. int compareBlocks(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2374. {
  2375. int compare = compareLocation(left, right);
  2376. if (compare != 0)
  2377. return compare;
  2378. return (int)(right->nDataSize - left->nDataSize);
  2379. }
  2380. void addLocation(unsigned & numUnique, _CrtMemBlockHeader * * locations, unsigned * counts, _CrtMemBlockHeader * search)
  2381. {
  2382. int left = 0;
  2383. int right = numUnique;
  2384. while (left < right)
  2385. {
  2386. int mid = (left + right) >> 1;
  2387. int cmp = compareBlocks(search, locations[mid]);
  2388. if (cmp < 0)
  2389. right = mid;
  2390. else if (cmp > 0)
  2391. left = mid+1;
  2392. else
  2393. {
  2394. //Save the lowest allocation number (so quicker to set a subsequent breakpoint)
  2395. if (search->lRequest < locations[mid]->lRequest)
  2396. locations[mid] = search;
  2397. counts[mid]++;
  2398. return;
  2399. }
  2400. }
  2401. if (numUnique != maxUnique)
  2402. {
  2403. assertex(left == right);
  2404. memmove(locations + left+1, locations + left, (numUnique-left)*sizeof(*locations));
  2405. memmove(counts + left+1, counts + left, (numUnique-left)*sizeof(*counts));
  2406. locations[left] = search;
  2407. counts[left] = 1;
  2408. numUnique++;
  2409. }
  2410. else
  2411. counts[maxUnique]++;
  2412. }
  2413. unsigned dumpMemory(unsigned lenTarget, char * target, unsigned lenSrc, const void * ptr)
  2414. {
  2415. if (lenSrc > lenTarget)
  2416. lenSrc = lenTarget;
  2417. const char * src = (const char *)ptr;
  2418. for (unsigned i=0; i < lenSrc; i++)
  2419. {
  2420. byte next = src[i];
  2421. target[i] = (next >= 0x20 && next <= 0x7e) ? next : '.';
  2422. }
  2423. return lenSrc;
  2424. }
  2425. void printAllocationSummary()
  2426. {
  2427. _CrtMemState state;
  2428. _CrtMemCheckpoint(&state);
  2429. unsigned numUnique = 0;
  2430. _CrtMemBlockHeader * locations[maxUnique+1];
  2431. unsigned counts[maxUnique+1];
  2432. _clear(counts);
  2433. unsigned __int64 totalFree = 0;
  2434. unsigned __int64 totalAllocated = 0;
  2435. //Walk the heap, keeping a tally of (filename, line, size)->count
  2436. _CrtMemBlockHeader * cur;
  2437. for (cur = state.pBlockHeader; cur; cur=cur->pBlockHeaderNext)
  2438. {
  2439. switch (cur->nBlockUse)
  2440. {
  2441. case _NORMAL_BLOCK:
  2442. {
  2443. addLocation(numUnique, locations, counts, cur);
  2444. totalAllocated += cur->nDataSize;
  2445. break;
  2446. }
  2447. case _FREE_BLOCK:
  2448. totalFree += cur->nDataSize;
  2449. break;
  2450. }
  2451. }
  2452. PROGLOG("%d Unique allocations by <filename>(line)@size", numUnique);
  2453. for (unsigned i2 = 0; i2 < numUnique; i2++)
  2454. {
  2455. _CrtMemBlockHeader * display = locations[i2];
  2456. //char tempBuffer[16];
  2457. //unsigned len = dumpMemory(sizeof(tempBuffer), tempBuffer, display->nDataSize,
  2458. PROGLOG("%s(%d) %d:%d {%ld} = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, display->nDataSize, counts[i2], display->lRequest, display->nDataSize * counts[i2]);
  2459. }
  2460. PROGLOG("Ungrouped: %d Total %"I64F"d", counts[maxUnique], totalAllocated);
  2461. PROGLOG("Summary by location");
  2462. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  2463. {
  2464. _CrtMemBlockHeader * display = locations[iSummary2];
  2465. unsigned count = counts[iSummary2];
  2466. unsigned __int64 size = count * display->nDataSize;
  2467. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  2468. {
  2469. _CrtMemBlockHeader * next = locations[iSummary2];
  2470. if (compareLocation(display, next) != 0)
  2471. break;
  2472. count += counts[iSummary2];
  2473. size += (counts[iSummary2] * next->nDataSize);
  2474. }
  2475. PROGLOG("%s(%d) %d = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, count, size);
  2476. }
  2477. PROGLOG("Summary by source");
  2478. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  2479. {
  2480. _CrtMemBlockHeader * display = locations[iSummary2];
  2481. unsigned count = counts[iSummary2];
  2482. unsigned __int64 size = count * display->nDataSize;
  2483. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  2484. {
  2485. _CrtMemBlockHeader * next = locations[iSummary2];
  2486. if (compareFile(display, next) != 0)
  2487. break;
  2488. count += counts[iSummary2];
  2489. size += (counts[iSummary2] * next->nDataSize);
  2490. }
  2491. PROGLOG("%s %d = %d", display->szFileName ? display->szFileName : "<unknown>", count, size);
  2492. }
  2493. }
  2494. #else
  2495. void printAllocationSummary()
  2496. {
  2497. }
  2498. #endif
  2499. #ifdef _USE_MALLOC_HOOK
  2500. // Note memory hooks should not be enabled for release (as not re-entrant in linux)
  2501. static CriticalSection hookSect;
  2502. #ifdef __linux__
  2503. static void *(*old_malloc_hook)(size_t, const void *);
  2504. static void (*old_free_hook)(void *, const void *);
  2505. static void *(*old_realloc_hook)(void *, size_t, const void *);
  2506. static void * jlib_malloc_hook (size_t size, const void *caller) ;
  2507. static void jlib_free_hook (void *ptr, const void *caller);
  2508. static void *jlib_realloc_hook (void *ptr, size_t size, const void *caller);
  2509. static int jlib_hooknest = 0; // this *shouldn't* really be needed
  2510. inline void restore_malloc_hooks()
  2511. {
  2512. if (--jlib_hooknest==0) {
  2513. __malloc_hook = old_malloc_hook;
  2514. __realloc_hook = old_realloc_hook;
  2515. __free_hook = old_free_hook;
  2516. }
  2517. }
  2518. inline void set_malloc_hooks()
  2519. {
  2520. assertex(jlib_hooknest==0);
  2521. old_malloc_hook = __malloc_hook;
  2522. old_free_hook = __free_hook;
  2523. old_realloc_hook = __realloc_hook;
  2524. __malloc_hook = jlib_malloc_hook;
  2525. __free_hook = jlib_free_hook;
  2526. __realloc_hook = jlib_realloc_hook;
  2527. jlib_hooknest = 1;
  2528. }
  2529. inline void reset_malloc_hooks()
  2530. {
  2531. if (jlib_hooknest++==0) {
  2532. __malloc_hook = jlib_malloc_hook;
  2533. __free_hook = jlib_free_hook;
  2534. __realloc_hook = jlib_realloc_hook;
  2535. }
  2536. }
  2537. inline void incCount(unsigned sz,bool inc)
  2538. {
  2539. int i=0;
  2540. size32_t s=sz;
  2541. while (s) {
  2542. s /= 2;
  2543. i++;
  2544. }
  2545. if (inc)
  2546. memArea[i] += sz;
  2547. else
  2548. memArea[i] -= sz;
  2549. }
  2550. void * jlib_malloc_hook (size_t size, const void *caller)
  2551. {
  2552. CriticalBlock block(hookSect);
  2553. void *res;
  2554. restore_malloc_hooks();
  2555. res = malloc (size);
  2556. if (res) {
  2557. size = malloc_usable_size(res);
  2558. totalMem+=size;
  2559. if (totalMem>hwmTotalMem) {
  2560. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  2561. PrintStackReport();
  2562. PROGLOG("TOTALMEM(%"I64F"d): malloc %u",totalMem,(unsigned)size);
  2563. }
  2564. hwmTotalMem = totalMem;
  2565. }
  2566. }
  2567. else
  2568. size = 0;
  2569. incCount(size,true);
  2570. if (size>REPORT_LARGER_BLOCK_THAN) {
  2571. PrintStackReport();
  2572. PROGLOG("LARGEALLOC(%u): %p",(unsigned)size,res);
  2573. }
  2574. reset_malloc_hooks();
  2575. return res;
  2576. }
  2577. void jlib_free_hook (void *ptr, const void *caller)
  2578. {
  2579. if (!ptr)
  2580. return;
  2581. CriticalBlock block(hookSect);
  2582. restore_malloc_hooks();
  2583. size32_t sz = malloc_usable_size(ptr);
  2584. free (ptr);
  2585. totalMem -= sz;
  2586. incCount(sz,false);
  2587. if (sz>REPORT_LARGER_BLOCK_THAN) {
  2588. PROGLOG("LARGEFREE(%u): %p",(unsigned)sz,ptr);
  2589. }
  2590. reset_malloc_hooks();
  2591. }
  2592. void *jlib_realloc_hook (void *ptr, size_t size, const void *caller)
  2593. {
  2594. CriticalBlock block(hookSect);
  2595. restore_malloc_hooks();
  2596. size32_t oldsz = ptr?malloc_usable_size(ptr):0;
  2597. void *res = realloc (ptr,size);
  2598. if (res) {
  2599. size = malloc_usable_size(res);
  2600. totalMem += size;
  2601. }
  2602. else
  2603. size = 0;
  2604. totalMem -= oldsz;
  2605. if (totalMem>hwmTotalMem) {
  2606. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  2607. PrintStackReport();
  2608. PROGLOG("TOTALMEM(%"I64F"d): realloc %u %u",totalMem,(unsigned)oldsz,(unsigned)size);
  2609. }
  2610. hwmTotalMem = totalMem;
  2611. }
  2612. incCount(size,true);
  2613. incCount(oldsz,false);
  2614. if ((size>REPORT_LARGER_BLOCK_THAN)||(oldsz>REPORT_LARGER_BLOCK_THAN)) {
  2615. if (size>oldsz) {
  2616. PrintStackReport();
  2617. PROGLOG("LARGEREALLOC_UP(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  2618. }
  2619. else {
  2620. PROGLOG("LARGEREALLOC_DN(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  2621. }
  2622. }
  2623. reset_malloc_hooks();
  2624. return res;
  2625. }
  2626. void jlib_decl jlib_init_hook()
  2627. {
  2628. set_malloc_hooks();
  2629. }
  2630. __int64 jlib_decl setAllocHook(bool on,bool clear)
  2631. {
  2632. CriticalBlock block(hookSect);
  2633. __int64 ret = totalMem;
  2634. if (clear) {
  2635. totalMem = 0;
  2636. hwmTotalMem = 0;
  2637. }
  2638. if (on) {
  2639. if (jlib_hooknest==0)
  2640. set_malloc_hooks();
  2641. }
  2642. else {
  2643. while (jlib_hooknest) {
  2644. restore_malloc_hooks();
  2645. //printf("Total = %d bytes\n",totalMem);
  2646. }
  2647. }
  2648. return ret;
  2649. }
  2650. unsigned jlib_decl setAllocHook(bool on)
  2651. {
  2652. // bwd compatible - should use above version in preference
  2653. CriticalBlock block(hookSect);
  2654. if (on) {
  2655. if (jlib_hooknest==0) {
  2656. set_malloc_hooks();
  2657. totalMem = 0;
  2658. hwmTotalMem = 0;
  2659. }
  2660. }
  2661. else {
  2662. while (jlib_hooknest) {
  2663. restore_malloc_hooks();
  2664. //printf("Total = %d bytes\n",totalMem);
  2665. }
  2666. }
  2667. return (unsigned)totalMem;
  2668. }
  2669. #else // windows
  2670. static _CRT_ALLOC_HOOK oldHook = NULL;
  2671. static int allocHook( int allocType, void *userData, size_t size, int nBlockUse,
  2672. long requestNumber, const unsigned char *filename, int lineNumber)
  2673. {
  2674. CriticalBlock block(hookSect);
  2675. if ( nBlockUse == _CRT_BLOCK ) // Ignore internal C runtime library allocations
  2676. return TRUE;
  2677. static bool recurse = false;
  2678. if (recurse)
  2679. return TRUE;
  2680. recurse = true;
  2681. char *operation[] = { "", "allocating", "re-allocating", "freeing" };
  2682. char *blockType[] = { "Free", "Normal", "CRT", "Ignore", "Client" };
  2683. switch (allocType) {
  2684. case _HOOK_REALLOC:
  2685. if (userData==NULL)
  2686. printf("no data on realloc\n");
  2687. else
  2688. totalMem-=_msize(userData);
  2689. // fall through
  2690. case _HOOK_ALLOC:
  2691. totalMem+=size;
  2692. break;
  2693. case _HOOK_FREE:
  2694. if (userData)
  2695. totalMem-=_msize(userData);
  2696. break;
  2697. }
  2698. // printf( "Memory operation in %s, line %d: %s a %d-byte '%s' block (#%ld)\n",
  2699. // filename, lineNumber, operation[allocType], size,
  2700. // blockType[nBlockUse], requestNumber );
  2701. recurse = false;
  2702. return TRUE; // Allow the memory operation to proceed
  2703. }
  2704. unsigned jlib_decl setAllocHook(bool on)
  2705. {
  2706. CriticalBlock block(hookSect);
  2707. if (on) {
  2708. if (oldHook==NULL) {
  2709. oldHook = _CrtSetAllocHook( allocHook );
  2710. totalMem = 0;
  2711. }
  2712. }
  2713. else {
  2714. if (oldHook!=NULL)
  2715. _CrtSetAllocHook( oldHook );
  2716. oldHook = NULL;
  2717. //printf("Total = %d bytes\n",totalMem);
  2718. }
  2719. return (unsigned)totalMem; // return unsigned for bwd compat
  2720. }
  2721. #endif
  2722. __int64 getTotalMem()
  2723. {
  2724. return totalMem;
  2725. }
  2726. #else // release
  2727. unsigned jlib_decl setAllocHook(bool on)
  2728. {
  2729. return 0;
  2730. }
  2731. __int64 jlib_decl setAllocHook(bool on,bool clear)
  2732. {
  2733. return 0;
  2734. }
  2735. __int64 jlib_decl getTotalMem()
  2736. {
  2737. return 0;
  2738. }
  2739. void jlib_decl jlib_init_hook()
  2740. {
  2741. }
  2742. class UserMetricMsgHandler : public CInterface, implements ILogMsgHandler, implements IUserMetric
  2743. {
  2744. mutable unsigned __int64 counter;
  2745. StringAttr metricName;
  2746. StringAttr regex;
  2747. Owned<ILogMsgFilter> regexFilter;
  2748. public:
  2749. virtual void Link(void) const { CInterface::Link(); }
  2750. virtual bool Release(void) const
  2751. {
  2752. if (CInterface::Release())
  2753. return true;
  2754. if (!IsShared())
  2755. {
  2756. queryLogMsgManager()->removeMonitor(const_cast<UserMetricMsgHandler *>(this)); // removeMonitor should take a const param really
  2757. }
  2758. return false;
  2759. }
  2760. UserMetricMsgHandler(const char *_name, const char *_regex) : metricName(_name), regex(_regex)
  2761. {
  2762. counter = 0;
  2763. regexFilter.setown(getRegexLogMsgFilter(regex, true));
  2764. queryLogMsgManager()->addMonitor(this, regexFilter);
  2765. }
  2766. // interface ILogMsgHandler
  2767. virtual void handleMessage(const LogMsg & msg) const { counter++; }
  2768. virtual bool needsPrep() const { return false; }
  2769. virtual void prep() {}
  2770. virtual unsigned queryMessageFields() const { return MSGFIELD_detail; }
  2771. virtual void setMessageFields(unsigned _fields = MSGFIELD_all) {}
  2772. virtual void addToPTree(IPropertyTree * parent) const {}
  2773. virtual int flush() { return 0; }
  2774. virtual char const *disable() { return 0; }
  2775. virtual void enable() {}
  2776. virtual bool getLogName(StringBuffer &name) const { return false; }
  2777. // interface IUserMetric
  2778. virtual unsigned __int64 queryCount() const { return counter; }
  2779. virtual const char *queryName() const { return metricName; }
  2780. virtual const char *queryMatchString() const { return regex; }
  2781. virtual void inc() { counter++; }
  2782. virtual void reset() { counter = 0; }
  2783. };
  2784. jlib_decl IUserMetric *createUserMetric(const char *name, const char *matchString)
  2785. {
  2786. return new UserMetricMsgHandler(name, matchString);
  2787. }
  2788. #endif