mon_lwtrace.cpp 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723
  1. #include "mon_lwtrace.h"
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <google/protobuf/text_format.h>
  5. #include <library/cpp/lwtrace/mon/analytics/all.h>
  6. #include <library/cpp/lwtrace/all.h>
  7. #include <library/cpp/monlib/service/pages/mon_page.h>
  8. #include <library/cpp/monlib/service/pages/resource_mon_page.h>
  9. #include <library/cpp/monlib/service/pages/templates.h>
  10. #include <library/cpp/resource/resource.h>
  11. #include <library/cpp/string_utils/base64/base64.h>
  12. #include <library/cpp/html/pcdata/pcdata.h>
  13. #include <util/string/escape.h>
  14. #include <util/system/condvar.h>
  15. #include <util/system/execpath.h>
  16. #include <util/system/hostname.h>
  17. using namespace NMonitoring;
  18. #define WWW_CHECK(cond, ...) \
  19. do { \
  20. if (!(cond)) { \
  21. ythrow yexception() << Sprintf(__VA_ARGS__); \
  22. } \
  23. } while (false) \
  24. /**/
  25. #define WWW_HTML_INNER(out) HTML(out) WITH_SCOPED(tmp, TScopedHtmlInner(out))
  26. #define WWW_HTML(out) out << NMonitoring::HTTPOKHTML; WWW_HTML_INNER(out)
  27. namespace NLwTraceMonPage {
  28. struct TTrackLogRefs {
  29. struct TItem {
  30. const TThread::TId ThreadId;
  31. const NLWTrace::TLogItem* Ptr;
  32. TItem()
  33. : ThreadId(0)
  34. , Ptr(nullptr)
  35. {}
  36. TItem(TThread::TId tid, const NLWTrace::TLogItem& ref)
  37. : ThreadId(tid)
  38. , Ptr(&ref)
  39. {}
  40. TItem(const TItem& o)
  41. : ThreadId(o.ThreadId)
  42. , Ptr(o.Ptr)
  43. {}
  44. operator const NLWTrace::TLogItem&() const { return *Ptr; }
  45. };
  46. using TItems = TVector<TItem>;
  47. TItems Items;
  48. TTrackLogRefs() {}
  49. TTrackLogRefs(const TTrackLogRefs& other)
  50. : Items(other.Items)
  51. {}
  52. void Clear()
  53. {
  54. Items.clear();
  55. }
  56. ui64 GetTimestampCycles() const
  57. {
  58. return Items.empty()? 0: Items.front().Ptr->GetTimestampCycles();
  59. }
  60. };
  61. //
  62. // Templates to treat both NLWTrace::TLogItem and NLWTrace::TTrackLog in the same way (e.g. in TLogQuery)
  63. //
  64. template <class TLog>
  65. struct TLogTraits {};
  66. template <>
  67. struct TLogTraits<NLWTrace::TLogItem> {
  68. using TLog = NLWTrace::TLogItem;
  69. using const_iterator = const NLWTrace::TLogItem*;
  70. using const_reverse_iterator = const NLWTrace::TLogItem*;
  71. static const_iterator begin(const TLog& log) { return &log; }
  72. static const_iterator end(const TLog& log) { return &log + 1; }
  73. static const_reverse_iterator rbegin(const TLog& log) { return &log; }
  74. static const_reverse_iterator rend(const TLog& log) { return &log + 1; }
  75. static bool empty(const TLog&) { return false; }
  76. static const NLWTrace::TLogItem& front(const TLog& log) { return log; }
  77. static const NLWTrace::TLogItem& back(const TLog& log) { return log; }
  78. };
  79. template <>
  80. struct TLogTraits<NLWTrace::TTrackLog> {
  81. using TLog = NLWTrace::TTrackLog;
  82. using const_iterator = NLWTrace::TTrackLog::TItems::const_iterator;
  83. using const_reverse_iterator = NLWTrace::TTrackLog::TItems::const_reverse_iterator;
  84. static const_iterator begin(const TLog& log) { return log.Items.begin(); }
  85. static const_iterator end(const TLog& log) { return log.Items.end(); }
  86. static const_reverse_iterator rbegin(const TLog& log) { return log.Items.rbegin(); }
  87. static const_reverse_iterator rend(const TLog& log) { return log.Items.rend(); }
  88. static bool empty(const TLog& log) { return log.Items.empty(); }
  89. static const NLWTrace::TLogItem& front(const TLog& log) { return log.Items.front(); }
  90. static const NLWTrace::TLogItem& back(const TLog& log) { return log.Items.back(); }
  91. };
  92. template <>
  93. struct TLogTraits<TTrackLogRefs> {
  94. using TLog = TTrackLogRefs;
  95. using const_iterator = TTrackLogRefs::TItems::const_iterator;
  96. using const_reverse_iterator = TTrackLogRefs::TItems::const_reverse_iterator;
  97. static const_iterator begin(const TLog& log) { return log.Items.begin(); }
  98. static const_iterator end(const TLog& log) { return log.Items.end(); }
  99. static const_reverse_iterator rbegin(const TLog& log) { return log.Items.rbegin(); }
  100. static const_reverse_iterator rend(const TLog& log) { return log.Items.rend(); }
  101. static bool empty(const TLog& log) { return log.Items.empty(); }
  102. static const NLWTrace::TLogItem& front(const TLog& log) { return log.Items.front(); }
  103. static const NLWTrace::TLogItem& back(const TLog& log) { return log.Items.back(); }
  104. };
  105. /*
  106. * Log Query Language:
  107. * Data expressions:
  108. * 1) myparam[0], myparam[-1] // the first and the last myparam in any probe/provider
  109. * 2) myparam // the first (the same as [0])
  110. * 3) PROVIDER..myparam // any probe with myparam in PROVIDER
  111. * 4) MyProbe._elapsedMs // Ms since track begin for the first MyProbe event
  112. * 5) PROVIDER.MyProbe._sliceUs // Us since previous event in track for the first PROVIDER.MyProbe event
  113. */
  114. struct TLogQuery {
  115. private:
  116. enum ESpecialParam {
  117. NotSpecial = 0,
  118. // The last '*' can be one of: Ms, Us, Ns, Min, Hours, (blank means seconds)
  119. // '*Time' can be one of: RTime (since cut ts for given dataset), NTime (negative time since now), Time (since machine start)
  120. TrackDuration = 1, // _track*
  121. TrackBeginTime = 2, // _begin*Time*
  122. TrackEndTime = 3, // _end*Time*
  123. ElapsedDuration = 4, // _elapsed*
  124. SliceDuration = 5, // _slice*
  125. ThreadTime = 6, // _thr*Time*
  126. };
  127. template <class TLog, class TTr = TLogTraits<TLog>>
  128. struct TExecuteQuery;
  129. template <class TLog, class TTr>
  130. friend struct TExecuteQuery;
  131. template <class TLog, class TTr>
  132. struct TExecuteQuery {
  133. const TLogQuery& Query;
  134. const TLog* Log = nullptr;
  135. bool Reversed;
  136. i64 Skip;
  137. const NLWTrace::TLogItem* Item = nullptr;
  138. typename TTr::const_iterator FwdIter;
  139. typename TTr::const_reverse_iterator RevIter;
  140. NLWTrace::TTypedParam Result;
  141. explicit TExecuteQuery(const TLogQuery& query, const TLog& log)
  142. : Query(query)
  143. , Log(&log)
  144. , Reversed(Query.Index < 0)
  145. , Skip(Reversed? -Query.Index - 1: Query.Index)
  146. , FwdIter()
  147. , RevIter()
  148. {}
  149. void ExecuteQuery()
  150. {
  151. if (!Reversed) {
  152. for (auto i = TTr::begin(*Log), e = TTr::end(*Log); i != e; ++i) {
  153. if (FwdIteration(i)) {
  154. return;
  155. }
  156. }
  157. } else {
  158. for (auto i = TTr::rbegin(*Log), e = TTr::rend(*Log); i != e; ++i) {
  159. if (RevIteration(i)) {
  160. return;
  161. }
  162. }
  163. }
  164. }
  165. bool FwdIteration(typename TTr::const_iterator it)
  166. {
  167. FwdIter = it;
  168. Item = &*it;
  169. return ProcessItem();
  170. }
  171. bool RevIteration(typename TTr::const_reverse_iterator it)
  172. {
  173. RevIter = it;
  174. Item = &*it;
  175. return ProcessItem();
  176. }
  177. bool ProcessItem()
  178. {
  179. if (Query.Provider && Query.Provider != Item->Probe->Event.GetProvider()) {
  180. return false;
  181. }
  182. if (Query.Probe && Query.Probe != Item->Probe->Event.Name) {
  183. return false;
  184. }
  185. switch (Query.SpecialParam) {
  186. case NotSpecial:
  187. if (Item->Probe->Event.Signature.FindParamIndex(Query.ParamName) != size_t(-1)) {
  188. break; // param found
  189. } else {
  190. return false; // param not found
  191. }
  192. case TrackDuration: Y_ABORT();
  193. case TrackBeginTime: Y_ABORT();
  194. case TrackEndTime: Y_ABORT();
  195. case ElapsedDuration: break;
  196. case SliceDuration: break;
  197. case ThreadTime: break;
  198. }
  199. if (Skip > 0) {
  200. Skip--;
  201. return false;
  202. }
  203. switch (Query.SpecialParam) {
  204. case NotSpecial:
  205. Result = NLWTrace::TTypedParam(Item->GetParam(Query.ParamName));
  206. return true;
  207. case TrackDuration: Y_ABORT();
  208. case TrackBeginTime: Y_ABORT();
  209. case TrackEndTime: Y_ABORT();
  210. case ElapsedDuration:
  211. Result = NLWTrace::TTypedParam(Query.Duration(
  212. Log->GetTimestampCycles(),
  213. Item->GetTimestampCycles()));
  214. return true;
  215. case SliceDuration:
  216. Result = NLWTrace::TTypedParam(Query.Duration(
  217. PrevOrSame().GetTimestampCycles(),
  218. Item->GetTimestampCycles()));
  219. return true;
  220. case ThreadTime:
  221. Result = NLWTrace::TTypedParam(Query.Instant(Item->GetTimestampCycles()));
  222. return true;
  223. }
  224. return true;
  225. }
  226. const NLWTrace::TLogItem& PrevOrSame() const
  227. {
  228. if (!Reversed) {
  229. auto i = FwdIter;
  230. if (i != TTr::begin(*Log)) {
  231. i--;
  232. }
  233. return *i;
  234. } else {
  235. auto j = RevIter + 1;
  236. if (j == TTr::rend(*Log)) {
  237. return *RevIter;
  238. }
  239. return *j;
  240. }
  241. }
  242. };
  243. TString Text;
  244. TString Provider;
  245. TString Probe;
  246. TString ParamName;
  247. ESpecialParam SpecialParam = NotSpecial;
  248. i64 Index = 0;
  249. double TimeUnitSec = 1.0;
  250. i64 ZeroTs = 0;
  251. i64 RTimeZeroTs = 0;
  252. i64 NTimeZeroTs = 0;
  253. public:
  254. TLogQuery() {}
  255. explicit TLogQuery(const TString& text)
  256. : Text(text)
  257. {
  258. try {
  259. if (!Text.empty()) {
  260. ParseQuery(Text);
  261. }
  262. } catch (...) {
  263. ythrow yexception()
  264. << CurrentExceptionMessage()
  265. << " while parsing track log query: "
  266. << Text;
  267. }
  268. }
  269. operator bool() const
  270. {
  271. return !Text.empty();
  272. }
  273. template <class TLog>
  274. NLWTrace::TTypedParam ExecuteQuery(const TLog& log) const
  275. {
  276. using TTr = TLogTraits<TLog>;
  277. WWW_CHECK(Text, "execute of empty log query");
  278. if (TTr::empty(log)) {
  279. return NLWTrace::TTypedParam();
  280. }
  281. if (SpecialParam == TrackDuration) {
  282. return Duration(
  283. log.GetTimestampCycles(),
  284. TTr::back(log).GetTimestampCycles());
  285. } else if (SpecialParam == TrackBeginTime) {
  286. return Instant(log.GetTimestampCycles());
  287. } else if (SpecialParam == TrackEndTime) {
  288. return Instant(TTr::back(log).GetTimestampCycles());
  289. }
  290. TExecuteQuery<TLog, TTr> exec(*this, log);
  291. exec.ExecuteQuery();
  292. return exec.Result;
  293. }
  294. private:
  295. NLWTrace::TTypedParam Duration(ui64 ts1, ui64 ts2) const
  296. {
  297. double sec = NHPTimer::GetSeconds(ts1 < ts2? ts2 - ts1: 0);
  298. return NLWTrace::TTypedParam(sec / TimeUnitSec);
  299. }
  300. NLWTrace::TTypedParam Instant(ui64 ts) const
  301. {
  302. double sec = NHPTimer::GetSeconds(i64(ts) - ZeroTs);
  303. return NLWTrace::TTypedParam(sec / TimeUnitSec);
  304. }
  305. void ParseQuery(const TString& s)
  306. {
  307. auto parts = SplitString(s, ".");
  308. WWW_CHECK(parts.size() <= 3, "too many name specifiers");
  309. ParseParamSelector(parts.back());
  310. if (parts.size() >= 2) {
  311. ParseProbeSelector(parts[parts.size() - 2]);
  312. }
  313. if (parts.size() >= 3) {
  314. ParseProviderSelector(parts[parts.size() - 3]);
  315. }
  316. }
  317. void ParseParamSelector(const TString& s)
  318. {
  319. size_t bracket = s.find('[');
  320. if (bracket == TString::npos) {
  321. ParseParamName(s);
  322. Index = 0;
  323. } else {
  324. ParseParamName(s.substr(0, bracket));
  325. size_t bracket2 = s.find(']', bracket);
  326. WWW_CHECK(bracket2 != TString::npos, "closing braket ']' is missing");
  327. Index = FromString<i64>(s.substr(bracket + 1, bracket2 - bracket - 1));
  328. }
  329. }
  330. void ParseParamName(const TString& s)
  331. {
  332. ParamName = s;
  333. TString paramName = s;
  334. const static TVector<std::pair<TString, ESpecialParam>> specials = {
  335. { "_track", TrackDuration },
  336. { "_begin", TrackBeginTime },
  337. { "_end", TrackEndTime },
  338. { "_elapsed", ElapsedDuration },
  339. { "_slice", SliceDuration },
  340. { "_thr", ThreadTime }
  341. };
  342. // Check for special params
  343. SpecialParam = NotSpecial;
  344. for (const auto& p : specials) {
  345. if (paramName.StartsWith(p.first)) {
  346. SpecialParam = p.second;
  347. paramName.erase(0, p.first.size());
  348. break;
  349. }
  350. }
  351. if (SpecialParam == NotSpecial) {
  352. return;
  353. }
  354. const static TVector<std::pair<TString, double>> timeUnits = {
  355. { "Ms", 1e-3 },
  356. { "Us", 1e-6 },
  357. { "Ns", 1e-9 },
  358. { "Min", 60.0 },
  359. { "Hours", 3600.0 }
  360. };
  361. // Parse units for special params
  362. TimeUnitSec = 1.0;
  363. for (const auto& p : timeUnits) {
  364. if (paramName.EndsWith(p.first)) {
  365. TimeUnitSec = p.second;
  366. paramName.erase(paramName.size() - p.first.size());
  367. break;
  368. }
  369. }
  370. if (SpecialParam == ThreadTime ||
  371. SpecialParam == TrackBeginTime ||
  372. SpecialParam == TrackEndTime)
  373. {
  374. // Parse time zero for special instant params
  375. const TVector<std::pair<TString, i64>> timeZeros = {
  376. { "RTime", RTimeZeroTs },
  377. { "NTime", NTimeZeroTs },
  378. { "Time", 0ll }
  379. };
  380. ZeroTs = -1;
  381. for (const auto& p : timeZeros) {
  382. if (paramName.EndsWith(p.first)) {
  383. ZeroTs = p.second;
  384. paramName.erase(paramName.size() - p.first.size());
  385. break;
  386. }
  387. }
  388. WWW_CHECK(ZeroTs != -1, "wrong special param name (postfix '*Time' required): %s", s.data());
  389. }
  390. WWW_CHECK(paramName.empty(), "wrong special param name: %s", s.data());
  391. }
  392. void ParseProbeSelector(const TString& s)
  393. {
  394. Probe = s;
  395. }
  396. void ParseProviderSelector(const TString& s)
  397. {
  398. Provider = s;
  399. }
  400. };
  401. using TVariants = TVector<std::pair<TString, TString>>;
  402. using TTags = TSet<TString>;
  403. TString GetProbeName(const NLWTrace::TProbe* probe, const char* sep = ".")
  404. {
  405. return TString(probe->Event.GetProvider()) + sep + probe->Event.Name;
  406. }
  407. struct TAdHocTraceConfig {
  408. NLWTrace::TQuery Cfg;
  409. TAdHocTraceConfig() {} // Invalid config
  410. TAdHocTraceConfig(ui16 logSize, ui64 logDurationUs, bool logShuttle)
  411. {
  412. auto block = Cfg.AddBlocks(); // Create one block to distinguish valid config
  413. if (logSize) {
  414. Cfg.SetPerThreadLogSize(logSize);
  415. }
  416. if (logDurationUs) {
  417. Cfg.SetLogDurationUs(logDurationUs);
  418. }
  419. if (logShuttle) {
  420. block->AddAction()->MutableRunLogShuttleAction();
  421. }
  422. }
  423. TAdHocTraceConfig(const TString& provider, const TString& probe, ui16 logSize = 0, ui64 logDurationUs = 0, bool logShuttle = false)
  424. : TAdHocTraceConfig(logSize, logDurationUs, logShuttle)
  425. {
  426. auto block = Cfg.MutableBlocks(0);
  427. auto pdesc = block->MutableProbeDesc();
  428. pdesc->SetProvider(provider);
  429. pdesc->SetName(probe);
  430. }
  431. explicit TAdHocTraceConfig(const TString& group, ui16 logSize = 0, ui64 logDurationUs = 0, bool logShuttle = false)
  432. : TAdHocTraceConfig(logSize, logDurationUs, logShuttle)
  433. {
  434. auto block = Cfg.MutableBlocks(0);
  435. auto pdesc = block->MutableProbeDesc();
  436. pdesc->SetGroup(group);
  437. }
  438. TString Id() const
  439. {
  440. TStringStream ss;
  441. for (size_t blockIdx = 0; blockIdx < Cfg.BlocksSize(); blockIdx++) {
  442. if (!ss.Str().empty()) {
  443. ss << "/";
  444. }
  445. auto block = Cfg.GetBlocks(blockIdx);
  446. auto pdesc = block.GetProbeDesc();
  447. if (pdesc.GetProvider()) {
  448. ss << "." << pdesc.GetProvider() << "." << pdesc.GetName();
  449. } else if (pdesc.GetGroup()) {
  450. ss << ".Group." << pdesc.GetGroup();
  451. }
  452. // TODO[serxa]: handle predicate
  453. for (size_t actionIdx = 0; actionIdx < block.ActionSize(); actionIdx++) {
  454. const NLWTrace::TAction& action = block.GetAction(actionIdx);
  455. if (action.HasRunLogShuttleAction()) {
  456. auto ls = action.GetRunLogShuttleAction();
  457. ss << ".alsr";
  458. if (ls.GetIgnore()) {
  459. ss << "-i";
  460. }
  461. if (ls.GetShuttlesCount()) {
  462. ss << "-s" << ls.GetShuttlesCount();
  463. }
  464. if (ls.GetMaxTrackLength()) {
  465. ss << "-t" << ls.GetMaxTrackLength();
  466. }
  467. } else if (action.HasEditLogShuttleAction()) {
  468. auto ls = action.GetEditLogShuttleAction();
  469. ss << ".alse";
  470. if (ls.GetIgnore()) {
  471. ss << "-i";
  472. }
  473. } else if (action.HasDropLogShuttleAction()) {
  474. ss << ".alsd";
  475. }
  476. }
  477. }
  478. if (Cfg.GetPerThreadLogSize()) {
  479. ss << ".l" << Cfg.GetPerThreadLogSize();
  480. }
  481. if (Cfg.GetLogDurationUs()) {
  482. ui64 logDurationUs = Cfg.GetLogDurationUs();
  483. if (logDurationUs % (60 * 1000 * 1000) == 0)
  484. ss << ".d" << logDurationUs / (60 * 1000 * 1000) << "m";
  485. if (logDurationUs % (1000 * 1000) == 0)
  486. ss << ".d" << logDurationUs / (1000 * 1000) << "s";
  487. else if (logDurationUs % 1000 == 0)
  488. ss << ".d" << logDurationUs / 1000 << "ms";
  489. else
  490. ss << ".d" << logDurationUs << "us";
  491. }
  492. return ss.Str();
  493. }
  494. bool IsValid() const
  495. {
  496. return Cfg.BlocksSize() > 0;
  497. }
  498. NLWTrace::TQuery Query() const
  499. {
  500. if (!IsValid()) {
  501. ythrow yexception() << "invalid adhoc trace config";
  502. }
  503. return Cfg;
  504. }
  505. bool ParseId(const TString& id)
  506. {
  507. if (IsAdHocId(id)) {
  508. for (const TString& block : SplitString(id, "/")) {
  509. if (block.empty()) {
  510. continue;
  511. }
  512. size_t cutPos = (block[0] == '.'? 1: 0);
  513. TVector<TString> parts = SplitString(block.substr(cutPos), ".");
  514. WWW_CHECK(parts.size() >= 2, "too few parts in adhoc trace id '%s' block '%s'", id.data(), block.data());
  515. auto blockPb = Cfg.AddBlocks();
  516. auto pdescPb = blockPb->MutableProbeDesc();
  517. if (parts[0] == "Group") {
  518. pdescPb->SetGroup(parts[1]);
  519. } else {
  520. pdescPb->SetProvider(parts[0]);
  521. pdescPb->SetName(parts[1]);
  522. }
  523. bool defaultAction = true;
  524. for (auto i = parts.begin() + 2, e = parts.end(); i != e; ++i) {
  525. const TString& part = *i;
  526. if (part.empty()) {
  527. continue;
  528. }
  529. switch (part[0]) {
  530. case 'l': Cfg.SetPerThreadLogSize(FromString<ui16>(part.substr(1))); break;
  531. case 'd': Cfg.SetLogDurationUs(ParseDuration(part.substr(1))); break;
  532. case 's': blockPb->MutablePredicate()->SetSampleRate(1.0 / Max<ui64>(1, FromString<ui64>(part.substr(1)))); break;
  533. case 'p': ParsePredicate(blockPb->MutablePredicate()->AddOperators(), part.substr(1)); break;
  534. case 'a': ParseAction(blockPb->AddAction(), part.substr(1)); defaultAction = false; break;
  535. default: WWW_CHECK(false, "unknown adhoc trace part type '%s' in '%s'", part.data(), id.data());
  536. }
  537. }
  538. if (defaultAction) {
  539. blockPb->AddAction()->MutableLogAction();
  540. }
  541. }
  542. return true;
  543. }
  544. return false;
  545. }
  546. private:
  547. static bool IsAdHocId(const TString& id)
  548. {
  549. return !id.empty() && id[0] == '.';
  550. }
  551. void ParsePredicate(NLWTrace::TOperator* op, const TString& p)
  552. {
  553. size_t sign = p.find_first_of("=!><");
  554. WWW_CHECK(sign != TString::npos, "wrong predicate format in adhoc trace: %s", p.data());
  555. op->AddArgument()->SetParam(p.substr(0, sign));
  556. size_t value = sign + 1;
  557. switch (p[sign]) {
  558. case '=':
  559. op->SetType(NLWTrace::OT_EQ);
  560. break;
  561. case '!': {
  562. WWW_CHECK(p.size() > sign + 1, "wrong predicate operator format in adhoc trace: %s", p.data());
  563. WWW_CHECK(p[sign + 1] == '=', "wrong predicate operator format in adhoc trace: %s", p.data());
  564. value++;
  565. op->SetType(NLWTrace::OT_NE);
  566. break;
  567. }
  568. case '<': {
  569. WWW_CHECK(p.size() > sign + 1, "wrong predicate operator format in adhoc trace: %s", p.data());
  570. if (p[sign + 1] == '=') {
  571. value++;
  572. op->SetType(NLWTrace::OT_LE);
  573. } else {
  574. op->SetType(NLWTrace::OT_LT);
  575. }
  576. break;
  577. }
  578. case '>': {
  579. WWW_CHECK(p.size() > sign + 1, "wrong predicate operator format in adhoc trace: %s", p.data());
  580. if (p[sign + 1] == '=') {
  581. value++;
  582. op->SetType(NLWTrace::OT_GE);
  583. } else {
  584. op->SetType(NLWTrace::OT_GT);
  585. }
  586. break;
  587. }
  588. default: WWW_CHECK(false, "wrong predicate operator format in adhoc trace: %s", p.data());
  589. }
  590. op->AddArgument()->SetValue(p.substr(value));
  591. }
  592. void ParseAction(NLWTrace::TAction* action, const TString& a)
  593. {
  594. // NOTE: checks for longer action names should go first, your captain.
  595. if (a.substr(0, 3) == "lsr") {
  596. auto pb = action->MutableRunLogShuttleAction();
  597. for (const TString& opt : SplitString(a.substr(3), "-")) {
  598. if (!opt.empty()) {
  599. switch (opt[0]) {
  600. case 'i': pb->SetIgnore(true); break;
  601. case 's': pb->SetShuttlesCount(FromString<ui64>(opt.substr(1))); break;
  602. case 't': pb->SetMaxTrackLength(FromString<ui64>(opt.substr(1))); break;
  603. default: WWW_CHECK(false, "unknown adhoc trace log shuttle opt '%s' in '%s'", opt.data(), a.data());
  604. }
  605. }
  606. }
  607. } else if (a.substr(0, 3) == "lse") {
  608. auto pb = action->MutableEditLogShuttleAction();
  609. for (const TString& opt : SplitString(a.substr(3), "-")) {
  610. if (!opt.empty()) {
  611. switch (opt[0]) {
  612. case 'i': pb->SetIgnore(true); break;
  613. default: WWW_CHECK(false, "unknown adhoc trace log shuttle opt '%s' in '%s'", opt.data(), a.data());
  614. }
  615. }
  616. }
  617. } else if (a.substr(0, 3) == "lsd") {
  618. action->MutableDropLogShuttleAction();
  619. } else if (a.substr(0, 1) == "l") {
  620. auto pb = action->MutableLogAction();
  621. for (const TString& opt : SplitString(a.substr(1), "-")) {
  622. if (!opt.empty()) {
  623. switch (opt[0]) {
  624. case 't': pb->SetLogTimestamp(true); break;
  625. case 'r': pb->SetMaxRecords(FromString<ui32>(opt.substr(1))); break;
  626. default: WWW_CHECK(false, "unknown adhoc trace log opt '%s' in '%s'", opt.data(), a.data());
  627. }
  628. }
  629. }
  630. } else {
  631. WWW_CHECK(false, "wrong action format in adhoc trace: %s", a.data());
  632. }
  633. }
  634. static ui64 ParseDuration(const TString& s)
  635. {
  636. if (s.substr(s.length() - 2) == "us")
  637. return FromString<ui64>(s.substr(0, s.length() - 2));
  638. if (s.substr(s.length() - 2) == "ms")
  639. return FromString<ui64>(s.substr(0, s.length() - 2)) * 1000;
  640. if (s.substr(s.length() - 1) == "s")
  641. return FromString<ui64>(s.substr(0, s.length() - 1)) * 1000 * 1000;
  642. if (s.substr(s.length() - 1) == "m")
  643. return FromString<ui64>(s.substr(0, s.length() - 1)) * 60 * 1000 * 1000;
  644. else
  645. return FromString<ui64>(s);
  646. }
  647. };
  648. // Class that maintains one thread iff there are adhoc traces and cleans'em by deadlines
  649. class TTraceCleaner {
  650. private:
  651. NLWTrace::TManager* TraceMngr;
  652. TAtomic Quit = 0;
  653. TMutex Mtx;
  654. TCondVar WakeCondVar;
  655. THashMap<TString, TInstant> Deadlines;
  656. volatile bool ThreadIsRunning = false;
  657. THolder<TThread> Thread;
  658. public:
  659. TTraceCleaner(NLWTrace::TManager* traceMngr)
  660. : TraceMngr(traceMngr)
  661. {}
  662. ~TTraceCleaner()
  663. {
  664. AtomicSet(Quit, 1);
  665. WakeCondVar.Signal();
  666. // TThread dtor joins thread
  667. }
  668. // Returns deadline for specified trace id or zero
  669. TInstant GetDeadline(const TString& id) const
  670. {
  671. TGuard<TMutex> g(Mtx);
  672. auto iter = Deadlines.find(id);
  673. return iter != Deadlines.end()? iter->second: TInstant::Zero();
  674. }
  675. // Postpone deletion of specified trace for specified timeout
  676. void Postpone(const TString& id, TDuration timeout, bool allowLowering)
  677. {
  678. TGuard<TMutex> g(Mtx);
  679. TInstant newDeadline = TInstant::Now() + timeout;
  680. if (Deadlines[id] < newDeadline) {
  681. Deadlines[id] = newDeadline;
  682. } else if (allowLowering) { // Deadline lowering requires wake
  683. Deadlines[id] = newDeadline;
  684. WakeCondVar.Signal();
  685. }
  686. if (newDeadline != TInstant::Max() && !ThreadIsRunning) {
  687. // Note that dtor joins previous thread if any
  688. Thread.Reset(new TThread(ThreadProc, this));
  689. Thread->Start();
  690. ThreadIsRunning = true;
  691. }
  692. }
  693. // Forget about specified trace deletion
  694. void Forget(const TString& id)
  695. {
  696. TGuard<TMutex> g(Mtx);
  697. Deadlines.erase(id);
  698. WakeCondVar.Signal(); // in case thread is not required any more
  699. }
  700. private:
  701. void Exec()
  702. {
  703. while (!AtomicGet(Quit)) {
  704. TGuard<TMutex> g(Mtx);
  705. // Delete all timed out traces
  706. TInstant now = TInstant::Now();
  707. TInstant nextDeadline = TInstant::Max();
  708. for (auto i = Deadlines.begin(), e = Deadlines.end(); i != e;) {
  709. const TString& id = i->first;
  710. TInstant deadline = i->second;
  711. if (deadline < now) {
  712. try {
  713. TraceMngr->Delete(id);
  714. } catch (...) {
  715. // already deleted
  716. }
  717. Deadlines.erase(i++);
  718. } else {
  719. nextDeadline = Min(nextDeadline, deadline);
  720. ++i;
  721. }
  722. }
  723. // Stop thread if there is no more work
  724. if (Deadlines.empty() || nextDeadline == TInstant::Max()) {
  725. ThreadIsRunning = false;
  726. break;
  727. }
  728. // Wait until next deadline or quit
  729. WakeCondVar.WaitD(Mtx, nextDeadline);
  730. }
  731. }
  732. static void* ThreadProc(void* _this)
  733. {
  734. TString name = "LWTraceCleaner";
  735. // Copy-pasted from kikimr/core/util/thread.h
  736. #if defined(_linux_)
  737. TStringStream linuxName;
  738. linuxName << TStringBuf(GetExecPath()).RNextTok('/') << "." << name;
  739. TThread::SetCurrentThreadName(linuxName.Str().data());
  740. #else
  741. TThread::SetCurrentThreadName(name.data());
  742. #endif
  743. static_cast<TTraceCleaner*>(_this)->Exec();
  744. return nullptr;
  745. }
  746. };
  747. class TChromeTrace {
  748. private:
  749. TMultiMap<double, TString> TraceEvents;
  750. THashMap<TThread::TId, TString> Tids;
  751. public:
  752. void Add(TThread::TId tid, ui64 tsCycles, const TString& ph, const TString& cat,
  753. const NLWTrace::TLogItem* argsItem = nullptr,
  754. const TString& name = TString(), const TString& id = TString())
  755. {
  756. auto tidIter = Tids.find(tid);
  757. if (tidIter == Tids.end()) {
  758. tidIter = Tids.emplace(tid, ToString(Tids.size() + 1)).first;
  759. }
  760. const TString& shortId = tidIter->second;
  761. double ts = Timestamp(tsCycles);
  762. TraceEvents.emplace(ts, Event(shortId, ts, ph, cat, argsItem, name, id));
  763. }
  764. void Output(IOutputStream& os)
  765. {
  766. os << "{\"traceEvents\":[";
  767. bool first = true;
  768. for (auto kv : TraceEvents) {
  769. if (!first) {
  770. os << ",\n";
  771. }
  772. os << kv.second;
  773. first = false;
  774. }
  775. os << "]}";
  776. }
  777. private:
  778. static TString Event(const TString& tid, double ts, const TString& ph, const TString& cat,
  779. const NLWTrace::TLogItem* argsItem,
  780. const TString& name, const TString& id)
  781. {
  782. TStringStream ss;
  783. pid_t pid = 1;
  784. ss << "{\"pid\":" << pid
  785. << ",\"tid\":" << tid
  786. << ",\"ts\":" << Sprintf("%lf", ts)
  787. << ",\"ph\":\"" << ph << "\""
  788. << ",\"cat\":\"" << cat << "\"";
  789. if (name) {
  790. ss << ",\"name\":\"" << name << "\"";
  791. }
  792. if (id) {
  793. ss << ",\"id\":\"" << id << "\"";
  794. }
  795. if (argsItem && argsItem->SavedParamsCount > 0) {
  796. ss << ",\"args\":{";
  797. TString paramValues[LWTRACE_MAX_PARAMS];
  798. argsItem->Probe->Event.Signature.SerializeParams(argsItem->Params, paramValues);
  799. bool first = true;
  800. for (size_t pi = 0; pi < argsItem->SavedParamsCount; pi++, first = false) {
  801. if (!first) {
  802. ss << ",";
  803. }
  804. ss << "\"" << TString(argsItem->Probe->Event.Signature.ParamNames[pi]) << "\":"
  805. "\"" << paramValues[pi] << "\"";
  806. }
  807. ss << "}";
  808. }
  809. ss << "}";
  810. return ss.Str();
  811. }
  812. static double Timestamp(ui64 cycles)
  813. {
  814. return double(cycles) * 1000000.0 / NHPTimer::GetClockRate();
  815. }
  816. };
  817. TString MakeUrl(const TCgiParameters& e, const THashMap<TString, TString>& values)
  818. {
  819. TStringStream ss;
  820. bool first = true;
  821. for (const auto& [k, v] : e) {
  822. if (values.find(k) == values.end()) {
  823. ss << (first? "?": "&") << k << "=" << v;
  824. first = false;
  825. }
  826. }
  827. for (const auto& [k, v] : values) {
  828. ss << (first? "?": "&") << k << "=" << v;
  829. first = false;
  830. }
  831. return ss.Str();
  832. }
  833. TString MakeUrl(const TCgiParameters& e, const TString& key, const TString& value, bool keep = false)
  834. {
  835. TStringStream ss;
  836. bool first = true;
  837. for (const auto& kv : e) {
  838. if (keep || kv.first != key) {
  839. ss << (first? "?": "&") << kv.first << "=" << kv.second;
  840. first = false;
  841. }
  842. }
  843. ss << (first? "?": "&") << key << "=" << value;
  844. return ss.Str();
  845. }
  846. TString MakeUrlAdd(const TCgiParameters& e, const TString& key, const TString& value)
  847. {
  848. TStringStream ss;
  849. bool first = true;
  850. for (const auto& kv : e) {
  851. ss << (first? "?": "&") << kv.first << "=" << kv.second;
  852. first = false;
  853. }
  854. ss << (first? "?": "&") << key << "=" << value;
  855. return ss.Str();
  856. }
  857. TString MakeUrlReplace(const TCgiParameters& e, const TString& key, const TString& oldValue, const TString& newValue)
  858. {
  859. TStringStream ss;
  860. bool first = true;
  861. bool inserted = false;
  862. for (const auto& kv : e) {
  863. if (kv.first == key && (kv.second == oldValue || kv.second == newValue)) {
  864. if (!inserted) {
  865. inserted = true;
  866. ss << (first? "?": "&") << key << "=" << newValue;
  867. first = false;
  868. }
  869. } else {
  870. ss << (first? "?": "&") << kv.first << "=" << kv.second;
  871. first = false;
  872. }
  873. }
  874. if (!inserted) {
  875. ss << (first? "?": "&") << key << "=" << newValue;
  876. }
  877. return ss.Str();
  878. }
  879. TString MakeUrlErase(const TCgiParameters& e, const TString& key, const TString& value)
  880. {
  881. TStringStream ss;
  882. bool first = true;
  883. for (const auto& kv : e) {
  884. if (kv.first != key || kv.second != value) {
  885. ss << (first? "?": "&") << kv.first << "=" << kv.second;
  886. first = false;
  887. }
  888. }
  889. return ss.Str();
  890. }
  891. TString EscapeSubvalue(const TString& s)
  892. {
  893. TString ret;
  894. ret.reserve(s.size());
  895. for (size_t i = 0; i < s.size(); i++) {
  896. char c = s[i];
  897. if (c == ':') {
  898. ret.append("^c");
  899. } else if (c == '^') {
  900. ret.append("^^");
  901. } else {
  902. ret.append(c);
  903. }
  904. }
  905. return ret;
  906. }
  907. TString UnescapeSubvalue(const TString& s)
  908. {
  909. TString ret;
  910. ret.reserve(s.size());
  911. for (size_t i = 0; i < s.size(); i++) {
  912. char c = s[i];
  913. if (c == '^' && i + 1 < s.size()) {
  914. char c2 = s[++i];
  915. if (c2 == 'c') {
  916. ret.append(':');
  917. } else if (c2 == '^') {
  918. ret.append('^');
  919. } else {
  920. ret.append(c);
  921. ret.append(c2);
  922. }
  923. } else {
  924. ret.append(c);
  925. }
  926. }
  927. return ret;
  928. }
  929. TVector<TString> Subvalues(const TCgiParameters& e, const TString& key)
  930. {
  931. if (!e.Has(key)) {
  932. return TVector<TString>();
  933. } else {
  934. TVector<TString> ret;
  935. for (const TString& s : SplitString(e.Get(key), ":", 0, KEEP_EMPTY_TOKENS)) {
  936. ret.push_back(UnescapeSubvalue(s));
  937. }
  938. if (ret.empty()) {
  939. ret.push_back("");
  940. }
  941. return ret;
  942. }
  943. }
  944. TString ParseTagsOut(const TString& taggedStr, TTags& tags)
  945. {
  946. auto vec = SplitString(taggedStr, "-");
  947. if (vec.empty()) {
  948. return "";
  949. }
  950. auto iter = vec.begin();
  951. TString value = *iter++;
  952. for (;iter != vec.end(); ++iter) {
  953. tags.insert(*iter);
  954. }
  955. return value;
  956. }
  957. TString JoinTags(TTags tags) {
  958. return JoinStrings(TVector<TString>(tags.begin(), tags.end()), "-");
  959. }
  960. TString MakeValue(const TVector<TString>& subvalues)
  961. {
  962. TVector<TString> subvaluesEsc;
  963. for (const TString& s : subvalues) {
  964. subvaluesEsc.push_back(EscapeSubvalue(s));
  965. }
  966. return JoinStrings(subvaluesEsc, ":");
  967. }
  968. TString MakeUrlAddSub(const TCgiParameters& e, const TString& key, const TString& subvalue)
  969. {
  970. const TString& value = e.Get(key);
  971. auto subvalues = Subvalues(e, key);
  972. subvalues.push_back(subvalue);
  973. return MakeUrlReplace(e, key, value, MakeValue(subvalues));
  974. }
  975. TString MakeUrlReplaceSub(const TCgiParameters& e, const TString& key, const TString& oldSubvalue, const TString& newSubvalue)
  976. {
  977. const TString& value = e.Get(key);
  978. auto subvalues = Subvalues(e, key);
  979. auto iter = std::find(subvalues.begin(), subvalues.end(), oldSubvalue);
  980. if (iter != subvalues.end()) {
  981. *iter = newSubvalue;
  982. } else {
  983. subvalues.push_back(newSubvalue);
  984. }
  985. return MakeUrlReplace(e, key, value, MakeValue(subvalues));
  986. }
  987. TString MakeUrlEraseSub(const TCgiParameters& e, const TString& key, const TString& subvalue)
  988. {
  989. const TString& value = e.Get(key);
  990. auto subvalues = Subvalues(e, key);
  991. auto iter = std::find(subvalues.begin(), subvalues.end(), subvalue);
  992. if (iter != subvalues.end()) {
  993. subvalues.erase(iter);
  994. }
  995. if (subvalues.empty()) {
  996. return MakeUrlErase(e, key, value);
  997. } else {
  998. return MakeUrlReplace(e, key, value, MakeValue(subvalues));
  999. }
  1000. }
  1001. template <bool sub> TString UrlAdd(const TCgiParameters& e, const TString& key, const TString& value);
  1002. template <> TString UrlAdd<false>(const TCgiParameters& e, const TString& key, const TString& value) {
  1003. return MakeUrlAdd(e, key, value);
  1004. }
  1005. template <> TString UrlAdd<true>(const TCgiParameters& e, const TString& key, const TString& value) {
  1006. return MakeUrlAddSub(e, key, value);
  1007. }
  1008. template <bool sub> TString UrlReplace(const TCgiParameters& e, const TString& key, const TString& oldValue, const TString& newValue);
  1009. template <> TString UrlReplace<false>(const TCgiParameters& e, const TString& key, const TString& oldValue, const TString& newValue) {
  1010. return MakeUrlReplace(e, key, oldValue, newValue);
  1011. }
  1012. template <> TString UrlReplace<true>(const TCgiParameters& e, const TString& key, const TString& oldValue, const TString& newValue) {
  1013. return MakeUrlReplaceSub(e, key, oldValue, newValue);
  1014. }
  1015. template <bool sub> TString UrlErase(const TCgiParameters& e, const TString& key, const TString& value);
  1016. template <> TString UrlErase<false>(const TCgiParameters& e, const TString& key, const TString& value) {
  1017. return MakeUrlErase(e, key, value);
  1018. }
  1019. template <> TString UrlErase<true>(const TCgiParameters& e, const TString& key, const TString& value) {
  1020. return MakeUrlEraseSub(e, key, value);
  1021. }
  1022. void OutputCommonHeader(IOutputStream& out)
  1023. {
  1024. out << NResource::Find("lwtrace/mon/static/header.html") << Endl;
  1025. }
  1026. void OutputCommonFooter(IOutputStream& out)
  1027. {
  1028. out << NResource::Find("lwtrace/mon/static/footer.html") << Endl;
  1029. }
  1030. struct TScopedHtmlInner {
  1031. explicit TScopedHtmlInner(IOutputStream& str)
  1032. : Str(str)
  1033. {
  1034. Str << "<!DOCTYPE html>\n"
  1035. "<html>";
  1036. HTML(str) {
  1037. HEAD() { OutputCommonHeader(Str); }
  1038. }
  1039. Str << "<body>";
  1040. }
  1041. ~TScopedHtmlInner()
  1042. {
  1043. OutputCommonFooter(Str);
  1044. Str << "</body></html>";
  1045. }
  1046. inline operator bool () const noexcept { return true; }
  1047. IOutputStream &Str;
  1048. };
  1049. TString NavbarHeader()
  1050. {
  1051. return "<div class=\"navbar-header\">"
  1052. "<a class=\"navbar-brand\" href=\"?mode=\">LWTrace</a>"
  1053. "</div>";
  1054. }
  1055. struct TSelectorsContainer {
  1056. TSelectorsContainer(IOutputStream& str)
  1057. : Str(str)
  1058. {
  1059. Str << "<nav id=\"selectors-container\" class=\"navbar navbar-default\">"
  1060. "<div class=\"container-fluid\">"
  1061. << NavbarHeader() <<
  1062. "<div class=\"navbar-text\" style=\"margin-top:12px;margin-bottom:10px\">";
  1063. }
  1064. ~TSelectorsContainer() {
  1065. try {
  1066. Str <<
  1067. "</div>"
  1068. "<div class=\"container-fluid\">"
  1069. "<div class=\"pull-right\">"
  1070. "<button id=\"download-btn\""
  1071. " type=\"button\" style=\"display: inline-block;margin:7px\""
  1072. " title=\"Chromium trace (load it in chrome://tracing/)\""
  1073. " class=\"btn btn-default hidden\">"
  1074. "<span class=\"glyphicon glyphicon-download-alt\"></span>"
  1075. "</button>"
  1076. "</div>"
  1077. "</div>"
  1078. "</div></nav>";
  1079. } catch(...) {}
  1080. }
  1081. IOutputStream& Str;
  1082. };
  1083. struct TNullContainer {
  1084. TNullContainer(IOutputStream&) {}
  1085. };
  1086. class TPageGenBase: public std::exception {};
  1087. template <class TContainer = TNullContainer>
  1088. class TPageGen: public TPageGenBase {
  1089. private:
  1090. TString Content;
  1091. TString HttpResponse;
  1092. public:
  1093. void BuildResponse()
  1094. {
  1095. TStringStream ss;
  1096. WWW_HTML(ss) {
  1097. TContainer container(ss);
  1098. ss << Content;
  1099. }
  1100. HttpResponse = ss.Str();
  1101. }
  1102. explicit TPageGen(const TString& content = TString())
  1103. : Content(content)
  1104. {
  1105. BuildResponse();
  1106. }
  1107. void Append(const TString& moreContent)
  1108. {
  1109. Content.append(moreContent);
  1110. BuildResponse();
  1111. }
  1112. void Prepend(const TString& moreContent)
  1113. {
  1114. Content.prepend(moreContent);
  1115. BuildResponse();
  1116. }
  1117. virtual const char* what() const noexcept { return HttpResponse.data(); }
  1118. operator bool() const { return !Content.empty(); }
  1119. };
  1120. enum EStyleFlags {
  1121. // bit 1
  1122. Link = 0x0,
  1123. Button = 0x1,
  1124. // bit 2
  1125. NonErasable = 0x0,
  1126. Erasable = 0x2,
  1127. // bit 3-4
  1128. Medium = 0x0,
  1129. Large = 0x4,
  1130. Small = 0x8,
  1131. ExtraSmall = 0xC,
  1132. SizeMask = 0xC,
  1133. // bit 5
  1134. NoCaret = 0x0,
  1135. Caret = 0x10,
  1136. // bit 6
  1137. SimpleValue = 0x0,
  1138. CompositeValue = 0x20
  1139. };
  1140. template <ui64 flags>
  1141. TString BtnClass() {
  1142. if ((flags & SizeMask) == Large) {
  1143. return "btn btn-lg";
  1144. } else if ((flags & SizeMask) == Small) {
  1145. return "btn btn-sm";
  1146. } else if ((flags & SizeMask) == ExtraSmall) {
  1147. return "btn btn-xs";
  1148. }
  1149. return "btn";
  1150. }
  1151. void SelectorTitle(IOutputStream& os, const TString& text)
  1152. {
  1153. if (!text.empty()) {
  1154. os << text;
  1155. }
  1156. }
  1157. template <ui64 flags>
  1158. void BtnHref(IOutputStream& os, const TString& text, const TString& href, bool push = false)
  1159. {
  1160. if (flags & Button) {
  1161. os << "<button type=\"button\" style=\"display: inline-block;margin:3px\" class=\""
  1162. << BtnClass<flags>() << " "
  1163. << (push? "btn-primary": "btn-default")
  1164. << "\" onClick=\"window.location.href='" << href << "';\">"
  1165. << text
  1166. << "</button>";
  1167. } else {
  1168. os << "<a href=\"" << href << "\">"
  1169. << text
  1170. << "</a>";
  1171. }
  1172. }
  1173. void DropdownBeginSublist(IOutputStream& os, const TString& text)
  1174. {
  1175. os << "<li>" << text << "<ul class=\"dropdown-menu\">";
  1176. }
  1177. void DropdownEndSublist(IOutputStream& os)
  1178. {
  1179. os << "</ul></li>";
  1180. }
  1181. void DropdownItem(IOutputStream& os, const TString& text, const TString& href, bool separated = false)
  1182. {
  1183. if (separated) {
  1184. os << "<li role=\"separator\" class=\"divider\"></li>";
  1185. }
  1186. os << "<li><a href=\"" << href << "\">" << text << "</a></li>";
  1187. }
  1188. TString SuggestSelection()
  1189. {
  1190. return "--- ";
  1191. }
  1192. TString RemoveSelection()
  1193. {
  1194. return "Remove";
  1195. }
  1196. TString GetDescription(const TString& value, const TVariants& variants)
  1197. {
  1198. for (const auto& var : variants) {
  1199. if (value == var.first) {
  1200. return var.second;
  1201. }
  1202. }
  1203. if (!value) {
  1204. return SuggestSelection();
  1205. }
  1206. return value;
  1207. }
  1208. template <ui64 flags, bool sub = false>
  1209. void DropdownSelector(IOutputStream& os, const TCgiParameters& e, const TString& param, const TString& value,
  1210. const TString& text, const TVariants& variants, const TString& realValue = TString())
  1211. {
  1212. HTML(os) {
  1213. SelectorTitle(os, text);
  1214. os << "<div class=\"dropdown\" style=\"display:inline-block;margin:3px\">";
  1215. if (flags & Button) {
  1216. os << "<button class=\"" << BtnClass<flags>() << " btn-primary dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\">";
  1217. } else {
  1218. os << "<a href=\"#\" data-toggle=\"dropdown\">";
  1219. }
  1220. os << GetDescription(flags & CompositeValue? realValue: value, variants);
  1221. if (flags & Caret) {
  1222. os << "<span class=\"caret\"></span>";
  1223. }
  1224. if (flags & Button) {
  1225. os <<"</button>";
  1226. } else {
  1227. os <<"</a>";
  1228. }
  1229. UL_CLASS ("dropdown-menu") {
  1230. for (const auto& var : variants) {
  1231. DropdownItem(os, var.second, UrlReplace<sub>(e, param, value, var.first));
  1232. }
  1233. if (flags & Erasable) {
  1234. DropdownItem(os, RemoveSelection(), UrlErase<sub>(e, param, value), true);
  1235. }
  1236. }
  1237. os << "</div>";
  1238. }
  1239. }
  1240. void RequireSelection(TStringStream& ss, const TCgiParameters& e, const TString& param,
  1241. const TString& text, const TVariants& variants)
  1242. {
  1243. const TString& value = e.Get(param);
  1244. DropdownSelector<Link>(ss, e, param, value, text, variants);
  1245. if (!value) {
  1246. throw TPageGen<TSelectorsContainer>(ss.Str());
  1247. }
  1248. }
  1249. void RequireMultipleSelection(TStringStream& ss, const TCgiParameters& e, const TString& param,
  1250. const TString& text, const TVariants& variants)
  1251. {
  1252. SelectorTitle(ss, text);
  1253. TSet<TString> selectedValues;
  1254. for (const TString& subvalue : Subvalues(e, param)) {
  1255. selectedValues.insert(subvalue);
  1256. }
  1257. for (const TString& subvalue : Subvalues(e, param)) {
  1258. DropdownSelector<Erasable, true>(ss, e, param, subvalue, "", variants);
  1259. }
  1260. if (selectedValues.contains("")) {
  1261. throw TPageGen<TSelectorsContainer>(ss.Str());
  1262. } else {
  1263. BtnHref<Button|ExtraSmall>(ss, "+", MakeUrlAddSub(e, param, ""));
  1264. if (selectedValues.empty()) {
  1265. throw TPageGen<TSelectorsContainer>(ss.Str());
  1266. }
  1267. }
  1268. }
  1269. void OptionalSelection(TStringStream& ss, const TCgiParameters& e, const TString& param,
  1270. const TString& text, const TVariants& variants)
  1271. {
  1272. TSet<TString> selectedValues;
  1273. for (const TString& subvalue : Subvalues(e, param)) {
  1274. selectedValues.insert(subvalue);
  1275. }
  1276. if (!selectedValues.empty()) {
  1277. SelectorTitle(ss, text);
  1278. }
  1279. for (const TString& subvalue : Subvalues(e, param)) {
  1280. DropdownSelector<Erasable, true>(ss, e, param, subvalue, "", variants);
  1281. }
  1282. if (selectedValues.empty()) {
  1283. BtnHref<Button|ExtraSmall>(ss, text, MakeUrlAddSub(e, param, ""));
  1284. }
  1285. }
  1286. void OptionalMultipleSelection(TStringStream& ss, const TCgiParameters& e, const TString& param,
  1287. const TString& text, const TVariants& variants)
  1288. {
  1289. TSet<TString> selectedValues;
  1290. for (const TString& subvalue : Subvalues(e, param)) {
  1291. selectedValues.insert(subvalue);
  1292. }
  1293. if (!selectedValues.empty()) {
  1294. SelectorTitle(ss, text);
  1295. }
  1296. for (const TString& subvalue : Subvalues(e, param)) {
  1297. DropdownSelector<Erasable, true>(ss, e, param, subvalue, "", variants);
  1298. }
  1299. if (selectedValues.contains("")) {
  1300. throw TPageGen<TSelectorsContainer>(ss.Str());
  1301. } else {
  1302. BtnHref<Button|ExtraSmall>(ss, selectedValues.empty()? text: "+", MakeUrlAddSub(e, param, ""));
  1303. }
  1304. }
  1305. TVariants ListColumns(const NAnalytics::TTable& table)
  1306. {
  1307. TSet<TString> cols;
  1308. // bool addSpecialCols = false;
  1309. // if (addSpecialCols) {
  1310. // cols.insert("_count");
  1311. // }
  1312. for (auto& row : table) {
  1313. for (auto& kv : row) {
  1314. cols.insert(kv.first);
  1315. }
  1316. }
  1317. TVariants result;
  1318. for (const auto& s : cols) {
  1319. result.emplace_back(s, s);
  1320. }
  1321. return result;
  1322. }
  1323. TString TaggedValue(const TString& value, const TString& tag)
  1324. {
  1325. if (!tag) {
  1326. return value;
  1327. }
  1328. return value + "-" + tag;
  1329. }
  1330. TVariants ValueVars(const TVariants& values, const TString& tag)
  1331. {
  1332. TVariants ret;
  1333. for (auto& p : values) {
  1334. ret.emplace_back(TaggedValue(p.first, tag), p.second);
  1335. }
  1336. return ret;
  1337. }
  1338. TVariants TagVars(const TString& value, const TVariants& tags)
  1339. {
  1340. TVariants ret;
  1341. for (auto& p : tags) {
  1342. ret.emplace_back(TaggedValue(value, p.first), p.second);
  1343. }
  1344. return ret;
  1345. }
  1346. TVariants SeriesTags()
  1347. {
  1348. TVariants ret; // MSVS2013 doesn't understand complex initializer lists
  1349. ret.emplace_back("", "as is");
  1350. ret.emplace_back("stack", "cumulative");
  1351. return ret;
  1352. }
  1353. void SeriesSelectors(TStringStream& ss, const TCgiParameters& e,
  1354. const TString& xparam, const TString& yparam, const NAnalytics::TTable& data)
  1355. {
  1356. TTags xtags;
  1357. TString xn = ParseTagsOut(e.Get(xparam), xtags);
  1358. DropdownSelector<Erasable, true>(ss, e, xparam, e.Get(xparam), "with Ox:",
  1359. ValueVars(ListColumns(data), JoinTags(xtags)));
  1360. if (xn) {
  1361. DropdownSelector<Link, true>(ss, e, xparam, e.Get(xparam), "",
  1362. TagVars(xn, SeriesTags()));
  1363. }
  1364. TString yns = e.Get(yparam);
  1365. SelectorTitle(ss, "and Oy:");
  1366. bool first = true;
  1367. bool hasEmpty = false;
  1368. for (auto& subvalue : Subvalues(e, yparam)) {
  1369. TTags ytags;
  1370. TString yn = ParseTagsOut(subvalue, ytags);
  1371. DropdownSelector<Erasable, true>(ss, e, yparam, subvalue, first? "": ", ",
  1372. ValueVars(ListColumns(data), JoinTags(ytags)));
  1373. if (yn) {
  1374. DropdownSelector<Link, true>(ss, e, yparam, subvalue, "",
  1375. TagVars(yn, SeriesTags()));
  1376. }
  1377. first = false;
  1378. if (yn.empty()) {
  1379. hasEmpty = true;
  1380. }
  1381. }
  1382. if (hasEmpty) {
  1383. throw TPageGen<TSelectorsContainer>(ss.Str());
  1384. } else {
  1385. BtnHref<Button|ExtraSmall>(ss, "+", MakeUrlAddSub(e, yparam, ""));
  1386. }
  1387. if (!xn || !yns) {
  1388. throw TPageGen<TSelectorsContainer>(ss.Str());
  1389. }
  1390. }
  1391. class TProbesHtmlPrinter {
  1392. private:
  1393. TVector<TVector<TString>> TableData;
  1394. static constexpr int TimeoutSec = 15 * 60; // default timeout
  1395. public:
  1396. void Push(const NLWTrace::TProbe* probe)
  1397. {
  1398. TableData.emplace_back();
  1399. auto& row = TableData.back();
  1400. row.emplace_back();
  1401. TString& groups = row.back();
  1402. bool first = true;
  1403. for (const char* const* i = probe->Event.Groups; *i != nullptr; ++i, first = false) {
  1404. groups.append(TString(first? "": ", ") + GroupHtml(*i));
  1405. }
  1406. row.push_back(ProbeHtml(probe->Event.GetProvider(), probe->Event.Name));
  1407. row.emplace_back();
  1408. TString& params = row.back();
  1409. first = true;
  1410. for (size_t i = 0; i < probe->Event.Signature.ParamCount; i++, first = false) {
  1411. params.append(TString(first? "": ", ") + probe->Event.Signature.ParamTypes[i]
  1412. + " " + probe->Event.Signature.ParamNames[i]);
  1413. }
  1414. row.emplace_back(ToString(probe->GetExecutorsCount()));
  1415. }
  1416. void Output(IOutputStream& os)
  1417. {
  1418. HTML(os) {
  1419. TABLE() {
  1420. TABLEHEAD() {
  1421. TABLEH() { os << "Groups"; }
  1422. TABLEH() { os << "Name"; }
  1423. TABLEH() { os << "Params"; }
  1424. TABLEH() { os << "ExecCount"; }
  1425. }
  1426. TABLEBODY() {
  1427. for (auto& row : TableData) {
  1428. TABLER() {
  1429. for (TString& cell : row) {
  1430. TABLED() { os << cell; }
  1431. }
  1432. }
  1433. }
  1434. }
  1435. }
  1436. }
  1437. }
  1438. private:
  1439. TString GroupHtml(const TString& group)
  1440. {
  1441. TStringStream ss;
  1442. ss << "<div class=\"dropdown\" style=\"display:inline-block\">"
  1443. "<a href=\"#\" data-toggle=\"dropdown\">" << group << "</a>"
  1444. "<ul class=\"dropdown-menu\">"
  1445. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1446. "{id:'" << TAdHocTraceConfig(group).Id() << "'});\">"
  1447. "Trace 1000 items</a></li>"
  1448. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1449. "{id:'" << TAdHocTraceConfig(group, 10000).Id() << "'});\">"
  1450. "Trace 10000 items</a></li>"
  1451. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1452. "{id:'" << TAdHocTraceConfig(group, 0, 1000000).Id() << "'});\">"
  1453. "Trace 1 second</a></li>"
  1454. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1455. "{id:'" << TAdHocTraceConfig(group, 0, 10000000).Id() << "'});\">"
  1456. "Trace 10 seconds</a></li>"
  1457. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1458. "{id:'" << TAdHocTraceConfig(group, 0, 0, true).Id() << "'});\">"
  1459. "Trace 1000 tracks</a></li>"
  1460. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1461. "{id:'" << TAdHocTraceConfig(group, 10000, 0, true).Id() << "'});\">"
  1462. "Trace 10000 tracks</a></li>"
  1463. "</ul>"
  1464. "</div>";
  1465. return ss.Str();
  1466. }
  1467. TString ProbeHtml(const TString& provider, const TString& probe)
  1468. {
  1469. TStringStream ss;
  1470. ss << "<div class=\"dropdown\">"
  1471. "<a href=\"#\" data-toggle=\"dropdown\">" << probe << "</a>"
  1472. "<ul class=\"dropdown-menu\">"
  1473. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1474. "{id:'" << TAdHocTraceConfig(provider, probe).Id() << "'});\">"
  1475. "Trace 1000 items</a></li>"
  1476. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1477. "{id:'" << TAdHocTraceConfig(provider, probe, 10000).Id() << "'});\">"
  1478. "Trace 10000 items</a></li>"
  1479. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1480. "{id:'" << TAdHocTraceConfig(provider, probe, 0, 1000000).Id() << "'});\">"
  1481. "Trace 1 second</a></li>"
  1482. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1483. "{id:'" << TAdHocTraceConfig(provider, probe, 0, 10000000).Id() << "'});\">"
  1484. "Trace 10 seconds</a></li>"
  1485. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1486. "{id:'" << TAdHocTraceConfig(provider, probe, 0, 0, true).Id() << "'});\">"
  1487. "Trace 1000 tracks</a></li>"
  1488. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=new&ui=y&timeout=" << TimeoutSec << "',"
  1489. "{id:'" << TAdHocTraceConfig(provider, probe, 10000, 0, true).Id() << "'});\">"
  1490. "Trace 10000 tracks</a></li>"
  1491. "</ul>"
  1492. "</div>";
  1493. return ss.Str();
  1494. }
  1495. };
  1496. void TDashboardRegistry::Register(const NLWTrace::TDashboard& dashboard) {
  1497. TGuard<TMutex> g(Mutex);
  1498. Dashboards[dashboard.GetName()] = dashboard;
  1499. }
  1500. void TDashboardRegistry::Register(const TVector<NLWTrace::TDashboard>& dashboards) {
  1501. for (const auto& dashboard : dashboards) {
  1502. Register(dashboard);
  1503. }
  1504. }
  1505. void TDashboardRegistry::Register(const TString& dashText) {
  1506. NLWTrace::TDashboard dash;
  1507. if (!google::protobuf::TextFormat::ParseFromString(dashText, &dash)) {
  1508. ythrow yexception() << "Couldn't parse into dashboard";
  1509. }
  1510. Register(dash);
  1511. }
  1512. bool TDashboardRegistry::Get(const TString& name, NLWTrace::TDashboard& dash) {
  1513. TGuard<TMutex> g(Mutex);
  1514. if (!Dashboards.contains(name)) {
  1515. return false;
  1516. }
  1517. dash = Dashboards[name];
  1518. return true;
  1519. }
  1520. void TDashboardRegistry::Output(TStringStream& ss) {
  1521. HTML(ss) {
  1522. TABLE() {
  1523. TABLEHEAD() {
  1524. TABLEH() { ss << "Name"; }
  1525. }
  1526. TABLEBODY() {
  1527. TGuard<TMutex> g(Mutex);
  1528. for (auto& kv : Dashboards) {
  1529. const auto& dash = kv.second;
  1530. TABLER() {
  1531. TABLED() {
  1532. ss << "<a href='?mode=dashboard&name=" << dash.GetName() << "'>" << dash.GetName() << "</a>";
  1533. }
  1534. }
  1535. }
  1536. }
  1537. }
  1538. }
  1539. }
  1540. class ILogSource {
  1541. public:
  1542. virtual ~ILogSource() {}
  1543. virtual TString GetId() = 0;
  1544. virtual TInstant GetStartTime() = 0;
  1545. virtual TDuration GetTimeout(TInstant now) = 0;
  1546. virtual ui64 GetEventsCount() = 0;
  1547. virtual ui64 GetThreadsCount() = 0;
  1548. };
  1549. class TTraceLogSource : public ILogSource {
  1550. private:
  1551. TString Id;
  1552. const TTraceCleaner& Cleaner;
  1553. const NLWTrace::TSession* Trace;
  1554. public:
  1555. TTraceLogSource(const TString& id, const NLWTrace::TSession* trace, const TTraceCleaner& cleaner)
  1556. : Id(id)
  1557. , Cleaner(cleaner)
  1558. , Trace(trace)
  1559. {}
  1560. TString GetId() override
  1561. {
  1562. return Id;
  1563. }
  1564. TInstant GetStartTime() override
  1565. {
  1566. return Trace->GetStartTime();
  1567. }
  1568. TDuration GetTimeout(TInstant now) override
  1569. {
  1570. TInstant deadline = Cleaner.GetDeadline(Id);
  1571. if (deadline < now) {
  1572. return TDuration::Zero();
  1573. } else if (deadline == TInstant::Max()) {
  1574. return TDuration::Max();
  1575. } else {
  1576. return deadline - now;
  1577. }
  1578. }
  1579. ui64 GetEventsCount() override
  1580. {
  1581. return Trace->GetEventsCount();
  1582. }
  1583. ui64 GetThreadsCount() override
  1584. {
  1585. return Trace->GetThreadsCount();
  1586. }
  1587. };
  1588. class TSnapshotLogSource : public ILogSource {
  1589. private:
  1590. TString Sid;
  1591. // Log should be used for read-only purpose, because it can be accessed from multiple threads
  1592. // Atomic pointer is used to avoid thread-safety issues with snapshot deletion
  1593. // (I hope protobuf const-implementation doesn't use any mutable non-thread-safe stuff inside)
  1594. TAtomicSharedPtr<NLWTrace::TLogPb> Log;
  1595. public:
  1596. // Constructor should be called under SnapshotsMtx lock
  1597. TSnapshotLogSource(const TString& sid, const TAtomicSharedPtr<NLWTrace::TLogPb>& log)
  1598. : Sid(sid)
  1599. , Log(log)
  1600. {}
  1601. TString GetId() override
  1602. {
  1603. return Sid + "~";
  1604. }
  1605. TInstant GetStartTime() override
  1606. {
  1607. return TInstant::MicroSeconds(Log->GetCrtTime());
  1608. }
  1609. TDuration GetTimeout(TInstant now) override
  1610. {
  1611. Y_UNUSED(now);
  1612. return TDuration::Max();
  1613. }
  1614. ui64 GetEventsCount() override
  1615. {
  1616. return Log->GetEventsCount();
  1617. }
  1618. ui64 GetThreadsCount() override
  1619. {
  1620. return Log->ThreadLogsSize();
  1621. }
  1622. };
  1623. class TLogSources {
  1624. private:
  1625. TTraceCleaner& Cleaner;
  1626. TInstant Now;
  1627. using TLogSourcePtr = std::unique_ptr<ILogSource>;
  1628. TMap<TString, TLogSourcePtr> LogSources;
  1629. public:
  1630. explicit TLogSources(TTraceCleaner& cleaner, TInstant now = TInstant::Now())
  1631. : Cleaner(cleaner)
  1632. , Now(now)
  1633. {}
  1634. void Push(const TString& sid, const TAtomicSharedPtr<NLWTrace::TLogPb>& log)
  1635. {
  1636. TLogSourcePtr ls(new TSnapshotLogSource(sid, log));
  1637. LogSources.emplace(ls->GetId(), std::move(ls));
  1638. }
  1639. void Push(const TString& id, const NLWTrace::TSession* trace)
  1640. {
  1641. TLogSourcePtr ls(new TTraceLogSource(id, trace, Cleaner));
  1642. LogSources.emplace(ls->GetId(), std::move(ls));
  1643. }
  1644. template <class TFunc>
  1645. void ForEach(TFunc& func)
  1646. {
  1647. for (auto& kv : LogSources) {
  1648. func.Push(kv.second.get());
  1649. }
  1650. }
  1651. template <class TFunc>
  1652. void ForEach(TFunc& func) const
  1653. {
  1654. for (const auto& kv : LogSources) {
  1655. func.Push(kv.second.get());
  1656. }
  1657. }
  1658. };
  1659. class TTracesHtmlPrinter {
  1660. private:
  1661. IOutputStream& Os;
  1662. TInstant Now;
  1663. public:
  1664. explicit TTracesHtmlPrinter(IOutputStream& os)
  1665. : Os(os)
  1666. , Now(TInstant::Now())
  1667. {}
  1668. void Push(ILogSource* src)
  1669. {
  1670. TString id = src->GetId();
  1671. Os << "<tr>";
  1672. Os << "<td>";
  1673. try {
  1674. Os << src->GetStartTime().ToStringUpToSeconds();
  1675. } catch (...) {
  1676. Os << "error: " << CurrentExceptionMessage();
  1677. }
  1678. Os << "</td>"
  1679. << "<td><div class=\"dropdown\">"
  1680. "<a href=\"#\" data-toggle=\"dropdown\">" << TimeoutToString(src->GetTimeout(Now)) << "</a>"
  1681. "<ul class=\"dropdown-menu\">"
  1682. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=settimeout&ui=y&timeout=60', {id:'" << id << "'});\">1 min</a></li>"
  1683. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=settimeout&ui=y&timeout=600', {id:'" << id << "'});\">10 min</a></li>"
  1684. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=settimeout&ui=y&timeout=3600', {id:'" << id << "'});\">1 hour</a></li>"
  1685. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=settimeout&ui=y&timeout=86400', {id:'" << id << "'});\">1 day</a></li>"
  1686. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=settimeout&ui=y&timeout=604800', {id:'" << id << "'});\">1 week</a></li>"
  1687. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=settimeout&ui=y', {id:'" << id << "'});\">no timeout</a></li>"
  1688. "</ul>"
  1689. "</div></td>"
  1690. << "<td>" << EncodeHtmlPcdata(id) << "</td>"
  1691. << "<td>" << src->GetEventsCount() << "</td>"
  1692. << "<td>" << src->GetThreadsCount() << "</td>"
  1693. << "<td><a href=\"?mode=log&id=" << id << "\">Text</a></td>"
  1694. << "<td><a href=\"?mode=log&format=json&id=" << id << "\">Json</a></td>"
  1695. << "<td><a href=\"?mode=query&id=" << id << "\">Query</a></td>"
  1696. << "<td><a href=\"?mode=analytics&id=" << id << "\">Analytics</a></td>"
  1697. << "<td><div class=\"dropdown navbar-right\">" // navbar-right is hack to drop left
  1698. "<a href=\"#\" data-toggle=\"dropdown\">Modify</a>"
  1699. "<ul class=\"dropdown-menu\">"
  1700. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=make_snapshot&ui=y', {id:'" << id << "'});\">Snapshot</a></li>"
  1701. "<li><a href=\"#\" onClick=\"$.redirectPost('?mode=delete&ui=y', {id:'" << id << "'});\">Delete</a></li>"
  1702. "</ul>"
  1703. "</div></td>"
  1704. << "</tr>\n";
  1705. }
  1706. private:
  1707. static TString TimeoutToString(TDuration d)
  1708. {
  1709. TStringStream ss;
  1710. if (d == TDuration::Zero()) {
  1711. ss << "0";
  1712. } else if (d == TDuration::Max()) {
  1713. ss << "-";
  1714. } else {
  1715. ui64 us = d.GetValue();
  1716. ui64 ms = us / 1000;
  1717. ui64 sec = ms / 1000;
  1718. ui64 min = sec / 60;
  1719. ui64 hours = min / 60;
  1720. ui64 days = hours / 24;
  1721. ui64 weeks = days / 7;
  1722. us -= ms * 1000;
  1723. ms -= sec * 1000;
  1724. sec -= min * 60;
  1725. min -= hours * 60;
  1726. hours -= days * 24;
  1727. days -= weeks * 7;
  1728. int terms = 0;
  1729. if ((terms > 0 && terms < 2) || ( terms == 0 && weeks)) { ss << (ss.Str()? " ": "") << weeks << "w"; terms++; }
  1730. if ((terms > 0 && terms < 2) || ( terms == 0 && days)) { ss << (ss.Str()? " ": "") << days << "d"; terms++; }
  1731. if ((terms > 0 && terms < 2) || ( terms == 0 && hours)) { ss << (ss.Str()? " ": "") << hours << "h"; terms++; }
  1732. if ((terms > 0 && terms < 2) || ( terms == 0 && min)) { ss << (ss.Str()? " ": "") << min << "m"; terms++; }
  1733. if ((terms > 0 && terms < 2) || ( terms == 0 && sec)) { ss << (ss.Str()? " ": "") << sec << "s"; terms++; }
  1734. if ((terms > 0 && terms < 2) || ( terms == 0 && ms)) { ss << (ss.Str()? " ": "") << ms << "ms"; terms++; }
  1735. if ((terms > 0 && terms < 2) || ( terms == 0 && us)) { ss << (ss.Str()? " ": "") << us << "us"; terms++; }
  1736. }
  1737. return ss.Str();
  1738. }
  1739. };
  1740. class TTracesLister {
  1741. private:
  1742. TVariants& Variants;
  1743. public:
  1744. TTracesLister(TVariants& variants)
  1745. : Variants(variants)
  1746. {}
  1747. void Push(ILogSource* src)
  1748. {
  1749. Variants.emplace_back(src->GetId(), src->GetId());
  1750. }
  1751. };
  1752. TVariants ListTraces(const TLogSources& srcs)
  1753. {
  1754. TVariants variants;
  1755. TTracesLister lister(variants);
  1756. srcs.ForEach(lister);
  1757. return variants;
  1758. }
  1759. class TTimestampCutter {
  1760. private:
  1761. THashMap<TThread::TId, std::pair<ui64, TInstant>> CutTsForThread; // tid -> time of first item
  1762. mutable ui64 CutTsMax = 0;
  1763. mutable TInstant CutInstantMax;
  1764. bool Enabled;
  1765. ui64 NowTs;
  1766. public:
  1767. explicit TTimestampCutter(bool enabled)
  1768. : Enabled(enabled)
  1769. , NowTs(GetCycleCount())
  1770. {}
  1771. void Push(TThread::TId tid, const NLWTrace::TLogItem& item)
  1772. {
  1773. auto it = CutTsForThread.find(tid);
  1774. if (it != CutTsForThread.end()) {
  1775. ui64& ts = it->second.first;
  1776. TInstant& inst = it->second.second;
  1777. ts = Min(ts, item.TimestampCycles);
  1778. inst = Min(inst, item.Timestamp);
  1779. } else {
  1780. CutTsForThread[tid] = std::make_pair(item.TimestampCycles, item.Timestamp);
  1781. }
  1782. }
  1783. // Timestamp from which we are ensured that cyclic log for every thread is not truncated
  1784. // NOTE: should NOT be called from Push(tid, item) functions
  1785. ui64 StartTimestamp() const
  1786. {
  1787. if (CutTsMax == 0) {
  1788. FindStartTime();
  1789. }
  1790. return CutTsMax;
  1791. }
  1792. ui64 NowTimestamp() const
  1793. {
  1794. return NowTs;
  1795. }
  1796. TInstant StartInstant() const
  1797. {
  1798. if (CutInstantMax == TInstant::Zero()) {
  1799. FindStartTime();
  1800. }
  1801. return CutInstantMax;
  1802. }
  1803. // Returns true iff item should be skipped to avoid surprizes
  1804. bool Skip(const NLWTrace::TLogItem& item) const
  1805. {
  1806. return Enabled && item.TimestampCycles < StartTimestamp();
  1807. }
  1808. private:
  1809. void FindStartTime() const
  1810. {
  1811. for (auto& kv : CutTsForThread) {
  1812. CutTsMax = Max(CutTsMax, kv.second.first);
  1813. CutInstantMax = Max(CutInstantMax, kv.second.second);
  1814. }
  1815. }
  1816. };
  1817. class TLogFilter {
  1818. private:
  1819. struct TFilter {
  1820. TString ParamName;
  1821. TString ParamValue;
  1822. bool Parsed;
  1823. TLogQuery Query;
  1824. NLWTrace::TLiteral Value;
  1825. explicit TFilter(const TString& text)
  1826. {
  1827. if (!text) { // Neither ParamName nor ParamValue is selected
  1828. ParamName.clear();
  1829. ParamValue.clear();
  1830. Parsed = false;
  1831. return;
  1832. }
  1833. size_t pos = text.find('=');
  1834. if (pos == TString::npos) { // Only ParamName has been selected
  1835. ParamName = text;
  1836. ParamValue.clear();
  1837. Parsed = false;
  1838. return;
  1839. }
  1840. // Both ParamName and ParamValue have been selected
  1841. ParamValue = text.substr(pos + 1);
  1842. ParamName = text.substr(0, pos);
  1843. Parsed = true;
  1844. Query = TLogQuery(ParamName);
  1845. Value = NLWTrace::TLiteral(ParamValue);
  1846. }
  1847. };
  1848. TVector<TFilter> Filters;
  1849. THashSet<const NLWTrace::TSignature*> Signatures; // Just to list param names
  1850. TVariants ParamNames;
  1851. THashMap<TString, THashSet<TString>> FilteredParamValues; // paramName -> { paramValue }
  1852. public:
  1853. explicit TLogFilter(const TVector<TString>& filters)
  1854. {
  1855. for (const TString& subvalue : filters) {
  1856. TFilter filter(subvalue);
  1857. FilteredParamValues[filter.ParamName]; // just create empty set to gather values later
  1858. if (filter.Parsed) {
  1859. Filters.push_back(filter);
  1860. }
  1861. }
  1862. }
  1863. virtual ~TLogFilter() {}
  1864. template <class TLog>
  1865. bool Filter(const TLog& log)
  1866. {
  1867. Gather(log);
  1868. for (const TFilter& filter : Filters) {
  1869. if (filter.Query.ExecuteQuery(log) != filter.Value) {
  1870. return false;
  1871. }
  1872. }
  1873. return true;
  1874. }
  1875. void FilterSelectors(TStringStream& ss, const TCgiParameters& e, const TString& fparam)
  1876. {
  1877. bool first = true;
  1878. bool allParsed = true;
  1879. for (const TString& subvalue : Subvalues(e, fparam)) {
  1880. TFilter filter(subvalue);
  1881. allParsed = allParsed && filter.Parsed;
  1882. if (first) {
  1883. SelectorTitle(ss, "where");
  1884. }
  1885. DropdownSelector<Erasable | CompositeValue, true>(
  1886. ss, e, fparam, subvalue, first? "": ", ", ListParamNames(),
  1887. filter.ParamName
  1888. );
  1889. if (filter.ParamName) {
  1890. DropdownSelector<Link | CompositeValue, true>(
  1891. ss, e, fparam, subvalue, "=", ListParamValues(filter.ParamName),
  1892. filter.ParamValue? (filter.ParamName + "=" + filter.ParamValue): ""
  1893. );
  1894. }
  1895. first = false;
  1896. }
  1897. if (!allParsed) {
  1898. throw TPageGen<TSelectorsContainer>(ss.Str());
  1899. } else {
  1900. BtnHref<Button|ExtraSmall>(ss, first? "where": "+", MakeUrlAddSub(e, fparam, ""));
  1901. }
  1902. }
  1903. const TVariants& ListParamNames()
  1904. {
  1905. if (ParamNames.empty()) {
  1906. THashSet<TString> paramNames;
  1907. for (const NLWTrace::TSignature* sgn: Signatures) {
  1908. for (size_t pi = 0; pi < sgn->ParamCount; pi++) {
  1909. paramNames.insert(sgn->ParamNames[pi]);
  1910. }
  1911. }
  1912. for (auto& pn : paramNames) {
  1913. ParamNames.emplace_back(pn, pn);
  1914. }
  1915. }
  1916. return ParamNames;
  1917. }
  1918. bool IsFiltered(const TString& paramName) const
  1919. {
  1920. return FilteredParamValues.contains(paramName);
  1921. }
  1922. private:
  1923. // Gather param names and values for selectors
  1924. void Gather(const NLWTrace::TLogItem& item)
  1925. {
  1926. Signatures.insert(&item.Probe->Event.Signature);
  1927. if (!FilteredParamValues.empty() && item.SavedParamsCount > 0) {
  1928. TString paramValues[LWTRACE_MAX_PARAMS];
  1929. item.Probe->Event.Signature.SerializeParams(item.Params, paramValues);
  1930. for (size_t pi = 0; pi < item.SavedParamsCount; pi++) {
  1931. auto iter = FilteredParamValues.find(item.Probe->Event.Signature.ParamNames[pi]);
  1932. if (iter != FilteredParamValues.end()) {
  1933. iter->second.insert(paramValues[pi]);
  1934. }
  1935. }
  1936. }
  1937. }
  1938. void Gather(const NLWTrace::TTrackLog& tl)
  1939. {
  1940. for (const NLWTrace::TLogItem& item : tl.Items) {
  1941. Gather(item);
  1942. }
  1943. }
  1944. TVariants ListParamValues(const TString& paramName) const
  1945. {
  1946. TVariants result;
  1947. auto iter = FilteredParamValues.find(paramName);
  1948. if (iter != FilteredParamValues.end()) {
  1949. for (const TString& paramValue : iter->second) {
  1950. result.emplace_back(paramName + "=" + paramValue, paramValue);
  1951. }
  1952. }
  1953. Sort(result.begin(), result.end());
  1954. return result;
  1955. }
  1956. };
  1957. static void EscapeJSONString(IOutputStream& os, const TString& s)
  1958. {
  1959. for (TString::const_iterator i = s.begin(), e = s.end(); i != e; ++i) {
  1960. char c = *i;
  1961. if (c < ' ') {
  1962. os << Sprintf("\\u%04x", int(c));
  1963. } else if (c == '"') {
  1964. os << "\\\"";
  1965. } else if (c == '\\') {
  1966. os << "\\\\";
  1967. } else {
  1968. os << c;
  1969. }
  1970. }
  1971. }
  1972. static TString EscapeJSONString(const TString& s)
  1973. {
  1974. TStringStream ss;
  1975. EscapeJSONString(ss, s);
  1976. return ss.Str();
  1977. }
  1978. class TLogJsonPrinter {
  1979. private:
  1980. IOutputStream& Os;
  1981. bool FirstThread;
  1982. bool FirstItem;
  1983. public:
  1984. explicit TLogJsonPrinter(IOutputStream& os)
  1985. : Os(os)
  1986. , FirstThread(true)
  1987. , FirstItem(true)
  1988. {}
  1989. void OutputHeader()
  1990. {
  1991. Os << "{\n\t\"source\": \"" << HostName() << "\""
  1992. "\n\t, \"items\": ["
  1993. ;
  1994. }
  1995. void OutputFooter(const NLWTrace::TSession* trace)
  1996. {
  1997. Os << "\n\t\t]"
  1998. "\n\t, \"threads\": ["
  1999. ;
  2000. trace->ReadThreads(*this);
  2001. Os << "]"
  2002. "\n\t, \"events_count\": " << trace->GetEventsCount() <<
  2003. "\n\t, \"threads_count\": " << trace->GetThreadsCount() <<
  2004. "\n\t, \"timestamp\": " << Now().GetValue() <<
  2005. "\n}"
  2006. ;
  2007. }
  2008. void PushThread(TThread::TId tid)
  2009. {
  2010. Os << (FirstThread? "": ", ") << tid;
  2011. FirstThread = false;
  2012. }
  2013. void Push(TThread::TId tid, const NLWTrace::TLogItem& item)
  2014. {
  2015. Os << "\n\t\t" << (FirstItem? "": ", ");
  2016. FirstItem = false;
  2017. Os << "[" << tid <<
  2018. ", " << item.Timestamp.GetValue() <<
  2019. ", \"" << item.Probe->Event.GetProvider() << "\""
  2020. ", \"" << item.Probe->Event.Name << "\""
  2021. ", {"
  2022. ;
  2023. if (item.SavedParamsCount > 0) {
  2024. TString ParamValues[LWTRACE_MAX_PARAMS];
  2025. item.Probe->Event.Signature.SerializeParams(item.Params, ParamValues);
  2026. bool first = true;
  2027. for (size_t i = 0; i < item.SavedParamsCount; i++, first = false) {
  2028. Os << (first? "": ", ") << "\"" << item.Probe->Event.Signature.ParamNames[i] << "\": \"";
  2029. EscapeJSONString(Os, ParamValues[i]);
  2030. Os << "\"";
  2031. }
  2032. }
  2033. Os << "}]";
  2034. }
  2035. };
  2036. class TLogTextPrinter : public TLogFilter {
  2037. private:
  2038. TMultiMap<NLWTrace::TTypedParam, std::pair<TThread::TId, NLWTrace::TLogItem> > Items;
  2039. TMultiMap<NLWTrace::TTypedParam, NLWTrace::TTrackLog> Depot;
  2040. THashMap<NLWTrace::TProbe*, size_t> ProbeId;
  2041. TVector<NLWTrace::TProbe*> Probes;
  2042. TTimestampCutter CutTs;
  2043. TLogQuery Order;
  2044. bool ReverseOrder = false;
  2045. ui64 Head = 0;
  2046. ui64 Tail = 0;
  2047. bool ShowTs = false;
  2048. public:
  2049. TLogTextPrinter(const TVector<TString>& filters, ui64 head, ui64 tail, const TString& order, bool reverseOrder, bool cutTs, bool showTs)
  2050. : TLogFilter(filters)
  2051. , CutTs(cutTs)
  2052. , Order(order)
  2053. , ReverseOrder(reverseOrder)
  2054. , Head(head)
  2055. , Tail(tail)
  2056. , ShowTs(showTs)
  2057. {}
  2058. TLogTextPrinter(const TCgiParameters& e)
  2059. : TLogTextPrinter(
  2060. Subvalues(e, "f"),
  2061. e.Has("head")? FromString<ui64>(e.Get("head")): 0,
  2062. e.Has("tail")? FromString<ui64>(e.Get("tail")): 0,
  2063. e.Get("s"),
  2064. e.Get("reverse") == "y",
  2065. e.Get("cutts") == "y",
  2066. e.Get("showts") == "y")
  2067. {}
  2068. enum EFormat {
  2069. Text,
  2070. Json
  2071. };
  2072. void Output(IOutputStream& os) const
  2073. {
  2074. OutputItems<Text>(os);
  2075. OutputDepot<Text>(os);
  2076. }
  2077. void OutputJson(IOutputStream& os) const
  2078. {
  2079. os << "{\"depot\":[\n";
  2080. OutputItems<Json>(os);
  2081. OutputDepot<Json>(os);
  2082. os << "],\"probes\":[";
  2083. bool first = true;
  2084. for (const NLWTrace::TProbe* probe : Probes) {
  2085. os << (first? "": ",") << "{\"provider\":\"" << probe->Event.GetProvider()
  2086. << "\",\"name\":\"" << probe->Event.Name << "\"}";
  2087. first = false;
  2088. }
  2089. os << "]}";
  2090. }
  2091. NLWTrace::TTypedParam GetKey(const NLWTrace::TLogItem& item)
  2092. {
  2093. return Order? Order.ExecuteQuery(item): NLWTrace::TTypedParam(item.GetTimestampCycles());
  2094. }
  2095. NLWTrace::TTypedParam GetKey(const NLWTrace::TTrackLog& tl)
  2096. {
  2097. return Order? Order.ExecuteQuery(tl): NLWTrace::TTypedParam(tl.GetTimestampCycles());
  2098. }
  2099. void Push(TThread::TId tid, const NLWTrace::TLogItem& item)
  2100. {
  2101. CutTs.Push(tid, item);
  2102. if (Filter(item)) {
  2103. AddId(item);
  2104. Items.emplace(GetKey(item), std::make_pair(tid, item));
  2105. }
  2106. }
  2107. void Push(TThread::TId tid, const NLWTrace::TTrackLog& tl)
  2108. {
  2109. Y_UNUSED(tid);
  2110. if (Filter(tl)) {
  2111. AddId(tl);
  2112. Depot.emplace(GetKey(tl), tl);
  2113. }
  2114. }
  2115. private:
  2116. void AddId(const NLWTrace::TLogItem& item)
  2117. {
  2118. if (ProbeId.find(item.Probe) == ProbeId.end()) {
  2119. size_t id = Probes.size();
  2120. ProbeId[item.Probe] = id;
  2121. Probes.emplace_back(item.Probe);
  2122. }
  2123. }
  2124. void AddId(const NLWTrace::TTrackLog& tl)
  2125. {
  2126. for (const auto& item : tl.Items) {
  2127. AddId(item);
  2128. }
  2129. }
  2130. bool HeadTailFilter(ui64 idx, ui64 size) const
  2131. {
  2132. bool headOk = idx < Head;
  2133. bool tailOk = size < Tail + idx + 1ull;
  2134. if (Head && Tail) {
  2135. return headOk || tailOk;
  2136. } else if (Head) {
  2137. return headOk;
  2138. } else if (Tail) {
  2139. return tailOk;
  2140. } else {
  2141. return true;
  2142. }
  2143. }
  2144. template <EFormat Format>
  2145. void OutputItems(IOutputStream& os) const
  2146. {
  2147. ui64 idx = 0;
  2148. ui64 size = Items.size();
  2149. ui64 startTs = ShowTs? CutTs.StartTimestamp(): 0;
  2150. ui64 prevTs = 0;
  2151. bool first = true;
  2152. if (!ReverseOrder) {
  2153. for (auto i = Items.begin(), e = Items.end(); i != e; ++i, idx++) {
  2154. if (HeadTailFilter(idx, size)) {
  2155. OutputItem<Format, true>(os, i->second.first, i->second.second, startTs, prevTs, first);
  2156. prevTs = startTs? i->second.second.GetTimestampCycles(): 0;
  2157. }
  2158. }
  2159. } else {
  2160. for (auto i = Items.rbegin(), e = Items.rend(); i != e; ++i, idx++) {
  2161. if (HeadTailFilter(idx, size)) {
  2162. OutputItem<Format, true>(os, i->second.first, i->second.second, startTs, prevTs, first);
  2163. prevTs = startTs? i->second.second.GetTimestampCycles(): 0;
  2164. }
  2165. }
  2166. }
  2167. }
  2168. template <EFormat Format>
  2169. void OutputDepot(IOutputStream& os) const
  2170. {
  2171. ui64 idx = 0;
  2172. ui64 size = Depot.size();
  2173. bool first = true;
  2174. if (!ReverseOrder) {
  2175. for (auto i = Depot.begin(), e = Depot.end(); i != e; ++i, idx++) {
  2176. if (HeadTailFilter(idx, size)) {
  2177. OutputTrackLog<Format>(os, i->second, first);
  2178. }
  2179. }
  2180. } else {
  2181. for (auto i = Depot.rbegin(), e = Depot.rend(); i != e; ++i, idx++) {
  2182. if (HeadTailFilter(idx, size)) {
  2183. OutputTrackLog<Format>(os, i->second, first);
  2184. }
  2185. }
  2186. }
  2187. }
  2188. template <EFormat Format, bool AsTrack = false>
  2189. void OutputItem(IOutputStream& os, TThread::TId tid, const NLWTrace::TLogItem& item, ui64 startTs, ui64 prevTs, bool& first) const
  2190. {
  2191. if (CutTs.Skip(item)) {
  2192. return;
  2193. }
  2194. if constexpr (Format == Text) {
  2195. if (startTs) {
  2196. if (!prevTs) {
  2197. prevTs = item.GetTimestampCycles();
  2198. }
  2199. os << Sprintf("%10.3lf %+10.3lf ms ",
  2200. NHPTimer::GetSeconds(item.GetTimestampCycles() - startTs) * 1000.0,
  2201. NHPTimer::GetSeconds(item.GetTimestampCycles() - prevTs) * 1000.0);
  2202. }
  2203. if (tid) {
  2204. os << "<" << tid << "> ";
  2205. }
  2206. if (item.Timestamp != TInstant::Zero()) {
  2207. os << "[" << item.Timestamp << "] ";
  2208. } else {
  2209. os << "[" << item.TimestampCycles << "] ";
  2210. }
  2211. os << GetProbeName(item.Probe) << "(";
  2212. if (item.SavedParamsCount > 0) {
  2213. TString ParamValues[LWTRACE_MAX_PARAMS];
  2214. item.Probe->Event.Signature.SerializeParams(item.Params, ParamValues);
  2215. bool first = true;
  2216. for (size_t i = 0; i < item.SavedParamsCount; i++, first = false) {
  2217. os << (first? "": ", ") << item.Probe->Event.Signature.ParamNames[i] << "='" << EscapeC(ParamValues[i]) << "'";
  2218. }
  2219. }
  2220. os << ")\n";
  2221. } else if constexpr (Format == Json) {
  2222. if (auto probeId = ProbeId.find(item.Probe); probeId != ProbeId.end()) {
  2223. os << (first? "": ",") << (AsTrack? "[":"") << "[\"" << tid << "\",\"";
  2224. if (item.Timestamp != TInstant::Zero()) {
  2225. os << item.Timestamp.MicroSeconds();
  2226. } else {
  2227. os << Sprintf("%.3lf", NHPTimer::GetSeconds(item.TimestampCycles) * 1e9);
  2228. }
  2229. os << "\"," << probeId->second << ",{";
  2230. if (item.SavedParamsCount > 0) {
  2231. TString ParamValues[LWTRACE_MAX_PARAMS];
  2232. item.Probe->Event.Signature.SerializeParams(item.Params, ParamValues);
  2233. bool first = true;
  2234. for (size_t i = 0; i < item.SavedParamsCount; i++, first = false) {
  2235. os << (first? "": ",") << "\"" << item.Probe->Event.Signature.ParamNames[i] << "\":\"";
  2236. EscapeJSONString(os, ParamValues[i]);
  2237. os << "\"";
  2238. }
  2239. }
  2240. os << "}]" << (AsTrack? "]":"");
  2241. }
  2242. }
  2243. first = false;
  2244. }
  2245. template <EFormat Format>
  2246. void OutputTrackLog(IOutputStream& os, const NLWTrace::TTrackLog& tl, bool& first) const
  2247. {
  2248. if constexpr (Format == Json) {
  2249. os << (first? "": ",") << "[";
  2250. }
  2251. first = false;
  2252. ui64 prevTs = tl.GetTimestampCycles();
  2253. bool firstItem = true;
  2254. for (const NLWTrace::TTrackLog::TItem& item: tl.Items) {
  2255. OutputItem<Format>(os, item.ThreadId, item, tl.GetTimestampCycles(), prevTs, firstItem);
  2256. prevTs = item.GetTimestampCycles();
  2257. }
  2258. if constexpr (Format == Json) {
  2259. os << "]";
  2260. }
  2261. os << "\n";
  2262. }
  2263. };
  2264. class TLogAnalyzer: public TLogFilter {
  2265. private:
  2266. TMultiMap<ui64, std::pair<TThread::TId, NLWTrace::TLogItem>> Items;
  2267. TVector<NLWTrace::TTrackLog> Depot;
  2268. THashMap<TString, TTrackLogRefs> Groups;
  2269. NAnalytics::TTable Table;
  2270. bool TableCreated = false;
  2271. TVector<TString> GroupBy;
  2272. TTimestampCutter CutTs;
  2273. public:
  2274. TLogAnalyzer(const TVector<TString>& filters, const TVector<TString>& groupBy, bool cutTs)
  2275. : TLogFilter(filters)
  2276. , CutTs(cutTs)
  2277. {
  2278. for (const TString& groupParam : groupBy) {
  2279. GroupBy.push_back(groupParam);
  2280. }
  2281. }
  2282. const NAnalytics::TTable& GetTable()
  2283. {
  2284. if (!TableCreated) {
  2285. TableCreated = true;
  2286. if (GroupBy.empty()) {
  2287. for (auto i = Items.begin(), e = Items.end(); i != e; ++i) {
  2288. ParseItems(i->second.first, i->second.second);
  2289. }
  2290. ParseDepot();
  2291. } else {
  2292. for (auto i = Items.begin(), e = Items.end(); i != e; ++i) {
  2293. Map(i->second.first, i->second.second);
  2294. }
  2295. Reduce();
  2296. }
  2297. }
  2298. return Table;
  2299. }
  2300. void Push(TThread::TId tid, const NLWTrace::TLogItem& item)
  2301. {
  2302. CutTs.Push(tid, item);
  2303. if (Filter(item)) {
  2304. Items.emplace(item.TimestampCycles, std::make_pair(tid, item));
  2305. }
  2306. }
  2307. void Push(TThread::TId, const NLWTrace::TTrackLog& tl)
  2308. {
  2309. if (Filter(tl)) {
  2310. Depot.emplace_back(tl);
  2311. }
  2312. }
  2313. private:
  2314. void FillRow(NAnalytics::TRow& row, const NLWTrace::TLogItem& item)
  2315. {
  2316. if (item.SavedParamsCount > 0) {
  2317. TString paramValues[LWTRACE_MAX_PARAMS];
  2318. item.Probe->Event.Signature.SerializeParams(item.Params, paramValues);
  2319. for (size_t i = 0; i < item.SavedParamsCount; i++) {
  2320. double value = FromString<double>(paramValues[i].data(), paramValues[i].size(), NAN);
  2321. // If value cannot be cast to double or is inf/nan -- assume it's a string
  2322. if (isfinite(value)) {
  2323. row[item.Probe->Event.Signature.ParamNames[i]] = value;
  2324. } else {
  2325. row[item.Probe->Event.Signature.ParamNames[i]] = paramValues[i];
  2326. }
  2327. }
  2328. }
  2329. }
  2330. TString GetParam(const NLWTrace::TLogItem& item, TString* paramValues, const TString& paramName)
  2331. {
  2332. for (size_t pi = 0; pi < item.SavedParamsCount; pi++) {
  2333. if (paramName == item.Probe->Event.Signature.ParamNames[pi]) {
  2334. return paramValues[pi];
  2335. }
  2336. }
  2337. return TString();
  2338. }
  2339. TString GetGroup(const NLWTrace::TLogItem& item, TString* paramValues)
  2340. {
  2341. TStringStream ss;
  2342. bool first = true;
  2343. for (const TString& groupParam : GroupBy) {
  2344. ss << (first? "": "|") << GetParam(item, paramValues, groupParam);
  2345. first = false;
  2346. }
  2347. return ss.Str();
  2348. }
  2349. void ParseItems(TThread::TId tid, const NLWTrace::TLogItem& item)
  2350. {
  2351. if (CutTs.Skip(item)) {
  2352. return;
  2353. }
  2354. Table.emplace_back();
  2355. NAnalytics::TRow& row = Table.back();
  2356. row["_thread"] = tid;
  2357. if (item.Timestamp != TInstant::Zero()) {
  2358. row["_wallTime"] = item.Timestamp.SecondsFloat();
  2359. row["_wallRTime"] = item.Timestamp.SecondsFloat() - CutTs.StartInstant().SecondsFloat();
  2360. }
  2361. row["_cycles"] = item.TimestampCycles;
  2362. row["_thrTime"] = CyclesToDuration((ui64)item.TimestampCycles).SecondsFloat();
  2363. row["_thrRTime"] = double(i64(item.TimestampCycles) - i64(CutTs.StartTimestamp())) / NHPTimer::GetCyclesPerSecond();
  2364. row["_thrNTime"] = double(i64(item.TimestampCycles) - i64(CutTs.NowTimestamp())) / NHPTimer::GetCyclesPerSecond();
  2365. row.Name = GetProbeName(item.Probe);
  2366. FillRow(row, item);
  2367. }
  2368. void Map(TThread::TId tid, const NLWTrace::TLogItem& item)
  2369. {
  2370. if (item.SavedParamsCount > 0 && !CutTs.Skip(item)) {
  2371. TString paramValues[LWTRACE_MAX_PARAMS];
  2372. item.Probe->Event.Signature.SerializeParams(item.Params, paramValues);
  2373. TTrackLogRefs& tl = Groups[GetGroup(item, paramValues)];
  2374. tl.Items.emplace_back(tid, item);
  2375. }
  2376. }
  2377. void Reduce()
  2378. {
  2379. for (auto& v : Groups) {
  2380. const TString& group = v.first;
  2381. const TTrackLogRefs& tl = v.second;
  2382. Table.emplace_back();
  2383. NAnalytics::TRow& row = Table.back();
  2384. row.Name = group;
  2385. for (const NLWTrace::TLogItem& item : tl.Items) {
  2386. FillRow(row, item);
  2387. }
  2388. }
  2389. }
  2390. void ParseDepot()
  2391. {
  2392. for (NLWTrace::TTrackLog& tl : Depot) {
  2393. Table.emplace_back();
  2394. NAnalytics::TRow& row = Table.back();
  2395. for (const NLWTrace::TLogItem& item : tl.Items) {
  2396. FillRow(row, item);
  2397. }
  2398. }
  2399. }
  2400. };
  2401. struct TSampleOpts {
  2402. bool ShowProvider = false;
  2403. size_t SizeLimit = 50;
  2404. };
  2405. enum ENodeType {
  2406. NT_ROOT,
  2407. NT_PROBE,
  2408. NT_PARAM
  2409. };
  2410. class TPatternTree;
  2411. struct TPatternNode;
  2412. struct TTrack : public TTrackLogRefs {
  2413. TString TrackId;
  2414. TPatternNode* LastNode = nullptr;
  2415. };
  2416. using TTrackTr = TLogTraits<TTrackLogRefs>;
  2417. using TTrackIter = TTrackTr::const_iterator;
  2418. // Visitor for tree traversing
  2419. class IVisitor {
  2420. public:
  2421. virtual ~IVisitor() {}
  2422. virtual void Visit(TPatternNode* node) = 0;
  2423. };
  2424. // Per-node classifier
  2425. class TClassifier {
  2426. public:
  2427. explicit TClassifier(TPatternNode* node, ENodeType childType, bool keepHead = false)
  2428. : Node(node)
  2429. , KeepHead(keepHead)
  2430. , ChildType(childType)
  2431. {}
  2432. virtual ~TClassifier() {}
  2433. virtual TPatternNode* Classify(TTrackIter cur, const TTrack& track) = 0;
  2434. virtual void Accept(IVisitor* visitor) = 0;
  2435. virtual bool IsLeaf() = 0;
  2436. ENodeType GetChildType() const { return ChildType; }
  2437. public:
  2438. TPatternNode* Node;
  2439. const bool KeepHead;
  2440. ENodeType ChildType;
  2441. };
  2442. // Track classification tree node
  2443. struct TPatternNode {
  2444. TString Name;
  2445. TPatternNode* Parent = nullptr;
  2446. THolder<TClassifier> Classifier;
  2447. struct TDesc {
  2448. ENodeType Type = NT_ROOT;
  2449. // NT_PROBE
  2450. const NLWTrace::TProbe* Probe = nullptr;
  2451. // NT_PARAM
  2452. size_t Rollbacks = 0;
  2453. TString ParamName;
  2454. TString ParamValue;
  2455. } Desc;
  2456. ui64 TrackCount = 0;
  2457. struct TTrackEntry {
  2458. TTrack* Track;
  2459. ui64 ResTotal;
  2460. ui64 ResLast;
  2461. TTrackEntry(TTrack* track, ui64 resTotal, ui64 resLast)
  2462. : Track(track)
  2463. , ResTotal(resTotal)
  2464. , ResLast(resLast)
  2465. {}
  2466. };
  2467. TVector<TTrackEntry> Tracks;
  2468. ui64 ResTotalSum = 0;
  2469. ui64 ResTotalMax = 0;
  2470. TVector<ui64> ResTotalAll;
  2471. ui64 ResLastSum = 0;
  2472. ui64 ResLastMax = 0;
  2473. TVector<ui64> ResLastAll;
  2474. TVector<ui64> TimelineSum;
  2475. NAnalytics::TTable Slices;
  2476. TString GetPath() const
  2477. {
  2478. if (Parent) {
  2479. return Parent->GetPath() + Name;
  2480. }
  2481. return "/";
  2482. }
  2483. NAnalytics::TTable GetTable() const
  2484. {
  2485. using namespace NAnalytics;
  2486. NAnalytics::TTable ret;
  2487. for (ui64 x : ResTotalAll) {
  2488. ret.emplace_back();
  2489. TRow& row = ret.back();
  2490. row["resTotal"] = double(x) * 1000.0 / NHPTimer::GetClockRate();
  2491. }
  2492. for (ui64 x : ResLastAll) {
  2493. ret.emplace_back();
  2494. TRow& row = ret.back();
  2495. row["resLast"] = double(x) * 1000.0 / NHPTimer::GetClockRate();
  2496. }
  2497. return ret;
  2498. }
  2499. template <typename TReader>
  2500. void OutputSample(const TString& bn, double b1, double b2, const TSampleOpts& opts, TReader& reader) const
  2501. {
  2502. bool filterTotal = false;
  2503. if (bn == "resTotal") {
  2504. filterTotal = true;
  2505. } else {
  2506. WWW_CHECK(bn == "resLast", "wrong sample filter param: %s", bn.data());
  2507. }
  2508. size_t spaceLeft = opts.SizeLimit;
  2509. for (const TTrackEntry& entry : Tracks) {
  2510. const TTrack* track = entry.Track;
  2511. // Filter out tracks that are not in sample
  2512. if (filterTotal) {
  2513. double resTotalMs = double(entry.ResTotal) * 1000.0 / NHPTimer::GetClockRate();
  2514. if (resTotalMs < b1 || resTotalMs > b2) {
  2515. continue;
  2516. }
  2517. } else {
  2518. double resLastMs = double(entry.ResLast) * 1000.0 / NHPTimer::GetClockRate();
  2519. if (resLastMs < b1 || resLastMs > b2) {
  2520. continue;
  2521. }
  2522. }
  2523. NLWTrace::TTrackLog tl;
  2524. for (TTrackIter i = TTrackTr::begin(*track), e = TTrackTr::end(*track); i != e; ++i) {
  2525. const NLWTrace::TLogItem& item = *i;
  2526. const auto threadId = i->ThreadId;
  2527. tl.Items.push_back(NLWTrace::TTrackLog::TItem(threadId, item));
  2528. }
  2529. reader.Push(0, tl);
  2530. if (spaceLeft) {
  2531. spaceLeft--;
  2532. if (!spaceLeft) {
  2533. break;
  2534. }
  2535. }
  2536. }
  2537. }
  2538. };
  2539. // Track classification tree
  2540. class TPatternTree {
  2541. public:
  2542. // Per-node classifier by probe name
  2543. class TClassifyByProbe : public TClassifier {
  2544. private:
  2545. using TChildren = THashMap<NLWTrace::TProbe*, TPatternNode>;
  2546. TChildren Children;
  2547. TVector<TChildren::value_type*> SortedChildren;
  2548. public:
  2549. explicit TClassifyByProbe(TPatternNode* node)
  2550. : TClassifier(node, NT_PROBE)
  2551. {}
  2552. TPatternNode* Classify(TTrackIter cur, const TTrack& track) override
  2553. {
  2554. Y_UNUSED(track);
  2555. const NLWTrace::TLogItem& item = *cur;
  2556. TPatternNode* node = &Children[item.Probe];
  2557. node->Name = "/" + GetProbeName(item.Probe);
  2558. node->Desc.Type = NT_PROBE;
  2559. node->Desc.Probe = item.Probe;
  2560. return node;
  2561. }
  2562. void Accept(IVisitor* visitor) override
  2563. {
  2564. if (SortedChildren.size() != Children.size()) {
  2565. SortedChildren.clear();
  2566. SortedChildren.reserve(Children.size());
  2567. for (auto i = Children.begin(), e = Children.end(); i != e; ++i) {
  2568. SortedChildren.push_back(&*i);
  2569. }
  2570. Sort(SortedChildren, [] (TChildren::value_type* lhs, TChildren::value_type* rhs) {
  2571. NLWTrace::TProbe* lp = lhs->first;
  2572. NLWTrace::TProbe* rp = rhs->first;
  2573. if (int cmp = strcmp(lp->Event.GetProvider(), rp->Event.GetProvider())) {
  2574. return cmp < 0;
  2575. }
  2576. return strcmp(lp->Event.Name, rp->Event.Name) < 0;
  2577. });
  2578. }
  2579. for (auto* kv : SortedChildren) {
  2580. visitor->Visit(&kv->second);
  2581. }
  2582. }
  2583. bool IsLeaf() override { return Children.empty(); }
  2584. };
  2585. // Per-node classifier by probe param value
  2586. class TClassifyByParam : public TClassifier {
  2587. private:
  2588. size_t Rollbacks; // How many items should we look back in track to locate probe
  2589. TString ParamName;
  2590. using TChildren = THashMap<TString, TPatternNode>;
  2591. TChildren Children;
  2592. TVector<TChildren::value_type*> SortedChildren;
  2593. public:
  2594. TClassifyByParam(TPatternNode* node, size_t rollbacks, const TString& paramName)
  2595. : TClassifier(node, NT_PARAM, true)
  2596. , Rollbacks(rollbacks)
  2597. , ParamName(paramName)
  2598. {}
  2599. TPatternNode* Classify(TTrackIter cur, const TTrack& track) override
  2600. {
  2601. WWW_CHECK((i64)Rollbacks >= 0 && std::distance(TTrackTr::begin(track), cur) >= (i64)Rollbacks, "wrong rollbacks in node '%s'",
  2602. Node->GetPath().data());
  2603. const NLWTrace::TLogItem& item = *(cur - Rollbacks);
  2604. WWW_CHECK(item.SavedParamsCount > 0, "classify by params on probe w/o param loggging in node '%s'",
  2605. Node->GetPath().data());
  2606. TString paramValues[LWTRACE_MAX_PARAMS];
  2607. TString* paramValue = nullptr;
  2608. item.Probe->Event.Signature.SerializeParams(item.Params, paramValues);
  2609. for (size_t pi = 0; pi < item.SavedParamsCount; pi++) {
  2610. if (item.Probe->Event.Signature.ParamNames[pi] == ParamName) {
  2611. paramValue = &paramValues[pi];
  2612. }
  2613. }
  2614. WWW_CHECK(paramValue, "param '%s' not found in probe '%s' at path '%s'",
  2615. ParamName.data(), GetProbeName(item.Probe).data(), Node->GetPath().data());
  2616. TPatternNode* node = &Children[*paramValue];
  2617. // Path example: "//Provider1.Probe1/Provider2.Probe2@1.xxx=123@2.type=harakiri"
  2618. node->Name = "@" + ToString(Rollbacks) + "." + ParamName + "=" + *paramValue;
  2619. node->Desc.Type = NT_PARAM;
  2620. node->Desc.Rollbacks = Rollbacks;
  2621. node->Desc.ParamName = ParamName;
  2622. node->Desc.ParamValue = *paramValue;
  2623. return node;
  2624. }
  2625. void Accept(IVisitor* visitor) override
  2626. {
  2627. if (SortedChildren.size() != Children.size()) {
  2628. SortedChildren.clear();
  2629. SortedChildren.reserve(Children.size());
  2630. for (auto i = Children.begin(), e = Children.end(); i != e; ++i) {
  2631. SortedChildren.push_back(&*i);
  2632. }
  2633. Sort(SortedChildren, [] (TChildren::value_type* lhs, TChildren::value_type* rhs) {
  2634. return lhs->first < rhs->first;
  2635. });
  2636. }
  2637. for (auto* kv : SortedChildren) {
  2638. visitor->Visit(&kv->second);
  2639. }
  2640. }
  2641. bool IsLeaf() override { return Children.empty(); }
  2642. };
  2643. private:
  2644. TPatternNode Root;
  2645. THashMap<TString, std::pair<size_t, TString>> ParamClassifiers; // path -> (rollbacks, param)
  2646. TString SelectedPattern;
  2647. TPatternNode* SelectedNode = nullptr;
  2648. TVector<ui64> Timeline; // Just to avoid reallocations
  2649. public:
  2650. TPatternTree(const TCgiParameters& e)
  2651. {
  2652. for (const TString& cl : Subvalues(e, "classify")) {
  2653. size_t at = cl.find_last_of('@');
  2654. if (at != TString::npos) {
  2655. size_t dot = cl.find('.', at + 1);
  2656. if (dot != TString::npos) {
  2657. size_t rollbacks = FromString<size_t>(cl.substr(at + 1, dot - at - 1));
  2658. ParamClassifiers[cl.substr(0, at)] = std::make_pair(rollbacks, cl.substr(dot + 1));
  2659. }
  2660. }
  2661. }
  2662. SelectedPattern = e.Get("pattern");
  2663. InitNode(&Root, nullptr);
  2664. }
  2665. TPatternNode* GetSelectedNode()
  2666. {
  2667. return SelectedNode;
  2668. }
  2669. NAnalytics::TTable GetSelectedTable()
  2670. {
  2671. if (SelectedNode) {
  2672. return SelectedNode->GetTable();
  2673. } else {
  2674. return NAnalytics::TTable();
  2675. }
  2676. }
  2677. template <typename TReader>
  2678. void OutputSelectedSample(const TString& bn, double b1, double b2, const TSampleOpts& opts, TReader& reader)
  2679. {
  2680. if (SelectedNode) {
  2681. SelectedNode->OutputSample(bn, b1, b2, opts, reader);
  2682. }
  2683. }
  2684. // Register track in given node
  2685. void AddTrackToNode(TPatternNode* node, TTrack& track, ui64 resTotal, TVector<ui64>& timeline)
  2686. {
  2687. if (!SelectedNode) {
  2688. if (node->GetPath() == SelectedPattern) {
  2689. SelectedNode = node;
  2690. }
  2691. }
  2692. // Counting
  2693. node->TrackCount++;
  2694. // Resource total
  2695. node->ResTotalSum += resTotal;
  2696. node->ResTotalMax = Max(node->ResTotalMax, resTotal);
  2697. node->ResTotalAll.push_back(resTotal);
  2698. // Resource last
  2699. ui64 resLast = 0;
  2700. resLast = resTotal - (timeline.size() < 2? 0: timeline[timeline.size() - 2]);
  2701. node->ResLastSum += resLast;
  2702. node->ResLastMax = Max(node->ResLastMax, resLast);
  2703. node->ResLastAll.push_back(resLast);
  2704. // Timeline
  2705. if (node->TimelineSum.size() < timeline.size()) {
  2706. node->TimelineSum.resize(timeline.size());
  2707. }
  2708. for (size_t i = 0; i < timeline.size(); i++) {
  2709. node->TimelineSum[i] += timeline[i];
  2710. }
  2711. if (node == SelectedNode && !timeline.empty()) {
  2712. node->Slices.emplace_back();
  2713. NAnalytics::TRow& row = node->Slices.back();
  2714. ui64 prev = 0;
  2715. for (size_t i = 0; i < timeline.size(); i++) {
  2716. // Note that col names should go in lexicographical order
  2717. // in the same way as slices go in pattern timeline
  2718. double sliceMs = double(timeline[i] - prev) * 1000.0 / NHPTimer::GetClockRate();
  2719. row[Sprintf("%09lu", i)] = sliceMs;
  2720. prev = timeline[i];
  2721. }
  2722. }
  2723. // Interlink node and track
  2724. node->Tracks.emplace_back(&track, resTotal, resLast);
  2725. track.LastNode = node;
  2726. }
  2727. bool CheckPattern(const char*& pi, const char* pe, TStringBuf str)
  2728. {
  2729. auto si = str.begin(), se = str.end();
  2730. for (;pi != pe && si != se; ++pi, ++si) {
  2731. if (*pi != *si) {
  2732. return false;
  2733. }
  2734. }
  2735. return si == se;
  2736. }
  2737. #define WWW_CHECK_PATTERN(str) if (!CheckPattern(pi, pe, (str))) { return false; }
  2738. bool MatchTrack(const TTrack& track, const TString& patternStr)
  2739. {
  2740. const char* pi = patternStr.data();
  2741. const char* pe = pi + patternStr.size();
  2742. WWW_CHECK_PATTERN("/");
  2743. for (TTrackIter i = TTrackTr::begin(track), e = TTrackTr::end(track); i != e; ++i) {
  2744. if (pi == pe) {
  2745. return true;
  2746. }
  2747. const NLWTrace::TLogItem& item = *i;
  2748. WWW_CHECK_PATTERN("/");
  2749. WWW_CHECK_PATTERN(item.Probe->Event.GetProvider());
  2750. WWW_CHECK_PATTERN(".");
  2751. WWW_CHECK_PATTERN(item.Probe->Event.Name);
  2752. while (true) {
  2753. if (pi == pe) {
  2754. return true;
  2755. }
  2756. char c = *pi;
  2757. if (c == '/') {
  2758. break;
  2759. } else if (c == '@') {
  2760. pi++;
  2761. // Parse rollbacks
  2762. TStringBuf p(pi, pe);
  2763. size_t dot = p.find('.');
  2764. if (dot == TStringBuf::npos) {
  2765. return false;
  2766. }
  2767. size_t rollbacks = 0;
  2768. try {
  2769. rollbacks = FromString<size_t>(p.substr(0, dot));
  2770. } catch (...) {
  2771. return false;
  2772. }
  2773. // Parse param name
  2774. size_t equals = p.find('=', dot + 1);
  2775. if (equals == TStringBuf::npos) {
  2776. return false;
  2777. }
  2778. TStringBuf paramName = p.substr(dot + 1, equals - dot - 1);
  2779. pi += equals + 1; // Advance to value
  2780. // Check param value
  2781. if ((i64)rollbacks < 0 || std::distance(TTrackTr::begin(track), i) < (i64)rollbacks) {
  2782. return false;
  2783. }
  2784. const NLWTrace::TLogItem& mitem = *(i - rollbacks);
  2785. if (mitem.SavedParamsCount == 0) {
  2786. return false;
  2787. }
  2788. TString paramValues[LWTRACE_MAX_PARAMS];
  2789. TString* paramValue = nullptr;
  2790. mitem.Probe->Event.Signature.SerializeParams(mitem.Params, paramValues);
  2791. for (size_t pi = 0; pi < mitem.SavedParamsCount; pi++) {
  2792. if (mitem.Probe->Event.Signature.ParamNames[pi] == paramName) {
  2793. paramValue = &paramValues[pi];
  2794. }
  2795. }
  2796. if (!paramValue) {
  2797. return false;
  2798. }
  2799. WWW_CHECK_PATTERN(*paramValue);
  2800. } else {
  2801. return false;
  2802. }
  2803. }
  2804. }
  2805. return true;
  2806. }
  2807. #undef WWW_CHECK_PATTERN
  2808. // Push new track through pattern tree
  2809. void AddTrack(TTrack& track)
  2810. {
  2811. // Truncate long tracks
  2812. if (track.Items.size() > 50) {
  2813. track.Items.resize(50);
  2814. }
  2815. if (SelectedPattern) {
  2816. if (!MatchTrack(track, SelectedPattern)) {
  2817. return;
  2818. }
  2819. }
  2820. Timeline.clear();
  2821. TPatternNode* node = &Root;
  2822. AddTrackToNode(node, track, 0, Timeline);
  2823. ui64 trackStart = TTrackTr::front(track).TimestampCycles;
  2824. for (TTrackIter i = TTrackTr::begin(track), e = TTrackTr::end(track); i != e;) {
  2825. // Get or create child by classification
  2826. TPatternNode* parent = node;
  2827. node = node->Classifier->Classify(i, track);
  2828. if (!node->Classifier) {
  2829. InitNode(node, parent);
  2830. }
  2831. const NLWTrace::TLogItem& item = *i;
  2832. ui64 resTotal = item.TimestampCycles - trackStart;
  2833. if (i != TTrackTr::begin(track)) {
  2834. Timeline.push_back(resTotal);
  2835. }
  2836. AddTrackToNode(node, track, resTotal, Timeline);
  2837. // Move through track
  2838. if (!node->Classifier->KeepHead) {
  2839. ++i;
  2840. }
  2841. }
  2842. }
  2843. // Traverse pattern tree (the only way to extract data from it)
  2844. template <class TOnNode, class TOnDescend, class TOnAscend>
  2845. void Traverse(TOnNode&& onNode, TOnDescend&& onDescend, TOnAscend&& onAscend)
  2846. {
  2847. struct TVisitor : public IVisitor {
  2848. TOnNode OnNode;
  2849. TOnDescend OnDescend;
  2850. TOnAscend OnAscend;
  2851. TVisitor(TOnNode&& onNode, TOnDescend&& onDescend, TOnAscend&& onAscend)
  2852. : OnNode(onNode)
  2853. , OnDescend(onDescend)
  2854. , OnAscend(onAscend)
  2855. {}
  2856. virtual void Visit(TPatternNode* node) override
  2857. {
  2858. OnNode(node);
  2859. if (!node->Classifier->IsLeaf()) {
  2860. OnDescend();
  2861. node->Classifier->Accept(this);
  2862. OnAscend();
  2863. }
  2864. }
  2865. };
  2866. TVisitor visitor(std::move(onNode), std::move(onDescend), std::move(onAscend));
  2867. visitor.Visit(&Root);
  2868. }
  2869. TPatternNode* GetRoot()
  2870. {
  2871. return &Root;
  2872. }
  2873. private:
  2874. void InitNode(TPatternNode* node, TPatternNode* parent)
  2875. {
  2876. node->Parent = parent;
  2877. auto iter = ParamClassifiers.find(node->GetPath());
  2878. if (iter != ParamClassifiers.end()) {
  2879. node->Classifier.Reset(new TClassifyByParam(node, iter->second.first, iter->second.second));
  2880. } else {
  2881. node->Classifier.Reset(new TClassifyByProbe(node));
  2882. }
  2883. }
  2884. };
  2885. class TLogTrackExtractor: public TLogFilter {
  2886. private:
  2887. // Data storage
  2888. TMultiMap<ui64, std::pair<TThread::TId, NLWTrace::TLogItem>> Items;
  2889. TVector<NLWTrace::TTrackLog> Depot;
  2890. // Data refs organized in tracks
  2891. THashMap<TString, TTrack> Tracks;
  2892. TVector<TTrack> TracksFromDepot;
  2893. // Analysis
  2894. TVector<TString> GroupBy;
  2895. THashSet<TString> TrackIds; // The same content as in GroupBy
  2896. TTimestampCutter CutTs;
  2897. TPatternTree Tree;
  2898. public:
  2899. TLogTrackExtractor(const TCgiParameters& e, const TVector<TString>& filters, const TVector<TString>& groupBy)
  2900. : TLogFilter(filters)
  2901. , CutTs(true) // Always cut input data for tracks
  2902. , Tree(e)
  2903. {
  2904. for (const TString& groupParam : groupBy) {
  2905. GroupBy.push_back(groupParam);
  2906. TrackIds.insert(groupParam);
  2907. }
  2908. }
  2909. // For reading lwtrace log (input point for all data)
  2910. void Push(TThread::TId tid, const NLWTrace::TLogItem& item)
  2911. {
  2912. CutTs.Push(tid, item);
  2913. if (Filter(item)) {
  2914. Items.emplace(item.TimestampCycles, std::make_pair(tid, item));
  2915. }
  2916. }
  2917. // For reading lwtrace depot (input point for all data)
  2918. void Push(TThread::TId, const NLWTrace::TTrackLog& tl)
  2919. {
  2920. if (Filter(tl)) {
  2921. Depot.emplace_back(tl);
  2922. }
  2923. }
  2924. // Analyze logs that have been read
  2925. void Run()
  2926. {
  2927. RunImplLog();
  2928. RunImplDepot();
  2929. }
  2930. void RunImplLog()
  2931. {
  2932. // Create tracks by filling them with lwtrace items in order of occurance time
  2933. for (auto& kv : Items) {
  2934. AddItemToTrack(kv.second.first, kv.second.second);
  2935. }
  2936. // Push tracks throught pattern tree
  2937. for (auto& kv : Tracks) {
  2938. TTrack& track = kv.second;
  2939. track.TrackId = kv.first;
  2940. Tree.AddTrack(track);
  2941. }
  2942. }
  2943. void RunImplDepot()
  2944. {
  2945. // Create tracks from depot
  2946. // OPTIMIZE[serxa]: this convertion is not necessary, done just to keep things simple
  2947. for (NLWTrace::TTrackLog& tl : Depot) {
  2948. TTrack& track = TracksFromDepot.emplace_back();
  2949. track.TrackId = ToString(tl.Id);
  2950. for (const NLWTrace::TTrackLog::TItem& i : tl.Items) {
  2951. track.Items.emplace_back(i.ThreadId, i);
  2952. }
  2953. }
  2954. for (TTrack& t : TracksFromDepot) {
  2955. Tree.AddTrack(t);
  2956. }
  2957. }
  2958. // Selected node distribution
  2959. NAnalytics::TTable Distribution(const TString& bn, const TString& b1Str, const TString& b2Str, const TString& widthStr)
  2960. {
  2961. using namespace NAnalytics;
  2962. const NAnalytics::TTable& inputTable = Tree.GetSelectedTable();
  2963. double b1 = b1Str? FromString<double>(b1Str): MinValue(bn, inputTable);
  2964. double b2 = b2Str? FromString<double>(b2Str): MaxValue(bn, inputTable);
  2965. if (isfinite(b1) && isfinite(b2)) {
  2966. WWW_CHECK(b1 <= b2, "invalid xrange [%le; %le]", b1, b2);
  2967. double width = widthStr? FromString<double>(widthStr): 99;
  2968. double dx = (b2 - b1) / width;
  2969. if (!(dx > 0)) {
  2970. dx = 1.0;
  2971. }
  2972. return HistogramAll(inputTable, bn, b1, b2, dx);
  2973. } else {
  2974. // Empty table -- it's ok -- leave data table empty
  2975. return NAnalytics::TTable();
  2976. }
  2977. }
  2978. // Selected sample
  2979. template <typename TReader>
  2980. void OutputSample(const TString& bn, double b1, double b2, const TSampleOpts& opts, TReader& reader)
  2981. {
  2982. Tree.OutputSelectedSample(bn, b1, b2, opts, reader);
  2983. }
  2984. // Tabular representation of tracks data
  2985. void OutputTable(IOutputStream& os, const TCgiParameters& e)
  2986. {
  2987. ui64 tracksTotal = Tree.GetRoot()->TrackCount;
  2988. double maxAvgResTotal = 0;
  2989. double maxMaxResTotal = 0;
  2990. Tree.Traverse([&] (TPatternNode* node) {
  2991. if (node->TrackCount > 0) {
  2992. maxAvgResTotal = Max(maxAvgResTotal, double(node->ResTotalSum) / node->TrackCount);
  2993. maxMaxResTotal = Max(maxMaxResTotal, double(node->ResTotalMax));
  2994. Sort(node->ResTotalAll);
  2995. Sort(node->ResLastAll);
  2996. }
  2997. }, [&] () { // On descend
  2998. }, [&] () { // On ascend
  2999. });
  3000. double maxTime = Min(maxMaxResTotal, 1.25 * maxAvgResTotal);
  3001. double percentile = e.Get("ile")? FromString<double>(e.Get("ile")): 90;
  3002. WWW_CHECK(percentile >= 0.0 && percentile <= 100.0, "wrong percentile: %lf", percentile);
  3003. ui64 row = 0;
  3004. TVector<ui64> chain;
  3005. HTML(os) {
  3006. TABLE_CLASS("tracks-tree") {
  3007. TABLEHEAD() {
  3008. os << "<tr>";
  3009. os << "<td rowspan=\"2\" style=\"vertical-align:bottom\" align=\"center\">#</td>";
  3010. os << "<td rowspan=\"2\" style=\"vertical-align:bottom\" align=\"center\">Pattern</td>";
  3011. os << "<td rowspan=\"2\" style=\"vertical-align:bottom\" align=\"center\">";
  3012. DIV_CLASS("rotate") { os << "Track Count"; }
  3013. os << "</td>";
  3014. os << "<td colspan=\"2\" style=\"vertical-align:bottom\" align=\"center\">Share</td>";
  3015. os << "<td colspan=\"2\" style=\"vertical-align:bottom\" align=\"center\">Total, ms</td>";
  3016. os << "<td colspan=\"2\" style=\"vertical-align:bottom\" align=\"center\">Last, ms</td>";
  3017. os << "<td rowspan=\"2\" style=\"vertical-align:bottom\" class=\"timelinehead\" align=\"center\">Global Timeline</td>";
  3018. os << "</tr><tr>";
  3019. TABLEH() DIV_CLASS("rotate") { os << "Absolute"; }
  3020. TABLEH() DIV_CLASS("rotate") { os << "Relative"; }
  3021. TABLEH() DIV_CLASS("rotate") { os << "Average"; }
  3022. TABLEH() DIV_CLASS("rotate") { os << percentile << "%-ile"; }
  3023. TABLEH() DIV_CLASS("rotate") { os << "Average"; }
  3024. TABLEH() DIV_CLASS("rotate") { os << percentile << "%-ile"; }
  3025. os << "</tr>";
  3026. }
  3027. TABLEBODY() {
  3028. if (tracksTotal == 0) {
  3029. return;
  3030. }
  3031. Tree.Traverse([&] (TPatternNode* node) {
  3032. TString parentClass;
  3033. if (!chain.empty()) {
  3034. parentClass = " treegrid-parent-" + ToString(chain.back());
  3035. }
  3036. TString selectedClass;
  3037. if (e.Get("pattern") == node->GetPath()) {
  3038. selectedClass = " danger";
  3039. }
  3040. TABLER_CLASS("treegrid-" + ToString(++row) + parentClass + selectedClass) {
  3041. // Counting
  3042. ui64 tracksParent = node->Parent? node->Parent->TrackCount: tracksTotal;
  3043. double absShare = double(node->TrackCount) * 100 / tracksTotal;
  3044. double relShare = double(node->TrackCount) * 100 / tracksParent;
  3045. // Resource total
  3046. double avgResTotal = double(node->ResTotalSum) / node->TrackCount;
  3047. size_t ileResTotalIdx = node->ResTotalAll.size() * percentile / 100;
  3048. if (ileResTotalIdx > 0) {
  3049. ileResTotalIdx--;
  3050. }
  3051. double ileResTotal = double(ileResTotalIdx >= node->ResTotalAll.size()? 0: node->ResTotalAll[ileResTotalIdx]);
  3052. double avgResTotalMs = avgResTotal * 1000.0 / NHPTimer::GetClockRate();
  3053. double ileResTotalMs = ileResTotal * 1000.0 / NHPTimer::GetClockRate();
  3054. // Resource last
  3055. double avgResLast = double(node->ResLastSum) / node->TrackCount;
  3056. size_t ileResLastIdx = node->ResLastAll.size() * percentile / 100;
  3057. if (ileResLastIdx > 0) {
  3058. ileResLastIdx--;
  3059. }
  3060. double ileResLast = double(ileResLastIdx >= node->ResLastAll.size()? 0: node->ResLastAll[ileResLastIdx]);
  3061. double avgResLastMs = avgResLast * 1000.0 / NHPTimer::GetClockRate();
  3062. double ileResLastMs = ileResLast * 1000.0 / NHPTimer::GetClockRate();
  3063. // Output
  3064. TABLED() { os << row; }
  3065. TABLED_CLASS("treegrid-element") { OutputPattern(os, e, node); }
  3066. TABLED() { os << node->TrackCount; }
  3067. TABLED() { OutputShare(os, absShare); }
  3068. TABLED() { OutputShare(os, relShare); }
  3069. TABLED() { os << FormatFloat(avgResTotalMs); }
  3070. TABLED() { os << FormatFloat(ileResTotalMs); }
  3071. TABLED() { os << FormatFloat(avgResLastMs); }
  3072. TABLED() { os << FormatFloat(ileResLastMs); }
  3073. TABLED() { OutputTimeline(os, MakeTimeline(node), maxTime); }
  3074. }
  3075. }, [&] () { // On descend
  3076. chain.push_back(row);
  3077. }, [&] () { // On ascend
  3078. chain.pop_back();
  3079. });
  3080. }
  3081. }
  3082. }
  3083. }
  3084. // Chromium-compatible trace representation of tracks data
  3085. void OutputChromeTrace(IOutputStream& os, const TCgiParameters& e)
  3086. {
  3087. Y_UNUSED(e);
  3088. TChromeTrace tr;
  3089. for (TPatternNode::TTrackEntry& entry: Tree.GetRoot()->Tracks) {
  3090. TTrack* track = entry.Track;
  3091. auto first = TTrackTr::begin(*track);
  3092. auto last = TTrackTr::rbegin(*track);
  3093. TString name = track->LastNode->GetPath();
  3094. const NLWTrace::TLogItem& firstItem = *first;
  3095. TThread::TId firstTid = first->ThreadId;
  3096. tr.Add(firstTid, firstItem.TimestampCycles, "b", "track", nullptr, name, track->TrackId);
  3097. for (auto cur = TTrackTr::begin(*track), end = TTrackTr::end(*track); cur != end; ++cur) {
  3098. const NLWTrace::TLogItem& item = *cur;
  3099. tr.Add(cur->ThreadId, item.TimestampCycles, "i", "event", &item, GetProbeName(item.Probe));
  3100. TString sliceName = GetProbeName(item.Probe);
  3101. auto next = cur + 1;
  3102. if (next != end) {
  3103. const NLWTrace::TLogItem& nextItem = *next;
  3104. tr.Add(cur->ThreadId, item.TimestampCycles, "b", "track", &item, sliceName, track->TrackId);
  3105. tr.Add(next->ThreadId, nextItem.TimestampCycles, "e", "track", &nextItem, sliceName, track->TrackId);
  3106. } else {
  3107. tr.Add(cur->ThreadId, item.TimestampCycles, "n", "track", &item, sliceName, track->TrackId);
  3108. }
  3109. }
  3110. const NLWTrace::TLogItem& lastItem = *last;
  3111. tr.Add(last->ThreadId, lastItem.TimestampCycles, "e", "track", nullptr, name, track->TrackId);
  3112. }
  3113. tr.Output(os);
  3114. }
  3115. void OutputSliceCovarianceMatrix(IOutputStream& os, const TCgiParameters& e)
  3116. {
  3117. Y_UNUSED(e);
  3118. TPatternNode* node = Tree.GetSelectedNode();
  3119. if (!node) {
  3120. return;
  3121. }
  3122. NAnalytics::TMatrix covMatrix = NAnalytics::CovarianceMatrix(node->Slices);
  3123. double var = covMatrix.CellSum();
  3124. double covMax = 0.0;
  3125. for (double x : covMatrix) {
  3126. if (covMax < x) {
  3127. covMax = x;
  3128. }
  3129. }
  3130. double dangerCov = covMax * 0.9 * 0.9;
  3131. double warnCov = covMax * 0.5 * 0.5;
  3132. HTML(os) {
  3133. TABLE() {
  3134. TTimeline timeline = MakeTimeline(node);
  3135. TABLED() {};
  3136. TABLEHEAD() TABLER() {
  3137. for (auto& e : timeline) TABLED() {
  3138. TPatternNode* subnode = e.first;
  3139. os << subnode->Name;
  3140. }
  3141. }
  3142. auto tl = timeline.begin();
  3143. TABLEBODY() for (size_t row = 0; row < covMatrix.Rows; row++) TABLER() {
  3144. TABLEH() {
  3145. if (tl != timeline.end()) {
  3146. TPatternNode* subnode = tl->first;
  3147. os << subnode->Name;
  3148. ++tl;
  3149. }
  3150. }
  3151. for (size_t col = 0; col < covMatrix.Cols; col++) {
  3152. double cov = covMatrix.Cell(row, col);
  3153. TString tdClass = (cov >= dangerCov? "danger": (cov >= warnCov? "warning": ""));
  3154. TABLED_CLASS(tdClass) {
  3155. double sigmaX = (covMatrix.Cell(row, row) > 0? sqrt(covMatrix.Cell(row, row)): 0);
  3156. double sigmaY = (covMatrix.Cell(col, col) > 0? sqrt(covMatrix.Cell(col, col)): 0);
  3157. os << Sprintf("cov=%.3lf&nbsp;ms<sup>2</sup>&nbsp;(%.3lf&nbsp;ms) corr=%.1lf%% var_share=%.1lf%%",
  3158. cov, sqrt(abs(cov)), cov * 100.0 / sigmaX / sigmaY, cov * 100.0 / var);
  3159. }
  3160. }
  3161. }
  3162. }
  3163. }
  3164. }
  3165. private:
  3166. TPatternNode* RollbackFind(TPatternNode* node)
  3167. {
  3168. for (;node != nullptr; node = node->Parent) {
  3169. if (node->Desc.Type == NT_PROBE) {
  3170. return node;
  3171. }
  3172. }
  3173. return nullptr;
  3174. }
  3175. void OutputPattern(IOutputStream& os, const TCgiParameters& e, TPatternNode* node)
  3176. {
  3177. // Fill pattern name
  3178. TString patternName;
  3179. TString patternTitle;
  3180. switch (node->Desc.Type) {
  3181. case NT_ROOT:
  3182. patternName = "All Tracks";
  3183. break;
  3184. case NT_PROBE:
  3185. patternTitle = GetProbeName(node->Desc.Probe);
  3186. patternName = node->Desc.Probe->Event.Name;
  3187. break;
  3188. case NT_PARAM:
  3189. patternName.append(node->Desc.ParamName + " = " + node->Desc.ParamValue);
  3190. break;
  3191. }
  3192. os << "<a href=\"" << MakeUrl(e, {
  3193. {"pattern", node->GetPath()},
  3194. {"ptrn_anlz", e.Get("ptrn_anlz") ? e.Get("ptrn_anlz") : "resTotal"},
  3195. {"linesfill", "y"},
  3196. {"linessteps", "y"},
  3197. {"pointsshow", "n"},
  3198. {"sel_x1", e.Get("sel_x1") ? e.Get("sel_x1") : "0"},
  3199. {"sel_x2", e.Get("sel_x2") ? e.Get("sel_x2") : "inf"}}) << "\""
  3200. " title=\"" + patternTitle + "\">" << patternName << "</a>";
  3201. // Add/remove node menu
  3202. if (node->Desc.Type != NT_ROOT) {
  3203. os << "<div class=\"dropdown pull-right\" style=\"display:inline-block\">";
  3204. if (node->Desc.Type == NT_PARAM) {
  3205. os<< "<button class=\"btn btn-xs btn-default\" type=\"button\""
  3206. << "\" onClick=\"window.location.href='"
  3207. << MakeUrlEraseSub(e, "classify", node->Parent->GetPath() + "@"
  3208. + ToString(node->Desc.Rollbacks) + "." + node->Desc.ParamName)
  3209. << "';\">"
  3210. "<span class=\"glyphicon glyphicon-minus\"></span>"
  3211. "</button>";
  3212. }
  3213. if (node->Classifier->GetChildType() != NT_PARAM) {
  3214. os << "<button class=\"btn btn-xs btn-default dropdown-toggle\" type=\"button\""
  3215. " data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"true\">"
  3216. "<span class=\"glyphicon glyphicon-plus\"></span>"
  3217. "</button>"
  3218. "<ul class=\"dropdown-menu\">"
  3219. "<li class=\"dropdown-header\">Classify by param:</li>";
  3220. int rollbacks = 0;
  3221. TPatternNode* probeNode = node;
  3222. while (probeNode = RollbackFind(probeNode)) {
  3223. const NLWTrace::TProbe* probe = probeNode->Desc.Probe;
  3224. os << "<li class=\"dropdown-header\">" << GetProbeName(probe) << "</li>";
  3225. const NLWTrace::TSignature* sgn = &probe->Event.Signature;
  3226. for (size_t pi = 0; pi < sgn->ParamCount; pi++) {
  3227. TString param = sgn->ParamNames[pi];
  3228. if (TrackIds.contains(param) || IsFiltered(param)) {
  3229. continue;
  3230. }
  3231. os << "<li><a href=\""
  3232. << MakeUrlAddSub(e, "classify", node->GetPath() + "@" + ToString(rollbacks) + "." + param)
  3233. << "\">" << param << "</a></li>";
  3234. }
  3235. rollbacks++;
  3236. probeNode = probeNode->Parent;
  3237. }
  3238. os << "</ul>";
  3239. }
  3240. os << "</div>";
  3241. }
  3242. }
  3243. void OutputShare(IOutputStream& os, double share)
  3244. {
  3245. double lshare = share;
  3246. double rshare = 100 - lshare;
  3247. os << "<div class=\"progress\" style=\"margin-bottom:0px;position:relative\">"
  3248. "<div class=\"progress-bar progress-bar-success\" role=\"progressbar\""
  3249. " aria-valuenow=\"" << lshare << "\""
  3250. " aria-valuemin=\"0\""
  3251. " aria-valuemax=\"100\""
  3252. " style=\"width: " << lshare << "%;\">"
  3253. "</div>"
  3254. "<div class=\"progress-bar progress-bar-danger\" role=\"progressbar\""
  3255. " aria-valuenow=\"" << rshare << "\""
  3256. " aria-valuemin=\"0\""
  3257. " aria-valuemax=\"100\""
  3258. " style=\"width: " << rshare << "%;\">"
  3259. "</div>"
  3260. "<span style=\"position:absolute;left:0;width:100%;text-align:center;z-index:2;color:white\">"
  3261. << (share == 100? "100%": Sprintf("%2.1lf%%", share)) <<
  3262. "</span>"
  3263. "</div>";
  3264. }
  3265. using TTimeline = TVector<std::pair<TPatternNode*, double>>;
  3266. TTimeline MakeTimeline(TPatternNode* node)
  3267. {
  3268. TTimeline ret;
  3269. if (node->TrackCount == 0) {
  3270. return ret;
  3271. }
  3272. ret.reserve(node->TimelineSum.size());
  3273. for (double time : node->TimelineSum) {
  3274. ret.emplace_back(nullptr, double(time) / node->TrackCount);
  3275. }
  3276. TPatternNode* n = node;
  3277. for (auto i = ret.rbegin(), e = ret.rend(); i != e; ++i) {
  3278. WWW_CHECK(n, "internal bug: wrong timeline length at pattern node '%s'", node->GetPath().data());
  3279. i->first = n;
  3280. n = n->Parent;
  3281. }
  3282. return ret;
  3283. }
  3284. void OutputTimeline(IOutputStream& os, const TTimeline& timeline, double maxTime)
  3285. {
  3286. static const char *barClass[] = {
  3287. "progress-bar-info",
  3288. "progress-bar-warning"
  3289. };
  3290. if (timeline.empty()) {
  3291. return;
  3292. }
  3293. os << "<div class=\"progress\" style=\"margin-bottom:0px;color:black\">";
  3294. double prevPos = 0.0;
  3295. double prevTime = 0.0;
  3296. size_t i = 0;
  3297. for (auto& e : timeline) {
  3298. TPatternNode* node = e.first;
  3299. double time = e.second;
  3300. double pos = time * 100 / maxTime;
  3301. if (pos > 100) {
  3302. pos = 100;
  3303. }
  3304. double width = pos - prevPos;
  3305. os << "<div class=\"progress-bar " << barClass[i % 2] << "\" role=\"progressbar\""
  3306. " aria-valuenow=\"" << width << "\""
  3307. " aria-valuemin=\"0\""
  3308. " aria-valuemax=\"100\""
  3309. " style=\"width:" << width << "%;color:black\""
  3310. " title=\"" << FormatTimelineTooltip(time, prevTime, node) << "\">";
  3311. if (width > 20) { // To ensure text will fit the bar
  3312. os << FormatCycles(time - prevTime);
  3313. }
  3314. os << "</div>";
  3315. prevPos = pos;
  3316. prevTime = time;
  3317. i++;
  3318. }
  3319. os << "</div>";
  3320. }
  3321. TString FormatTimelineTooltip(double time, double prevTime, TPatternNode* node)
  3322. {
  3323. return FormatCycles(time - prevTime) + ": "
  3324. + FormatCycles(prevTime) + " -> " + FormatCycles(time)
  3325. + "(" + node->Name + ")";
  3326. }
  3327. TString FormatFloat(double value)
  3328. {
  3329. if (value == 0.0) {
  3330. return "0";
  3331. }
  3332. if (value > 1.0) {
  3333. if (value > 100.0) {
  3334. return Sprintf("%.0lf", value);
  3335. }
  3336. if (value > 10.0) {
  3337. return Sprintf("%.1lf", value);
  3338. }
  3339. return Sprintf("%.2lf", value);
  3340. } else if (value > 1e-3) {
  3341. if (value > 1e-1) {
  3342. return Sprintf("%.3lf", value);
  3343. }
  3344. if (value > 1e-2) {
  3345. return Sprintf("%.4lf", value);
  3346. }
  3347. return Sprintf("%.5lf", value);
  3348. } else if (value > 1e-6) {
  3349. if (value > 1e-4) {
  3350. return Sprintf("%.6lf", value);
  3351. }
  3352. if (value > 1e-5) {
  3353. return Sprintf("%.7lf", value);
  3354. }
  3355. return Sprintf("%.8lfus", value);
  3356. } else {
  3357. if (value > 1e-7) {
  3358. return Sprintf("%.9lfns", value);
  3359. }
  3360. if (value > 1e-8) {
  3361. return Sprintf("%.10lfns", value);
  3362. }
  3363. return Sprintf("%.2le", value);
  3364. }
  3365. }
  3366. TString FormatCycles(double timeCycles)
  3367. {
  3368. double timeSec = timeCycles / NHPTimer::GetClockRate();
  3369. if (timeSec > 1.0) {
  3370. if (timeSec > 100.0) {
  3371. return Sprintf("%.0lfs", timeSec);
  3372. }
  3373. if (timeSec > 10.0) {
  3374. return Sprintf("%.1lfs", timeSec);
  3375. }
  3376. return Sprintf("%.2lfs", timeSec);
  3377. } else if (timeSec > 1e-3) {
  3378. if (timeSec > 1e-1) {
  3379. return Sprintf("%.0lfms", timeSec * 1e3);
  3380. }
  3381. if (timeSec > 1e-2) {
  3382. return Sprintf("%.1lfms", timeSec * 1e3);
  3383. }
  3384. return Sprintf("%.2lfms", timeSec * 1e3);
  3385. } else if (timeSec > 1e-6) {
  3386. if (timeSec > 1e-4) {
  3387. return Sprintf("%.0lfus", timeSec * 1e6);
  3388. }
  3389. if (timeSec > 1e-5) {
  3390. return Sprintf("%.1lfus", timeSec * 1e6);
  3391. }
  3392. return Sprintf("%.2lfus", timeSec * 1e6);
  3393. } else {
  3394. if (timeSec > 1e-7) {
  3395. return Sprintf("%.0lfns", timeSec * 1e9);
  3396. }
  3397. if (timeSec > 1e-8) {
  3398. return Sprintf("%.1lfns", timeSec * 1e9);
  3399. }
  3400. return Sprintf("%.2lfns", timeSec * 1e9);
  3401. }
  3402. }
  3403. TString GetParam(const NLWTrace::TLogItem& item, TString* paramValues, const TString& paramName)
  3404. {
  3405. for (size_t pi = 0; pi < item.SavedParamsCount; pi++) {
  3406. if (paramName == item.Probe->Event.Signature.ParamNames[pi]) {
  3407. return paramValues[pi];
  3408. }
  3409. }
  3410. return TString();
  3411. }
  3412. TString GetGroup(const NLWTrace::TLogItem& item, TString* paramValues)
  3413. {
  3414. TStringStream ss;
  3415. bool first = true;
  3416. for (const TString& groupParam : GroupBy) {
  3417. ss << (first? "": "|") << GetParam(item, paramValues, groupParam);
  3418. first = false;
  3419. }
  3420. return ss.Str();
  3421. }
  3422. void AddItemToTrack(TThread::TId tid, const NLWTrace::TLogItem& item)
  3423. {
  3424. // Ensure cyclic per thread lwtrace logs wont drop *inner* items of a track
  3425. // (note that some *starting* items can be dropped)
  3426. if (item.SavedParamsCount > 0 && !CutTs.Skip(item)) {
  3427. TString paramValues[LWTRACE_MAX_PARAMS];
  3428. item.Probe->Event.Signature.SerializeParams(item.Params, paramValues);
  3429. Tracks[GetGroup(item, paramValues)].Items.emplace_back(tid, item);
  3430. }
  3431. }
  3432. };
  3433. NLWTrace::TProbeRegistry g_Probes;
  3434. TString g_sanitizerTest("TString g_sanitizerTest");
  3435. NLWTrace::TManager g_SafeManager(g_Probes, false);
  3436. NLWTrace::TManager g_UnsafeManager(g_Probes, true);
  3437. TDashboardRegistry g_DashboardRegistry;
  3438. class TLWTraceMonPage : public NMonitoring::IMonPage {
  3439. private:
  3440. NLWTrace::TManager* TraceMngr;
  3441. TString StartTime;
  3442. TTraceCleaner Cleaner;
  3443. TMutex SnapshotsMtx;
  3444. THashMap<TString, TAtomicSharedPtr<NLWTrace::TLogPb>> Snapshots;
  3445. public:
  3446. explicit TLWTraceMonPage(bool allowUnsafe = false)
  3447. : NMonitoring::IMonPage("trace", "Tracing")
  3448. , TraceMngr(&TraceManager(allowUnsafe))
  3449. , Cleaner(TraceMngr)
  3450. {
  3451. time_t stime = TInstant::Now().TimeT();
  3452. StartTime = CTimeR(&stime);
  3453. }
  3454. virtual void Output(NMonitoring::IMonHttpRequest& request) {
  3455. TStringStream out;
  3456. try {
  3457. if (request.GetParams().Get("mode") == "") {
  3458. OutputTracesAndSnapshots(request, out);
  3459. } else if (request.GetParams().Get("mode") == "probes") {
  3460. OutputProbes(request, out);
  3461. } else if (request.GetParams().Get("mode") == "dashboards") {
  3462. OutputDashboards(request, out);
  3463. } else if (request.GetParams().Get("mode") == "dashboard") {
  3464. OutputDashboard(request, out);
  3465. } else if (request.GetParams().Get("mode") == "log") {
  3466. OutputLog(request, out);
  3467. } else if (request.GetParams().Get("mode") == "query") {
  3468. OutputQuery(request, out);
  3469. } else if (request.GetParams().Get("mode") == "builder") {
  3470. OutputBuilder(request, out);
  3471. } else if (request.GetParams().Get("mode") == "analytics") {
  3472. OutputAnalytics(request, out);
  3473. } else if (request.GetParams().Get("mode") == "new") {
  3474. PostNew(request, out);
  3475. } else if (request.GetParams().Get("mode") == "delete") {
  3476. PostDelete(request, out);
  3477. } else if (request.GetParams().Get("mode") == "make_snapshot") {
  3478. PostSnapshot(request, out);
  3479. } else if (request.GetParams().Get("mode") == "settimeout") {
  3480. PostSetTimeout(request, out);
  3481. } else {
  3482. ythrow yexception() << "Bad request";
  3483. }
  3484. } catch (TPageGenBase& gen) {
  3485. out.Clear();
  3486. out << gen.what();
  3487. } catch (...) {
  3488. out.Clear();
  3489. if (request.GetParams().Get("error") == "text") {
  3490. // Text error reply is helpful for ajax requests
  3491. out << NMonitoring::HTTPOKTEXT;
  3492. out << CurrentExceptionMessage();
  3493. } else {
  3494. WWW_HTML(out) {
  3495. out << "<h2>Error</h2><pre>"
  3496. << CurrentExceptionMessage()
  3497. << Endl;
  3498. }
  3499. }
  3500. }
  3501. request.Output() << out.Str();
  3502. }
  3503. private:
  3504. void OutputNavbar(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3505. {
  3506. TString active = " class=\"active\"";
  3507. out <<
  3508. "<nav class=\"navbar navbar-default\"><div class=\"container-fluid\">"
  3509. << NavbarHeader() <<
  3510. "<ul class=\"nav navbar-nav\">"
  3511. "<li" << (request.GetParams().Get("mode") == ""? active: "") << "><a href=\"?mode=\">Traces</a></li>"
  3512. "<li" << (request.GetParams().Get("mode") == "probes"? active: "") << "><a href=\"?mode=probes\">Probes</a></li>"
  3513. "<li" << (request.GetParams().Get("mode") == "dashboards"? active: "") << "><a href=\"?mode=dashboards\">Dashboard</a></li>"
  3514. "<li" << (request.GetParams().Get("mode") == "builder"? active: "") << "><a href=\"?mode=builder\">Builder</a></li>"
  3515. "<li" << (request.GetParams().Get("mode") == "analytics"? active: "") << "><a href=\"?mode=analytics&id=\">Analytics</a></li>"
  3516. "<li><a href=\"https://wiki.yandex-team.ru/development/poisk/arcadia/library/cpp/lwtrace/\" target=\"_blank\">Documentation</a></li>"
  3517. "</ul>"
  3518. "</div></nav>"
  3519. ;
  3520. }
  3521. template <class TReader>
  3522. void ReadSnapshots(TReader& reader) const
  3523. {
  3524. TGuard<TMutex> g(SnapshotsMtx);
  3525. for (const auto& kv : Snapshots) {
  3526. reader.Push(kv.first, kv.second);
  3527. }
  3528. }
  3529. void OutputTracesAndSnapshots(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3530. {
  3531. TLogSources logSources(Cleaner);
  3532. TraceMngr->ReadTraces(logSources);
  3533. ReadSnapshots(logSources);
  3534. TStringStream ss;
  3535. TTracesHtmlPrinter printer(ss);
  3536. logSources.ForEach(printer);
  3537. WWW_HTML(out) {
  3538. OutputNavbar(request, out);
  3539. out <<
  3540. "<table class=\"table table-striped\">"
  3541. "<tr><th>Start Time</th><th>Timeout</th><th>Name</th><th>Events</th><th>Threads</th><th></th><th></th><th></th><th></th><th></th></tr>"
  3542. << ss.Str() <<
  3543. "</table>"
  3544. ;
  3545. out << "<hr/><p><strong>Start time:</strong> " << StartTime;
  3546. out << "<br/><strong>Build date:</strong> ";
  3547. out << __DATE__ << " " << __TIME__ << "</p>" << Endl;
  3548. }
  3549. }
  3550. void OutputProbes(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3551. {
  3552. TStringStream ss;
  3553. TProbesHtmlPrinter printer;
  3554. TraceMngr->ReadProbes(printer);
  3555. printer.Output(ss);
  3556. WWW_HTML(out) {
  3557. OutputNavbar(request, out);
  3558. out << ss.Str();
  3559. }
  3560. }
  3561. void OutputDashboards(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3562. {
  3563. TStringStream ss;
  3564. g_DashboardRegistry.Output(ss);
  3565. WWW_HTML(out) {
  3566. OutputNavbar(request, out);
  3567. out << ss.Str();
  3568. }
  3569. }
  3570. void OutputDashboard(const NMonitoring::IMonHttpRequest& request, IOutputStream& out) {
  3571. if (!request.GetParams().Has("name")) {
  3572. ythrow yexception() << "Cgi-parameter 'name' is not specified";
  3573. } else {
  3574. auto name = request.GetParams().Get("name");
  3575. NLWTrace::TDashboard dash;
  3576. if (!g_DashboardRegistry.Get(name, dash)) {
  3577. ythrow yexception() << "Dashboard doesn't exist";
  3578. }
  3579. WWW_HTML(out) {
  3580. OutputNavbar(request, out);
  3581. out << "<style type='text/css'>html, body { height: 100%; }</style>";
  3582. out << "<h2>" << dash.GetName() << "</h2>";
  3583. if (dash.GetDescription()) {
  3584. out << "<h3>" << dash.GetDescription() << "</h3>";
  3585. }
  3586. int height = 85; // %
  3587. int minHeight = 100; // px
  3588. out << "<table height='" << height << "%' width='100%' cellpadding='4'><tbody height='100%' width='100%'>";
  3589. ui32 rows = 0;
  3590. auto maxRowSpan = [](const auto& row) {
  3591. ui32 rowSpan = 1;
  3592. for (const auto& cell : row.GetCells()) {
  3593. rowSpan = Max(rowSpan, cell.GetRowSpan());
  3594. }
  3595. return rowSpan;
  3596. };
  3597. for (const auto& row : dash.GetRows()) {
  3598. rows += maxRowSpan(row);
  3599. }
  3600. for (const auto& row : dash.GetRows()) {
  3601. int rowSpan = maxRowSpan(row);
  3602. out << "<tr align='left' valign='top' style='height:" << (height * rowSpan / rows) << "%; min-height:" << (minHeight * rowSpan)<< "px'>";
  3603. for (const auto& cell : row.GetCells()) {
  3604. TString url = cell.GetUrl();
  3605. TString title = cell.GetTitle();
  3606. TString text = cell.GetText();
  3607. auto rowSpan = Max<ui64>(1, cell.GetRowSpan());
  3608. auto colSpan = Max<ui64>(1, cell.GetColSpan());
  3609. if (url) {
  3610. if (title) {
  3611. out << "<td rowspan='" << rowSpan << "' colSpan='1'><a href=" << url << ">" << title << "</a><br>";
  3612. }
  3613. out << "<iframe scrolling='no' width='" << 100 * colSpan << "%' height='" << height << "%' style='border: 0' src=" << url << "></iframe></td>";
  3614. // Add fake cells to fix html table
  3615. for (ui32 left = 1; left < colSpan; ++left) {
  3616. out << "<td height='100%' rowspan='" << rowSpan << "' colSpan='1'>"
  3617. << "<iframe scrolling='no' width='100%' height='100%' style='border: 0' src=" << "" << "></iframe></td>";
  3618. }
  3619. } else {
  3620. out << "<td style='font-size: 25px' align='left' rowspan='" << rowSpan << "' colSpan='" << colSpan << "'>" << text << "</td>";
  3621. }
  3622. }
  3623. }
  3624. out << "</tbody></table>";
  3625. }
  3626. }
  3627. }
  3628. static double ParseDouble(const TString& s)
  3629. {
  3630. if (s == "inf") {
  3631. return std::numeric_limits<double>::infinity();
  3632. } else if (s == "-inf") {
  3633. return -std::numeric_limits<double>::infinity();
  3634. } else {
  3635. return FromString<double>(s);
  3636. }
  3637. }
  3638. void OutputLog(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3639. {
  3640. if (request.GetParams().NumOfValues("id") == 0) {
  3641. ythrow yexception() << "Cgi-parameter 'id' is not specified";
  3642. } else {
  3643. const TCgiParameters& e = request.GetParams();
  3644. TStringStream ss;
  3645. if (e.Get("format") == "json") {
  3646. TLogJsonPrinter printer(ss);
  3647. printer.OutputHeader();
  3648. TString id = e.Get("id");
  3649. CheckAdHocTrace(id, TDuration::Minutes(1));
  3650. TraceMngr->ReadLog(id, printer);
  3651. printer.OutputFooter(TraceMngr->GetTrace(id));
  3652. out << HTTPOKJSON;
  3653. out << ss.Str();
  3654. } if (e.Get("format") == "json2") {
  3655. TLogTextPrinter printer(e);
  3656. for (const TString& id : Subvalues(e, "id")) {
  3657. CheckAdHocTrace(id, TDuration::Minutes(1));
  3658. TraceMngr->ReadLog(id, printer);
  3659. TraceMngr->ReadDepot(id, printer);
  3660. }
  3661. printer.OutputJson(ss);
  3662. out << HTTPOKJSON;
  3663. out << ss.Str();
  3664. } else if (e.Get("format") == "analytics" && e.Get("aggr") == "tracks") {
  3665. TLogTrackExtractor logTrackExtractor(e,
  3666. Subvalues(e, "f"),
  3667. Subvalues(e, "g")
  3668. );
  3669. for (const TString& id : Subvalues(e, "id")) {
  3670. CheckAdHocTrace(id, TDuration::Minutes(1));
  3671. TraceMngr->ReadLog(id, logTrackExtractor);
  3672. TraceMngr->ReadDepot(id, logTrackExtractor);
  3673. }
  3674. TString patternAnalyzer;
  3675. if (e.Get("pattern")) {
  3676. patternAnalyzer = e.Get("ptrn_anlz");
  3677. }
  3678. logTrackExtractor.Run();
  3679. TLogTextPrinter printer(e);
  3680. const TString& distBy = patternAnalyzer;
  3681. double sel_x1 = e.Get("sel_x1")? ParseDouble(e.Get("sel_x1")): NAN;
  3682. double sel_x2 = e.Get("sel_x2")? ParseDouble(e.Get("sel_x2")): NAN;
  3683. TSampleOpts opts;
  3684. opts.ShowProvider = (e.Get("show_provider") == "y");
  3685. if (e.Get("size_limit")) {
  3686. opts.SizeLimit = FromString<size_t>(e.Get("size_limit"));
  3687. }
  3688. logTrackExtractor.OutputSample(distBy, sel_x1, sel_x2, opts, printer);
  3689. printer.Output(ss);
  3690. out << HTTPOKTEXT;
  3691. out << ss.Str();
  3692. } else {
  3693. TLogTextPrinter printer(e);
  3694. for (const TString& id : Subvalues(e, "id")) {
  3695. CheckAdHocTrace(id, TDuration::Minutes(1));
  3696. TraceMngr->ReadLog(id, printer);
  3697. TraceMngr->ReadDepot(id, printer);
  3698. }
  3699. printer.Output(ss);
  3700. out << HTTPOKTEXT;
  3701. out << ss.Str();
  3702. }
  3703. }
  3704. }
  3705. void OutputQuery(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3706. {
  3707. if (request.GetParams().NumOfValues("id") == 0) {
  3708. ythrow yexception() << "Cgi-parameter 'id' is not specified";
  3709. } else {
  3710. TString id = request.GetParams().Get("id");
  3711. const NLWTrace::TQuery& query = TraceMngr->GetTrace(id)->GetQuery();
  3712. TString queryStr = query.DebugString();
  3713. WWW_HTML(out) {
  3714. out << "<h2>Trace Query: " << id << "</h2><pre>" << queryStr;
  3715. }
  3716. }
  3717. }
  3718. void OutputBuilder(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  3719. {
  3720. Y_UNUSED(request);
  3721. WWW_HTML(out) {
  3722. OutputNavbar(request, out);
  3723. out << "<form class=\"form-horizontal\" action=\"?mode=new&ui=y\" method=\"POST\">";
  3724. DIV_CLASS("form-group") {
  3725. LABEL_CLASS_FOR("col-sm-1 control-label", "inputId") { out << "Name"; }
  3726. DIV_CLASS("col-sm-11") {
  3727. out << "<input class=\"form-control\" id=\"inputId\" name=\"id\" placeholder=\"mytrace\">";
  3728. }
  3729. }
  3730. DIV_CLASS("form-group") {
  3731. LABEL_CLASS_FOR("col-sm-1 control-label", "textareaQuery") { out << "Query"; }
  3732. DIV_CLASS("col-sm-11") {
  3733. out << "<textarea class=\"form-control\" id=\"textareaQuery\" name=\"query\" rows=\"10\"></textarea>";
  3734. }
  3735. }
  3736. DIV_CLASS("form-group") {
  3737. DIV_CLASS("col-sm-offset-1 col-sm-11") {
  3738. out << "<button type=\"submit\" class=\"btn btn-default\">Trace</button>";
  3739. }
  3740. }
  3741. out << "</form>";
  3742. }
  3743. }
  3744. void OutputAnalytics(const NMonitoring::IMonHttpRequest& request, TStringStream& out)
  3745. {
  3746. using namespace NAnalytics;
  3747. const TCgiParameters& e = request.GetParams();
  3748. TLogSources logSources(Cleaner);
  3749. TraceMngr->ReadTraces(logSources);
  3750. ReadSnapshots(logSources);
  3751. RequireMultipleSelection(out, e, "id", "Analyze ", ListTraces(logSources));
  3752. THolder<TLogFilter> logFilter;
  3753. TLogAnalyzer* logAnalyzer = nullptr;
  3754. TLogTrackExtractor* logTracks = nullptr;
  3755. if (request.GetParams().Get("aggr") == "tracks") {
  3756. logFilter.Reset(logTracks = new TLogTrackExtractor(e,
  3757. Subvalues(request.GetParams(), "f"),
  3758. Subvalues(request.GetParams(), "g")
  3759. ));
  3760. for (const TString& id : Subvalues(request.GetParams(), "id")) {
  3761. CheckAdHocTrace(id, TDuration::Minutes(1));
  3762. TraceMngr->ReadLog(id, *logTracks);
  3763. TraceMngr->ReadDepot(id, *logTracks);
  3764. }
  3765. } else {
  3766. logFilter.Reset(logAnalyzer = new TLogAnalyzer(
  3767. Subvalues(request.GetParams(), "f"),
  3768. Subvalues(request.GetParams(), "g"),
  3769. request.GetParams().Get("cutts") == "y"
  3770. ));
  3771. for (const TString& id : Subvalues(request.GetParams(), "id")) {
  3772. CheckAdHocTrace(id, TDuration::Minutes(1));
  3773. TraceMngr->ReadLog(id, *logAnalyzer);
  3774. TraceMngr->ReadDepot(id, *logAnalyzer);
  3775. }
  3776. }
  3777. logFilter->FilterSelectors(out, e, "f");
  3778. OptionalMultipleSelection(out, e, "g", "group by", logFilter->ListParamNames());
  3779. {
  3780. auto paramNamesList = logFilter->ListParamNames();
  3781. if (e.Get("aggr") == "tracks") {
  3782. paramNamesList.emplace_back("_trackMs", "_trackMs");
  3783. }
  3784. OptionalSelection(out, e, "s", "order by", paramNamesList);
  3785. }
  3786. if (e.Get("s")) {
  3787. TVariants variants;
  3788. variants.emplace_back("", "asc");
  3789. variants.emplace_back("y", "desc");
  3790. DropdownSelector<Link>(out, e, "reverse", e.Get("reverse"), "", variants);
  3791. }
  3792. TString aggr = e.Get("aggr");
  3793. TVariants variants1; // MSVS2013 doesn't understand complex initializer lists
  3794. variants1.emplace_back("", "without aggregation");
  3795. variants1.emplace_back("hist", "as histogram");
  3796. variants1.emplace_back("tracks", "tracks");
  3797. DropdownSelector<Link>(out, e, "aggr", e.Get("aggr"), "", variants1);
  3798. unsigned refresh = e.Get("refresh")?
  3799. FromString<unsigned>(e.Get("refresh")):
  3800. 1000;
  3801. if (aggr == "tracks") {
  3802. TVariants ileVars;
  3803. ileVars.emplace_back("0", "0");
  3804. ileVars.emplace_back("25", "25");
  3805. ileVars.emplace_back("50", "50");
  3806. ileVars.emplace_back("75", "75");
  3807. ileVars.emplace_back("", "90");
  3808. ileVars.emplace_back("95", "95");
  3809. ileVars.emplace_back("99", "99");
  3810. ileVars.emplace_back("99.9", "99.9");
  3811. ileVars.emplace_back("100", "100");
  3812. DropdownSelector<Link>(out, e, "ile", e.Get("ile"), "and show", ileVars);
  3813. out << "%-ile. ";
  3814. TString patternAnalyzer;
  3815. TString distBy;
  3816. TString distType;
  3817. if (e.Get("pattern")) {
  3818. TVariants analyzePatternVars;
  3819. analyzePatternVars.emplace_back("resTotal", "distribution by total");
  3820. analyzePatternVars.emplace_back("resLast", "distribution by last");
  3821. analyzePatternVars.emplace_back("covMatrix", "covariance matrix");
  3822. DropdownSelector<Link>(
  3823. out, e, "ptrn_anlz", e.Get("ptrn_anlz"),
  3824. "Pattern", analyzePatternVars
  3825. );
  3826. patternAnalyzer = e.Get("ptrn_anlz");
  3827. TVariants distTypeVars;
  3828. distTypeVars.emplace_back("", "as is");
  3829. distTypeVars.emplace_back("-stack", "cumulative");
  3830. DropdownSelector<Link>(out, e, "dist_type", e.Get("dist_type"), "", distTypeVars);
  3831. distType = e.Get("dist_type");
  3832. } else {
  3833. out << "<i>Select pattern for more options</i>";
  3834. }
  3835. logTracks->Run();
  3836. if (e.Get("download") == "y") {
  3837. out.Clear();
  3838. out <<
  3839. "HTTP/1.1 200 Ok\r\n"
  3840. "Content-Type: application/force-download\r\n"
  3841. "Content-Transfer-Encoding: binary\r\n"
  3842. "Content-Disposition: attachment; filename=\"trace_chrome.json\"\r\n"
  3843. "\r\n"
  3844. ;
  3845. logTracks->OutputChromeTrace(out, e);
  3846. return;
  3847. }
  3848. NAnalytics::TTable distData;
  3849. bool showSample = false;
  3850. TLogTextPrinter printer(e);
  3851. if (patternAnalyzer == "resTotal" || patternAnalyzer == "resLast") {
  3852. distBy = patternAnalyzer;
  3853. distData = logTracks->Distribution(distBy, "", "", e.Get("width"));
  3854. double sel_x1 = e.Get("sel_x1")? ParseDouble(e.Get("sel_x1")): NAN;
  3855. double sel_x2 = e.Get("sel_x2")? ParseDouble(e.Get("sel_x2")): NAN;
  3856. if (!isnan(sel_x1) && !isnan(sel_x2)) {
  3857. showSample = true;
  3858. TSampleOpts opts;
  3859. opts.ShowProvider = (e.Get("show_provider") == "y");
  3860. if (e.Get("size_limit")) {
  3861. opts.SizeLimit = FromString<size_t>(e.Get("size_limit"));
  3862. }
  3863. logTracks->OutputSample(distBy, sel_x1, sel_x2, opts, printer);
  3864. }
  3865. }
  3866. TString selectors = out.Str();
  3867. out.Clear();
  3868. out << NMonitoring::HTTPOKHTML;
  3869. out << "<!DOCTYPE html>" << Endl;
  3870. HTML(out) {
  3871. HTML_TAG() {
  3872. HEAD() {
  3873. out << NResource::Find("lwtrace/mon/static/analytics.header.html") << Endl;
  3874. if (distBy) {
  3875. out <<
  3876. "<script type=\"text/javascript\">\n"
  3877. "$(function() {\n"
  3878. " var dataurl = null;\n"
  3879. " var datajson = " << ToJsonFlot(distData, distBy, {"_count_sum" + distType}) << ";\n"
  3880. " var refreshPeriod = 0;\n"
  3881. " var xn = \"" << distBy << "\";\n"
  3882. " var navigate = false;\n"
  3883. << NResource::Find("lwtrace/mon/static/analytics.js") <<
  3884. " embededMode();"
  3885. " enableSelection();"
  3886. "});\n"
  3887. "</script>\n";
  3888. }
  3889. // Show download button
  3890. out <<
  3891. "<script type=\"text/javascript\">"
  3892. "$(function() {"
  3893. " $(\"#download-btn\").click(function(){window.location.href='"
  3894. << MakeUrlAdd(e, "download", "y") <<
  3895. "';});"
  3896. " $(\"#download-btn\").removeClass(\"hidden\");"
  3897. "});"
  3898. "</script>\n";
  3899. }
  3900. BODY() {
  3901. // Wrap selectors with navbar
  3902. { TSelectorsContainer sc(out);
  3903. out << selectors;
  3904. }
  3905. logTracks->OutputTable(out, e);
  3906. if (distBy) {
  3907. out << NResource::Find("lwtrace/mon/static/analytics.flot.html") << Endl;
  3908. if (showSample) {
  3909. static const THashSet<TString> keepParams = {
  3910. "f",
  3911. "g",
  3912. "head",
  3913. "tail",
  3914. "s",
  3915. "reverse",
  3916. "cutts",
  3917. "showts",
  3918. "show_provider",
  3919. "size_limit",
  3920. "aggr",
  3921. "id",
  3922. "pattern",
  3923. "ptrn_anlz",
  3924. "sel_x1",
  3925. "sel_x2"
  3926. };
  3927. TCgiParameters cgiParams;
  3928. for (const auto& kv : request.GetParams()) {
  3929. if (keepParams.count(kv.first)) {
  3930. cgiParams.insert(kv);
  3931. }
  3932. }
  3933. cgiParams.insert(std::pair<TString, TString>("mode", "log"));
  3934. BtnHref<Button|Medium>(out, "Open logs", MakeUrlAdd(cgiParams, "format", "analytics"));
  3935. out << "<pre>\n";
  3936. printer.Output(out);
  3937. out << "</pre>\n";
  3938. }
  3939. }
  3940. if (patternAnalyzer == "covMatrix") {
  3941. logTracks->OutputSliceCovarianceMatrix(out, e);
  3942. }
  3943. }
  3944. }
  3945. }
  3946. } else {
  3947. double width = e.Get("width")? FromString<double>(e.Get("width")): 99;
  3948. NAnalytics::TTable data;
  3949. if (aggr == "") {
  3950. data = logAnalyzer->GetTable();
  3951. } else if (aggr == "hist") {
  3952. RequireSelection(out, e, "bn", "by", logFilter->ListParamNames());
  3953. const NAnalytics::TTable& inputTable = logAnalyzer->GetTable();
  3954. TString bn = e.Get("bn");
  3955. double b1 = e.Get("b1")? FromString<double>(e.Get("b1")): MinValue(bn, inputTable);
  3956. double b2 = e.Get("b2")? FromString<double>(e.Get("b2")): MaxValue(bn, inputTable);
  3957. if (isfinite(b1) && isfinite(b2)) {
  3958. WWW_CHECK(b1 <= b2, "invalid xrange [%le; %le]", b1, b2);
  3959. double dx = e.Get("dx")? FromString<double>(e.Get("dx")): (b2-b1)/width;
  3960. data = HistogramAll(inputTable, e.Get("bn"), b1, b2, dx);
  3961. } else {
  3962. // Empty table -- it's ok -- leave data table empty
  3963. }
  3964. }
  3965. TString xn = e.Get("xn");
  3966. TString outFormat = e.Get("out");
  3967. TVariants variants2;
  3968. variants2.emplace_back("html", "table");
  3969. variants2.emplace_back("flot", "chart");
  3970. variants2.emplace_back("gantt", "gantt");
  3971. variants2.emplace_back("text", "text");
  3972. variants2.emplace_back("csv", "CSV");
  3973. variants2.emplace_back("json_flot", "JSON");
  3974. RequireSelection(out, e, "out", "and show", variants2);
  3975. if (outFormat == "csv") {
  3976. TString sep = e.Get("sep")? e.Get("sep"): TString("\t");
  3977. out.Clear();
  3978. out << NMonitoring::HTTPOKTEXT;
  3979. out << ToCsv(data, sep, e.Get("head") != "n");
  3980. } else if (outFormat == "html") {
  3981. TString selectors = out.Str();
  3982. out.Clear();
  3983. WWW_HTML(out) {
  3984. // Wrap selectors with navbar
  3985. { TSelectorsContainer sc(out);
  3986. out << selectors;
  3987. }
  3988. out << ToHtml(data);
  3989. }
  3990. } else if (outFormat == "json_flot") {
  3991. SeriesSelectors(out, e, "xn", "yns", data);
  3992. out.Clear();
  3993. out << NMonitoring::HTTPOKJSON;
  3994. out << ToJsonFlot(data, xn, SplitString(e.Get("yns"), ":"));
  3995. } else if (outFormat == "flot") {
  3996. SeriesSelectors(out, e, "xn", "yns", data);
  3997. TString selectors = out.Str();
  3998. TVector<TString> ynos = SplitString(e.Get("yns"), ":");
  3999. out.Clear();
  4000. out << NMonitoring::HTTPOKHTML;
  4001. out << "<!DOCTYPE html>" << Endl;
  4002. HTML(out) {
  4003. HTML_TAG() {
  4004. HEAD() {
  4005. out << NResource::Find("lwtrace/mon/static/analytics.header.html") << Endl;
  4006. out <<
  4007. "<script type=\"text/javascript\">\n"
  4008. "$(function() {\n"
  4009. " var dataurl = \"" << EscapeJSONString(MakeUrl(e, "out", "json_flot")) << "\";\n"
  4010. " var refreshPeriod = " << refresh << ";\n"
  4011. " var xn = \"" << ParseName(xn) << "\";\n"
  4012. " var navigate = true;\n"
  4013. << NResource::Find("lwtrace/mon/static/analytics.js") <<
  4014. "});\n"
  4015. "</script>\n"
  4016. ;
  4017. }
  4018. BODY() {
  4019. // Wrap selectors with navbar
  4020. { TSelectorsContainer sc(out);
  4021. out << selectors;
  4022. }
  4023. out << NResource::Find("lwtrace/mon/static/analytics.flot.html") << Endl;
  4024. }
  4025. }
  4026. }
  4027. } else if (outFormat == "gantt") {
  4028. TString selectors = out.Str();
  4029. out.Clear();
  4030. out << NMonitoring::HTTPOKHTML;
  4031. out << "<!DOCTYPE html>" << Endl;
  4032. HTML(out) {
  4033. HTML_TAG() {
  4034. HEAD() {
  4035. out << NResource::Find("lwtrace/mon/static/analytics.header.html") << Endl;
  4036. out <<
  4037. "<script type=\"text/javascript\">\n"
  4038. "$(function() {\n"
  4039. " var dataurl = \"" << EscapeJSONString(MakeUrl(e, {{"mode", "log"}, {"format", "json2"}, {"gantt",""}})) << "\";\n"
  4040. " var refreshPeriod = " << refresh << ";\n"
  4041. " var xn = \"" << ParseName(xn) << "\";\n"
  4042. " var navigate = true;\n"
  4043. << NResource::Find("lwtrace/mon/static/analytics.js") <<
  4044. "});\n"
  4045. "</script>\n"
  4046. ;
  4047. }
  4048. BODY() {
  4049. // Wrap selectors with navbar
  4050. { TSelectorsContainer sc(out);
  4051. out << selectors;
  4052. }
  4053. out << NResource::Find("lwtrace/mon/static/analytics.gantt.html") << Endl;
  4054. }
  4055. }
  4056. }
  4057. } else if (outFormat = "text") {
  4058. out << " <input type='text' id='logsLimit' size='2' placeholder='Limit'>" << Endl;
  4059. out <<
  4060. R"END(<script>
  4061. {
  4062. var url = new URL(window.location.href);
  4063. if (url.searchParams.has('head')) {
  4064. document.getElementById('logsLimit').value = url.searchParams.get('head');
  4065. }
  4066. }
  4067. $('#logsLimit').on('keypress', function(ev) {
  4068. if (ev.keyCode == 13) {
  4069. var url = new URL(window.location.href);
  4070. var limit_value = document.getElementById('logsLimit').value;
  4071. if (limit_value && !isNaN(limit_value)) {
  4072. url.searchParams.set('head', limit_value);
  4073. window.location.href = url.toString();
  4074. } else if (!limit_value) {
  4075. url.searchParams.delete('head');
  4076. window.location.href = url.toString();
  4077. }
  4078. }
  4079. });
  4080. </script>)END";
  4081. TString selectors = out.Str();
  4082. TLogTextPrinter printer(e);
  4083. TStringStream ss;
  4084. for (const TString& id : Subvalues(e, "id")) {
  4085. CheckAdHocTrace(id, TDuration::Minutes(1));
  4086. TraceMngr->ReadLog(id, printer);
  4087. TraceMngr->ReadDepot(id, printer);
  4088. }
  4089. printer.Output(ss);
  4090. out.Clear();
  4091. out << NMonitoring::HTTPOKHTML;
  4092. out << "<!DOCTYPE html>" << Endl;
  4093. HTML(out) {
  4094. HTML_TAG() {
  4095. HEAD() {
  4096. out << NResource::Find("lwtrace/mon/static/analytics.header.html") << Endl;
  4097. }
  4098. BODY() {
  4099. // Wrap selectors with navbar
  4100. { TSelectorsContainer sc(out);
  4101. out << selectors;
  4102. }
  4103. static const THashSet<TString> keepParams = {
  4104. "s",
  4105. "head",
  4106. "reverse",
  4107. "cutts",
  4108. "showts",
  4109. "id",
  4110. "out"
  4111. };
  4112. TCgiParameters cgiParams;
  4113. for (const auto& kv : request.GetParams()) {
  4114. if (keepParams.count(kv.first)) {
  4115. cgiParams.insert(kv);
  4116. }
  4117. }
  4118. cgiParams.insert(std::pair<TString, TString>("mode", "analytics"));
  4119. auto toggledButton = [&out, &e, &cgiParams] (const TString& label, const TString& cgiKey) {
  4120. if (e.Get(cgiKey) == "y") {
  4121. BtnHref<Button|Medium>(out, label, MakeUrlErase(cgiParams, cgiKey, "y"), true);
  4122. } else {
  4123. BtnHref<Button|Medium>(out, label, MakeUrlAdd(cgiParams, cgiKey, "y"));
  4124. }
  4125. };
  4126. toggledButton("Cut Tails", "cutts");
  4127. toggledButton("Relative Time", "showts");
  4128. cgiParams.erase("mode");
  4129. cgiParams.insert(std::pair<TString, TString>("mode", "log"));
  4130. BtnHref<Button|Medium>(out, "Fullscreen", MakeUrlAdd(cgiParams, "format", "text"));
  4131. out << "<pre>\n";
  4132. out << ss.Str() << Endl;
  4133. out << "</pre>\n";
  4134. }
  4135. }
  4136. }
  4137. }
  4138. }
  4139. }
  4140. TDuration GetGetTimeout(const NMonitoring::IMonHttpRequest& request)
  4141. {
  4142. return (request.GetParams().Has("timeout")?
  4143. TDuration::Seconds(FromString<double>(request.GetParams().Get("timeout"))):
  4144. TDuration::Max());
  4145. }
  4146. void PostNew(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  4147. {
  4148. WWW_CHECK(request.GetPostParams().Has("id"), "POST parameter 'id' is not specified");
  4149. const TString& id = request.GetPostParams().Get("id");
  4150. bool ui = (request.GetParams().Get("ui") == "y");
  4151. TDuration timeout = GetGetTimeout(request);
  4152. if (!CheckAdHocTrace(id, timeout)) {
  4153. NLWTrace::TQuery query;
  4154. TString queryStr = request.GetPostParams().Get("query");
  4155. if (!ui) {
  4156. queryStr = Base64Decode(queryStr); // Needed for trace.sh (historically)
  4157. }
  4158. WWW_CHECK(queryStr, "Empty trace query");
  4159. bool parsed = NProtoBuf::TextFormat::ParseFromString(queryStr, &query);
  4160. WWW_CHECK(parsed, "Trace query text protobuf parse failed"); // TODO[serxa]: report error line/col and message
  4161. TraceMngr->New(id, query);
  4162. Cleaner.Postpone(id, timeout, false);
  4163. } else {
  4164. WWW_CHECK(!request.GetPostParams().Has("query"), "trace id '%s' is reserved for ad-hoc traces", id.data());
  4165. }
  4166. if (ui) {
  4167. WWW_HTML(out) {
  4168. out <<
  4169. "<div class=\"jumbotron alert-success\">"
  4170. "<h2>Trace created successfully</h2>"
  4171. "</div>"
  4172. "<script type=\"text/javascript\">\n"
  4173. "$(function() {\n"
  4174. " setTimeout(function() {"
  4175. " window.location.replace('?');"
  4176. " }, 1000);"
  4177. "});\n"
  4178. "</script>\n";
  4179. }
  4180. } else {
  4181. out << HTTPOKTEXT;
  4182. out << "OK\n";
  4183. }
  4184. }
  4185. void PostDelete(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  4186. {
  4187. WWW_CHECK(request.GetPostParams().Has("id"), "POST parameter 'id' is not specified");
  4188. const TString& id = request.GetPostParams().Get("id");
  4189. bool ui = (request.GetParams().Get("ui") == "y");
  4190. TraceMngr->Delete(id);
  4191. Cleaner.Forget(id);
  4192. if (ui) {
  4193. WWW_HTML(out) {
  4194. out <<
  4195. "<div class=\"jumbotron alert-success\">"
  4196. "<h2>Trace deleted successfully</h2>"
  4197. "</div>"
  4198. "<script type=\"text/javascript\">\n"
  4199. "$(function() {\n"
  4200. " setTimeout(function() {"
  4201. " window.location.replace('?');"
  4202. " }, 1000);"
  4203. "});\n"
  4204. "</script>\n";
  4205. }
  4206. } else {
  4207. out << HTTPOKTEXT;
  4208. out << "OK\n";
  4209. }
  4210. }
  4211. void PostSnapshot(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  4212. {
  4213. WWW_CHECK(request.GetPostParams().Has("id"), "POST parameter 'id' is not specified");
  4214. const TString& id = request.GetPostParams().Get("id");
  4215. bool ui = (request.GetParams().Get("ui") == "y");
  4216. TInstant now = TInstant::Now();
  4217. TGuard<TMutex> g(SnapshotsMtx);
  4218. const NLWTrace::TSession* trace = TraceMngr->GetTrace(id);
  4219. struct tm tm0;
  4220. TString sid = id + Strftime("_%Y%m%d-%H%M%S", now.GmTime(&tm0));
  4221. TAtomicSharedPtr<NLWTrace::TLogPb>& pbPtr = Snapshots[sid];
  4222. pbPtr.Reset(new NLWTrace::TLogPb());
  4223. trace->ToProtobuf(*pbPtr);
  4224. pbPtr->SetName(sid);
  4225. if (ui) {
  4226. WWW_HTML(out) {
  4227. out <<
  4228. "<div class=\"jumbotron alert-success\">"
  4229. "<h2>Snapshot created successfully</h2>"
  4230. "</div>"
  4231. "<script type=\"text/javascript\">\n"
  4232. "$(function() {\n"
  4233. " setTimeout(function() {"
  4234. " window.location.replace('?');"
  4235. " }, 1000);"
  4236. "});\n"
  4237. "</script>\n";
  4238. }
  4239. } else {
  4240. out << HTTPOKTEXT;
  4241. out << "OK\n";
  4242. }
  4243. }
  4244. void PostSetTimeout(const NMonitoring::IMonHttpRequest& request, IOutputStream& out)
  4245. {
  4246. WWW_CHECK(request.GetPostParams().Has("id"), "POST parameter 'id' is not specified");
  4247. const TString& id = request.GetPostParams().Get("id");
  4248. TDuration timeout = GetGetTimeout(request);
  4249. bool ui = (request.GetParams().Get("ui") == "y");
  4250. Cleaner.Postpone(id, timeout, true);
  4251. if (ui) {
  4252. WWW_HTML(out) {
  4253. out <<
  4254. "<div class=\"jumbotron alert-success\">"
  4255. "<h2>Timeout changed successfully</h2>"
  4256. "</div>"
  4257. "<script type=\"text/javascript\">\n"
  4258. "$(function() {\n"
  4259. " setTimeout(function() {"
  4260. " window.location.replace('?');"
  4261. " }, 1000);"
  4262. "});\n"
  4263. "</script>\n";
  4264. }
  4265. } else {
  4266. out << HTTPOKTEXT;
  4267. out << "OK\n";
  4268. }
  4269. }
  4270. void RegisterDashboard(const TString& dashConfig) {
  4271. g_DashboardRegistry.Register(dashConfig);
  4272. }
  4273. private:
  4274. // Returns true iff trace is ad-hoc and ensures trace is created
  4275. bool CheckAdHocTrace(const TString& id, TDuration timeout)
  4276. {
  4277. TAdHocTraceConfig cfg;
  4278. if (cfg.ParseId(id)) {
  4279. if (!TraceMngr->HasTrace(id)) {
  4280. TraceMngr->New(id, cfg.Query());
  4281. }
  4282. Cleaner.Postpone(id, timeout, false);
  4283. return true;
  4284. }
  4285. return false;
  4286. }
  4287. };
  4288. void RegisterPages(NMonitoring::TIndexMonPage* index, bool allowUnsafe) {
  4289. THolder<NLwTraceMonPage::TLWTraceMonPage> p = MakeHolder<NLwTraceMonPage::TLWTraceMonPage>(allowUnsafe);
  4290. index->Register(p.Release());
  4291. #define WWW_STATIC_FILE(file, type) \
  4292. index->Register(new TResourceMonPage(file, file, NMonitoring::TResourceMonPage::type));
  4293. WWW_STATIC_FILE("lwtrace/mon/static/common.css", CSS);
  4294. WWW_STATIC_FILE("lwtrace/mon/static/common.js", JAVASCRIPT);
  4295. WWW_STATIC_FILE("lwtrace/mon/static/css/bootstrap.min.css", CSS);
  4296. WWW_STATIC_FILE("lwtrace/mon/static/css/d3-gantt.css", CSS);
  4297. WWW_STATIC_FILE("lwtrace/mon/static/css/jquery.treegrid.css", CSS);
  4298. WWW_STATIC_FILE("lwtrace/mon/static/analytics.css", CSS);
  4299. WWW_STATIC_FILE("lwtrace/mon/static/fonts/glyphicons-halflings-regular.eot", FONT_EOT);
  4300. WWW_STATIC_FILE("lwtrace/mon/static/fonts/glyphicons-halflings-regular.svg", SVG);
  4301. WWW_STATIC_FILE("lwtrace/mon/static/fonts/glyphicons-halflings-regular.ttf", FONT_TTF);
  4302. WWW_STATIC_FILE("lwtrace/mon/static/fonts/glyphicons-halflings-regular.woff2", FONT_WOFF2);
  4303. WWW_STATIC_FILE("lwtrace/mon/static/fonts/glyphicons-halflings-regular.woff", FONT_WOFF);
  4304. WWW_STATIC_FILE("lwtrace/mon/static/img/collapse.png", PNG);
  4305. WWW_STATIC_FILE("lwtrace/mon/static/img/expand.png", PNG);
  4306. WWW_STATIC_FILE("lwtrace/mon/static/img/file.png", PNG);
  4307. WWW_STATIC_FILE("lwtrace/mon/static/img/folder.png", PNG);
  4308. WWW_STATIC_FILE("lwtrace/mon/static/js/bootstrap.min.js", JAVASCRIPT);
  4309. WWW_STATIC_FILE("lwtrace/mon/static/js/d3.v4.min.js", JAVASCRIPT);
  4310. WWW_STATIC_FILE("lwtrace/mon/static/js/d3-gantt.js", JAVASCRIPT);
  4311. WWW_STATIC_FILE("lwtrace/mon/static/js/d3-tip-0.8.0-alpha.1.js", JAVASCRIPT);
  4312. WWW_STATIC_FILE("lwtrace/mon/static/js/filesaver.min.js", JAVASCRIPT);
  4313. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.flot.extents.js", JAVASCRIPT);
  4314. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.flot.min.js", JAVASCRIPT);
  4315. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.flot.navigate.min.js", JAVASCRIPT);
  4316. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.flot.selection.min.js", JAVASCRIPT);
  4317. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.min.js", JAVASCRIPT);
  4318. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.treegrid.bootstrap3.js", JAVASCRIPT);
  4319. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.treegrid.min.js", JAVASCRIPT);
  4320. WWW_STATIC_FILE("lwtrace/mon/static/js/jquery.url.min.js", JAVASCRIPT);
  4321. #undef WWW_STATIC_FILE
  4322. }
  4323. NLWTrace::TProbeRegistry& ProbeRegistry() {
  4324. return g_Probes;
  4325. }
  4326. NLWTrace::TManager& TraceManager(bool allowUnsafe) {
  4327. return allowUnsafe? g_UnsafeManager: g_SafeManager;
  4328. }
  4329. TDashboardRegistry& DashboardRegistry() {
  4330. return g_DashboardRegistry;
  4331. }
  4332. } // namespace NLwTraceMonPage