apps_plugin.c 217 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. /*
  3. * netdata apps.plugin
  4. * (C) Copyright 2023 Netdata Inc.
  5. * Released under GPL v3+
  6. */
  7. #include "collectors/all.h"
  8. #include "libnetdata/libnetdata.h"
  9. #include "libnetdata/required_dummies.h"
  10. #define APPS_PLUGIN_PROCESSES_FUNCTION_DESCRIPTION "Detailed information on the currently running processes."
  11. #define APPS_PLUGIN_FUNCTIONS() do { \
  12. fprintf(stdout, PLUGINSD_KEYWORD_FUNCTION " \"processes\" %d \"%s\"\n", PLUGINS_FUNCTIONS_TIMEOUT_DEFAULT, APPS_PLUGIN_PROCESSES_FUNCTION_DESCRIPTION); \
  13. } while(0)
  14. #define APPS_PLUGIN_GLOBAL_FUNCTIONS() do { \
  15. fprintf(stdout, PLUGINSD_KEYWORD_FUNCTION " GLOBAL \"processes\" %d \"%s\"\n", PLUGINS_FUNCTIONS_TIMEOUT_DEFAULT, APPS_PLUGIN_PROCESSES_FUNCTION_DESCRIPTION); \
  16. } while(0)
  17. // ----------------------------------------------------------------------------
  18. // debugging
  19. static int debug_enabled = 0;
  20. static inline void debug_log_int(const char *fmt, ... ) {
  21. va_list args;
  22. fprintf( stderr, "apps.plugin: ");
  23. va_start( args, fmt );
  24. vfprintf( stderr, fmt, args );
  25. va_end( args );
  26. fputc('\n', stderr);
  27. }
  28. #ifdef NETDATA_INTERNAL_CHECKS
  29. #define debug_log(fmt, args...) do { if(unlikely(debug_enabled)) debug_log_int(fmt, ##args); } while(0)
  30. #else
  31. static inline void debug_log_dummy(void) {}
  32. #define debug_log(fmt, args...) debug_log_dummy()
  33. #endif
  34. // ----------------------------------------------------------------------------
  35. #ifdef __FreeBSD__
  36. #include <sys/user.h>
  37. #endif
  38. // ----------------------------------------------------------------------------
  39. // per O/S configuration
  40. // the minimum PID of the system
  41. // this is also the pid of the init process
  42. #define INIT_PID 1
  43. // if the way apps.plugin will work, will read the entire process list,
  44. // including the resource utilization of each process, instantly
  45. // set this to 1
  46. // when set to 0, apps.plugin builds a sort list of processes, in order
  47. // to process children processes, before parent processes
  48. #ifdef __FreeBSD__
  49. #define ALL_PIDS_ARE_READ_INSTANTLY 1
  50. #else
  51. #define ALL_PIDS_ARE_READ_INSTANTLY 0
  52. #endif
  53. // ----------------------------------------------------------------------------
  54. // string lengths
  55. #define MAX_COMPARE_NAME 100
  56. #define MAX_NAME 100
  57. #define MAX_CMDLINE 16384
  58. // ----------------------------------------------------------------------------
  59. // the rates we are going to send to netdata will have this detail a value of:
  60. // - 1 will send just integer parts to netdata
  61. // - 100 will send 2 decimal points
  62. // - 1000 will send 3 decimal points
  63. // etc.
  64. #define RATES_DETAIL 10000ULL
  65. // ----------------------------------------------------------------------------
  66. // factor for calculating correct CPU time values depending on units of raw data
  67. static unsigned int time_factor = 0;
  68. // ----------------------------------------------------------------------------
  69. // to avoid reallocating too frequently, we can increase the number of spare
  70. // file descriptors used by processes.
  71. // IMPORTANT:
  72. // having a lot of spares, increases the CPU utilization of the plugin.
  73. #define MAX_SPARE_FDS 1
  74. // ----------------------------------------------------------------------------
  75. // command line options
  76. static int
  77. update_every = 1,
  78. enable_guest_charts = 0,
  79. #ifdef __FreeBSD__
  80. enable_file_charts = 0,
  81. #else
  82. enable_file_charts = 1,
  83. max_fds_cache_seconds = 60,
  84. #endif
  85. enable_function_cmdline = 0,
  86. enable_detailed_uptime_charts = 0,
  87. enable_users_charts = 1,
  88. enable_groups_charts = 1,
  89. include_exited_childs = 1;
  90. // will be changed to getenv(NETDATA_USER_CONFIG_DIR) if it exists
  91. static char *user_config_dir = CONFIG_DIR;
  92. static char *stock_config_dir = LIBCONFIG_DIR;
  93. // some variables for keeping track of processes count by states
  94. typedef enum {
  95. PROC_STATUS_RUNNING = 0,
  96. PROC_STATUS_SLEEPING_D, // uninterruptible sleep
  97. PROC_STATUS_SLEEPING, // interruptible sleep
  98. PROC_STATUS_ZOMBIE,
  99. PROC_STATUS_STOPPED,
  100. PROC_STATUS_END, //place holder for ending enum fields
  101. } proc_state;
  102. #ifndef __FreeBSD__
  103. static proc_state proc_state_count[PROC_STATUS_END];
  104. static const char *proc_states[] = {
  105. [PROC_STATUS_RUNNING] = "running",
  106. [PROC_STATUS_SLEEPING] = "sleeping_interruptible",
  107. [PROC_STATUS_SLEEPING_D] = "sleeping_uninterruptible",
  108. [PROC_STATUS_ZOMBIE] = "zombie",
  109. [PROC_STATUS_STOPPED] = "stopped",
  110. };
  111. #endif
  112. // ----------------------------------------------------------------------------
  113. // internal flags
  114. // handled in code (automatically set)
  115. // log each problem once per process
  116. // log flood protection flags (log_thrown)
  117. typedef enum __attribute__((packed)) {
  118. PID_LOG_IO = (1 << 0),
  119. PID_LOG_STATUS = (1 << 1),
  120. PID_LOG_CMDLINE = (1 << 2),
  121. PID_LOG_FDS = (1 << 3),
  122. PID_LOG_STAT = (1 << 4),
  123. PID_LOG_LIMITS = (1 << 5),
  124. PID_LOG_LIMITS_DETAIL = (1 << 6),
  125. } PID_LOG;
  126. static int
  127. show_guest_time = 0, // 1 when guest values are collected
  128. show_guest_time_old = 0,
  129. proc_pid_cmdline_is_needed = 0; // 1 when we need to read /proc/cmdline
  130. // ----------------------------------------------------------------------------
  131. // internal counters
  132. static size_t
  133. global_iterations_counter = 1,
  134. calls_counter = 0,
  135. file_counter = 0,
  136. filenames_allocated_counter = 0,
  137. inodes_changed_counter = 0,
  138. links_changed_counter = 0,
  139. targets_assignment_counter = 0;
  140. // ----------------------------------------------------------------------------
  141. // Normalization
  142. //
  143. // With normalization we lower the collected metrics by a factor to make them
  144. // match the total utilization of the system.
  145. // The discrepancy exists because apps.plugin needs some time to collect all
  146. // the metrics. This results in utilization that exceeds the total utilization
  147. // of the system.
  148. //
  149. // During normalization, we align the per-process utilization, to the total of
  150. // the system. We first consume the exited children utilization and it the
  151. // collected values is above the total, we proportionally scale each reported
  152. // metric.
  153. // the total system time, as reported by /proc/stat
  154. static kernel_uint_t
  155. global_utime = 0,
  156. global_stime = 0,
  157. global_gtime = 0;
  158. // the normalization ratios, as calculated by normalize_utilization()
  159. NETDATA_DOUBLE
  160. utime_fix_ratio = 1.0,
  161. stime_fix_ratio = 1.0,
  162. gtime_fix_ratio = 1.0,
  163. minflt_fix_ratio = 1.0,
  164. majflt_fix_ratio = 1.0,
  165. cutime_fix_ratio = 1.0,
  166. cstime_fix_ratio = 1.0,
  167. cgtime_fix_ratio = 1.0,
  168. cminflt_fix_ratio = 1.0,
  169. cmajflt_fix_ratio = 1.0;
  170. struct pid_on_target {
  171. int32_t pid;
  172. struct pid_on_target *next;
  173. };
  174. struct openfds {
  175. kernel_uint_t files;
  176. kernel_uint_t pipes;
  177. kernel_uint_t sockets;
  178. kernel_uint_t inotifies;
  179. kernel_uint_t eventfds;
  180. kernel_uint_t timerfds;
  181. kernel_uint_t signalfds;
  182. kernel_uint_t eventpolls;
  183. kernel_uint_t other;
  184. };
  185. #define pid_openfds_sum(p) ((p)->openfds.files + (p)->openfds.pipes + (p)->openfds.sockets + (p)->openfds.inotifies + (p)->openfds.eventfds + (p)->openfds.timerfds + (p)->openfds.signalfds + (p)->openfds.eventpolls + (p)->openfds.other)
  186. struct pid_limits {
  187. // kernel_uint_t max_cpu_time;
  188. // kernel_uint_t max_file_size;
  189. // kernel_uint_t max_data_size;
  190. // kernel_uint_t max_stack_size;
  191. // kernel_uint_t max_core_file_size;
  192. // kernel_uint_t max_resident_set;
  193. // kernel_uint_t max_processes;
  194. kernel_uint_t max_open_files;
  195. // kernel_uint_t max_locked_memory;
  196. // kernel_uint_t max_address_space;
  197. // kernel_uint_t max_file_locks;
  198. // kernel_uint_t max_pending_signals;
  199. // kernel_uint_t max_msgqueue_size;
  200. // kernel_uint_t max_nice_priority;
  201. // kernel_uint_t max_realtime_priority;
  202. // kernel_uint_t max_realtime_timeout;
  203. };
  204. // ----------------------------------------------------------------------------
  205. // target
  206. //
  207. // target is the structure that processes are aggregated to be reported
  208. // to netdata.
  209. //
  210. // - Each entry in /etc/apps_groups.conf creates a target.
  211. // - Each user and group used by a process in the system, creates a target.
  212. struct target {
  213. char compare[MAX_COMPARE_NAME + 1];
  214. uint32_t comparehash;
  215. size_t comparelen;
  216. char id[MAX_NAME + 1];
  217. uint32_t idhash;
  218. char name[MAX_NAME + 1];
  219. uid_t uid;
  220. gid_t gid;
  221. kernel_uint_t minflt;
  222. kernel_uint_t cminflt;
  223. kernel_uint_t majflt;
  224. kernel_uint_t cmajflt;
  225. kernel_uint_t utime;
  226. kernel_uint_t stime;
  227. kernel_uint_t gtime;
  228. kernel_uint_t cutime;
  229. kernel_uint_t cstime;
  230. kernel_uint_t cgtime;
  231. kernel_uint_t num_threads;
  232. // kernel_uint_t rss;
  233. kernel_uint_t status_vmsize;
  234. kernel_uint_t status_vmrss;
  235. kernel_uint_t status_vmshared;
  236. kernel_uint_t status_rssfile;
  237. kernel_uint_t status_rssshmem;
  238. kernel_uint_t status_vmswap;
  239. kernel_uint_t status_voluntary_ctxt_switches;
  240. kernel_uint_t status_nonvoluntary_ctxt_switches;
  241. kernel_uint_t io_logical_bytes_read;
  242. kernel_uint_t io_logical_bytes_written;
  243. kernel_uint_t io_read_calls;
  244. kernel_uint_t io_write_calls;
  245. kernel_uint_t io_storage_bytes_read;
  246. kernel_uint_t io_storage_bytes_written;
  247. kernel_uint_t io_cancelled_write_bytes;
  248. int *target_fds;
  249. int target_fds_size;
  250. struct openfds openfds;
  251. NETDATA_DOUBLE max_open_files_percent;
  252. kernel_uint_t starttime;
  253. kernel_uint_t collected_starttime;
  254. kernel_uint_t uptime_min;
  255. kernel_uint_t uptime_sum;
  256. kernel_uint_t uptime_max;
  257. unsigned int processes; // how many processes have been merged to this
  258. int exposed; // if set, we have sent this to netdata
  259. int hidden; // if set, we set the hidden flag on the dimension
  260. int debug_enabled;
  261. int ends_with;
  262. int starts_with; // if set, the compare string matches only the
  263. // beginning of the command
  264. struct pid_on_target *root_pid; // list of aggregated pids for target debugging
  265. struct target *target; // the one that will be reported to netdata
  266. struct target *next;
  267. };
  268. struct target
  269. *apps_groups_default_target = NULL, // the default target
  270. *apps_groups_root_target = NULL, // apps_groups.conf defined
  271. *users_root_target = NULL, // users
  272. *groups_root_target = NULL; // user groups
  273. size_t
  274. apps_groups_targets_count = 0; // # of apps_groups.conf targets
  275. // ----------------------------------------------------------------------------
  276. // pid_stat
  277. //
  278. // structure to store data for each process running
  279. // see: man proc for the description of the fields
  280. struct pid_fd {
  281. int fd;
  282. #ifndef __FreeBSD__
  283. ino_t inode;
  284. char *filename;
  285. uint32_t link_hash;
  286. size_t cache_iterations_counter;
  287. size_t cache_iterations_reset;
  288. #endif
  289. };
  290. struct pid_stat {
  291. int32_t pid;
  292. int32_t ppid;
  293. // int32_t pgrp;
  294. // int32_t session;
  295. // int32_t tty_nr;
  296. // int32_t tpgid;
  297. // uint64_t flags;
  298. char state;
  299. char comm[MAX_COMPARE_NAME + 1];
  300. char *cmdline;
  301. // these are raw values collected
  302. kernel_uint_t minflt_raw;
  303. kernel_uint_t cminflt_raw;
  304. kernel_uint_t majflt_raw;
  305. kernel_uint_t cmajflt_raw;
  306. kernel_uint_t utime_raw;
  307. kernel_uint_t stime_raw;
  308. kernel_uint_t gtime_raw; // guest_time
  309. kernel_uint_t cutime_raw;
  310. kernel_uint_t cstime_raw;
  311. kernel_uint_t cgtime_raw; // cguest_time
  312. // these are rates
  313. kernel_uint_t minflt;
  314. kernel_uint_t cminflt;
  315. kernel_uint_t majflt;
  316. kernel_uint_t cmajflt;
  317. kernel_uint_t utime;
  318. kernel_uint_t stime;
  319. kernel_uint_t gtime;
  320. kernel_uint_t cutime;
  321. kernel_uint_t cstime;
  322. kernel_uint_t cgtime;
  323. // int64_t priority;
  324. // int64_t nice;
  325. int32_t num_threads;
  326. // int64_t itrealvalue;
  327. kernel_uint_t collected_starttime;
  328. // kernel_uint_t vsize;
  329. // kernel_uint_t rss;
  330. // kernel_uint_t rsslim;
  331. // kernel_uint_t starcode;
  332. // kernel_uint_t endcode;
  333. // kernel_uint_t startstack;
  334. // kernel_uint_t kstkesp;
  335. // kernel_uint_t kstkeip;
  336. // uint64_t signal;
  337. // uint64_t blocked;
  338. // uint64_t sigignore;
  339. // uint64_t sigcatch;
  340. // uint64_t wchan;
  341. // uint64_t nswap;
  342. // uint64_t cnswap;
  343. // int32_t exit_signal;
  344. // int32_t processor;
  345. // uint32_t rt_priority;
  346. // uint32_t policy;
  347. // kernel_uint_t delayacct_blkio_ticks;
  348. uid_t uid;
  349. gid_t gid;
  350. kernel_uint_t status_voluntary_ctxt_switches_raw;
  351. kernel_uint_t status_nonvoluntary_ctxt_switches_raw;
  352. kernel_uint_t status_vmsize;
  353. kernel_uint_t status_vmrss;
  354. kernel_uint_t status_vmshared;
  355. kernel_uint_t status_rssfile;
  356. kernel_uint_t status_rssshmem;
  357. kernel_uint_t status_vmswap;
  358. kernel_uint_t status_voluntary_ctxt_switches;
  359. kernel_uint_t status_nonvoluntary_ctxt_switches;
  360. #ifndef __FreeBSD__
  361. ARL_BASE *status_arl;
  362. #endif
  363. kernel_uint_t io_logical_bytes_read_raw;
  364. kernel_uint_t io_logical_bytes_written_raw;
  365. kernel_uint_t io_read_calls_raw;
  366. kernel_uint_t io_write_calls_raw;
  367. kernel_uint_t io_storage_bytes_read_raw;
  368. kernel_uint_t io_storage_bytes_written_raw;
  369. kernel_uint_t io_cancelled_write_bytes_raw;
  370. kernel_uint_t io_logical_bytes_read;
  371. kernel_uint_t io_logical_bytes_written;
  372. kernel_uint_t io_read_calls;
  373. kernel_uint_t io_write_calls;
  374. kernel_uint_t io_storage_bytes_read;
  375. kernel_uint_t io_storage_bytes_written;
  376. kernel_uint_t io_cancelled_write_bytes;
  377. kernel_uint_t uptime;
  378. struct pid_fd *fds; // array of fds it uses
  379. size_t fds_size; // the size of the fds array
  380. struct openfds openfds;
  381. struct pid_limits limits;
  382. NETDATA_DOUBLE openfds_limits_percent;
  383. int sortlist; // higher numbers = top on the process tree
  384. // each process gets a unique number
  385. int children_count; // number of processes directly referencing this
  386. int keeploops; // increases by 1 every time keep is 1 and updated 0
  387. PID_LOG log_thrown;
  388. bool keep; // true when we need to keep this process in memory even after it exited
  389. bool updated; // true when the process is currently running
  390. bool merged; // true when it has been merged to its parent
  391. bool read; // true when we have already read this process for this iteration
  392. bool matched_by_config;
  393. struct target *target; // app_groups.conf targets
  394. struct target *user_target; // uid based targets
  395. struct target *group_target; // gid based targets
  396. usec_t stat_collected_usec;
  397. usec_t last_stat_collected_usec;
  398. usec_t io_collected_usec;
  399. usec_t last_io_collected_usec;
  400. usec_t last_limits_collected_usec;
  401. char *fds_dirname; // the full directory name in /proc/PID/fd
  402. char *stat_filename;
  403. char *status_filename;
  404. char *io_filename;
  405. char *cmdline_filename;
  406. char *limits_filename;
  407. struct pid_stat *parent;
  408. struct pid_stat *prev;
  409. struct pid_stat *next;
  410. };
  411. size_t pagesize;
  412. kernel_uint_t global_uptime;
  413. static struct pid_stat
  414. *root_of_pids = NULL, // global list of all processes running
  415. **all_pids = NULL; // to avoid allocations, we pre-allocate
  416. // a pointer for each pid in the entire pid space.
  417. static size_t
  418. all_pids_count = 0; // the number of processes running
  419. #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
  420. // Another pre-allocated list of all possible pids.
  421. // We need it to pids and assign them a unique sortlist id, so that we
  422. // read parents before children. This is needed to prevent a situation where
  423. // a child is found running, but until we read its parent, it has exited and
  424. // its parent has accumulated its resources.
  425. static pid_t
  426. *all_pids_sortlist = NULL;
  427. #endif
  428. // ----------------------------------------------------------------------------
  429. // file descriptor
  430. //
  431. // this is used to keep a global list of all open files of the system.
  432. // it is needed in order to calculate the unique files processes have open.
  433. #define FILE_DESCRIPTORS_INCREASE_STEP 100
  434. // types for struct file_descriptor->type
  435. typedef enum fd_filetype {
  436. FILETYPE_OTHER,
  437. FILETYPE_FILE,
  438. FILETYPE_PIPE,
  439. FILETYPE_SOCKET,
  440. FILETYPE_INOTIFY,
  441. FILETYPE_EVENTFD,
  442. FILETYPE_EVENTPOLL,
  443. FILETYPE_TIMERFD,
  444. FILETYPE_SIGNALFD
  445. } FD_FILETYPE;
  446. struct file_descriptor {
  447. avl_t avl;
  448. #ifdef NETDATA_INTERNAL_CHECKS
  449. uint32_t magic;
  450. #endif /* NETDATA_INTERNAL_CHECKS */
  451. const char *name;
  452. uint32_t hash;
  453. FD_FILETYPE type;
  454. int count;
  455. int pos;
  456. } *all_files = NULL;
  457. static int
  458. all_files_len = 0,
  459. all_files_size = 0;
  460. // ----------------------------------------------------------------------------
  461. // read users and groups from files
  462. struct user_or_group_id {
  463. avl_t avl;
  464. union {
  465. uid_t uid;
  466. gid_t gid;
  467. } id;
  468. char *name;
  469. int updated;
  470. struct user_or_group_id * next;
  471. };
  472. enum user_or_group_id_type {
  473. USER_ID,
  474. GROUP_ID
  475. };
  476. struct user_or_group_ids{
  477. enum user_or_group_id_type type;
  478. avl_tree_type index;
  479. struct user_or_group_id *root;
  480. char filename[FILENAME_MAX + 1];
  481. };
  482. int user_id_compare(void* a, void* b) {
  483. if(((struct user_or_group_id *)a)->id.uid < ((struct user_or_group_id *)b)->id.uid)
  484. return -1;
  485. else if(((struct user_or_group_id *)a)->id.uid > ((struct user_or_group_id *)b)->id.uid)
  486. return 1;
  487. else
  488. return 0;
  489. }
  490. struct user_or_group_ids all_user_ids = {
  491. .type = USER_ID,
  492. .index = {
  493. NULL,
  494. user_id_compare
  495. },
  496. .root = NULL,
  497. .filename = "",
  498. };
  499. int group_id_compare(void* a, void* b) {
  500. if(((struct user_or_group_id *)a)->id.gid < ((struct user_or_group_id *)b)->id.gid)
  501. return -1;
  502. else if(((struct user_or_group_id *)a)->id.gid > ((struct user_or_group_id *)b)->id.gid)
  503. return 1;
  504. else
  505. return 0;
  506. }
  507. struct user_or_group_ids all_group_ids = {
  508. .type = GROUP_ID,
  509. .index = {
  510. NULL,
  511. group_id_compare
  512. },
  513. .root = NULL,
  514. .filename = "",
  515. };
  516. int file_changed(const struct stat *statbuf, struct timespec *last_modification_time) {
  517. if(likely(statbuf->st_mtim.tv_sec == last_modification_time->tv_sec &&
  518. statbuf->st_mtim.tv_nsec == last_modification_time->tv_nsec)) return 0;
  519. last_modification_time->tv_sec = statbuf->st_mtim.tv_sec;
  520. last_modification_time->tv_nsec = statbuf->st_mtim.tv_nsec;
  521. return 1;
  522. }
  523. int read_user_or_group_ids(struct user_or_group_ids *ids, struct timespec *last_modification_time) {
  524. struct stat statbuf;
  525. if(unlikely(stat(ids->filename, &statbuf)))
  526. return 1;
  527. else
  528. if(likely(!file_changed(&statbuf, last_modification_time))) return 0;
  529. procfile *ff = procfile_open(ids->filename, " :\t", PROCFILE_FLAG_DEFAULT);
  530. if(unlikely(!ff)) return 1;
  531. ff = procfile_readall(ff);
  532. if(unlikely(!ff)) return 1;
  533. size_t line, lines = procfile_lines(ff);
  534. for(line = 0; line < lines ;line++) {
  535. size_t words = procfile_linewords(ff, line);
  536. if(unlikely(words < 3)) continue;
  537. char *name = procfile_lineword(ff, line, 0);
  538. if(unlikely(!name || !*name)) continue;
  539. char *id_string = procfile_lineword(ff, line, 2);
  540. if(unlikely(!id_string || !*id_string)) continue;
  541. struct user_or_group_id *user_or_group_id = callocz(1, sizeof(struct user_or_group_id));
  542. if(ids->type == USER_ID)
  543. user_or_group_id->id.uid = (uid_t) str2ull(id_string, NULL);
  544. else
  545. user_or_group_id->id.gid = (uid_t) str2ull(id_string, NULL);
  546. user_or_group_id->name = strdupz(name);
  547. user_or_group_id->updated = 1;
  548. struct user_or_group_id *existing_user_id = NULL;
  549. if(likely(ids->root))
  550. existing_user_id = (struct user_or_group_id *)avl_search(&ids->index, (avl_t *) user_or_group_id);
  551. if(unlikely(existing_user_id)) {
  552. freez(existing_user_id->name);
  553. existing_user_id->name = user_or_group_id->name;
  554. existing_user_id->updated = 1;
  555. freez(user_or_group_id);
  556. }
  557. else {
  558. if(unlikely(avl_insert(&ids->index, (avl_t *) user_or_group_id) != (void *) user_or_group_id)) {
  559. netdata_log_error("INTERNAL ERROR: duplicate indexing of id during realloc");
  560. };
  561. user_or_group_id->next = ids->root;
  562. ids->root = user_or_group_id;
  563. }
  564. }
  565. procfile_close(ff);
  566. // remove unused ids
  567. struct user_or_group_id *user_or_group_id = ids->root, *prev_user_id = NULL;
  568. while(user_or_group_id) {
  569. if(unlikely(!user_or_group_id->updated)) {
  570. if(unlikely((struct user_or_group_id *)avl_remove(&ids->index, (avl_t *) user_or_group_id) != user_or_group_id))
  571. netdata_log_error("INTERNAL ERROR: removal of unused id from index, removed a different id");
  572. if(prev_user_id)
  573. prev_user_id->next = user_or_group_id->next;
  574. else
  575. ids->root = user_or_group_id->next;
  576. freez(user_or_group_id->name);
  577. freez(user_or_group_id);
  578. if(prev_user_id)
  579. user_or_group_id = prev_user_id->next;
  580. else
  581. user_or_group_id = ids->root;
  582. }
  583. else {
  584. user_or_group_id->updated = 0;
  585. prev_user_id = user_or_group_id;
  586. user_or_group_id = user_or_group_id->next;
  587. }
  588. }
  589. return 0;
  590. }
  591. // ----------------------------------------------------------------------------
  592. // apps_groups.conf
  593. // aggregate all processes in groups, to have a limited number of dimensions
  594. static struct target *get_users_target(uid_t uid) {
  595. struct target *w;
  596. for(w = users_root_target ; w ; w = w->next)
  597. if(w->uid == uid) return w;
  598. w = callocz(sizeof(struct target), 1);
  599. snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
  600. w->comparehash = simple_hash(w->compare);
  601. w->comparelen = strlen(w->compare);
  602. snprintfz(w->id, MAX_NAME, "%u", uid);
  603. w->idhash = simple_hash(w->id);
  604. struct user_or_group_id user_id_to_find, *user_or_group_id = NULL;
  605. user_id_to_find.id.uid = uid;
  606. if(*netdata_configured_host_prefix) {
  607. static struct timespec last_passwd_modification_time;
  608. int ret = read_user_or_group_ids(&all_user_ids, &last_passwd_modification_time);
  609. if(likely(!ret && all_user_ids.index.root))
  610. user_or_group_id = (struct user_or_group_id *)avl_search(&all_user_ids.index, (avl_t *) &user_id_to_find);
  611. }
  612. if(user_or_group_id && user_or_group_id->name && *user_or_group_id->name) {
  613. snprintfz(w->name, MAX_NAME, "%s", user_or_group_id->name);
  614. }
  615. else {
  616. struct passwd *pw = getpwuid(uid);
  617. if(!pw || !pw->pw_name || !*pw->pw_name)
  618. snprintfz(w->name, MAX_NAME, "%u", uid);
  619. else
  620. snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
  621. }
  622. netdata_fix_chart_name(w->name);
  623. w->uid = uid;
  624. w->next = users_root_target;
  625. users_root_target = w;
  626. debug_log("added uid %u ('%s') target", w->uid, w->name);
  627. return w;
  628. }
  629. struct target *get_groups_target(gid_t gid)
  630. {
  631. struct target *w;
  632. for(w = groups_root_target ; w ; w = w->next)
  633. if(w->gid == gid) return w;
  634. w = callocz(sizeof(struct target), 1);
  635. snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
  636. w->comparehash = simple_hash(w->compare);
  637. w->comparelen = strlen(w->compare);
  638. snprintfz(w->id, MAX_NAME, "%u", gid);
  639. w->idhash = simple_hash(w->id);
  640. struct user_or_group_id group_id_to_find, *group_id = NULL;
  641. group_id_to_find.id.gid = gid;
  642. if(*netdata_configured_host_prefix) {
  643. static struct timespec last_group_modification_time;
  644. int ret = read_user_or_group_ids(&all_group_ids, &last_group_modification_time);
  645. if(likely(!ret && all_group_ids.index.root))
  646. group_id = (struct user_or_group_id *)avl_search(&all_group_ids.index, (avl_t *) &group_id_to_find);
  647. }
  648. if(group_id && group_id->name && *group_id->name) {
  649. snprintfz(w->name, MAX_NAME, "%s", group_id->name);
  650. }
  651. else {
  652. struct group *gr = getgrgid(gid);
  653. if(!gr || !gr->gr_name || !*gr->gr_name)
  654. snprintfz(w->name, MAX_NAME, "%u", gid);
  655. else
  656. snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
  657. }
  658. netdata_fix_chart_name(w->name);
  659. w->gid = gid;
  660. w->next = groups_root_target;
  661. groups_root_target = w;
  662. debug_log("added gid %u ('%s') target", w->gid, w->name);
  663. return w;
  664. }
  665. // find or create a new target
  666. // there are targets that are just aggregated to other target (the second argument)
  667. static struct target *get_apps_groups_target(const char *id, struct target *target, const char *name) {
  668. int tdebug = 0, thidden = target?target->hidden:0, ends_with = 0;
  669. const char *nid = id;
  670. // extract the options
  671. while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
  672. if(nid[0] == '-') thidden = 1;
  673. if(nid[0] == '+') tdebug = 1;
  674. if(nid[0] == '*') ends_with = 1;
  675. nid++;
  676. }
  677. uint32_t hash = simple_hash(id);
  678. // find if it already exists
  679. struct target *w, *last = apps_groups_root_target;
  680. for(w = apps_groups_root_target ; w ; w = w->next) {
  681. if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
  682. return w;
  683. last = w;
  684. }
  685. // find an existing target
  686. if(unlikely(!target)) {
  687. while(*name == '-') {
  688. if(*name == '-') thidden = 1;
  689. name++;
  690. }
  691. for(target = apps_groups_root_target ; target != NULL ; target = target->next) {
  692. if(!target->target && strcmp(name, target->name) == 0)
  693. break;
  694. }
  695. if(unlikely(debug_enabled)) {
  696. if(unlikely(target))
  697. debug_log("REUSING TARGET NAME '%s' on ID '%s'", target->name, target->id);
  698. else
  699. debug_log("NEW TARGET NAME '%s' on ID '%s'", name, id);
  700. }
  701. }
  702. if(target && target->target)
  703. fatal("Internal Error: request to link process '%s' to target '%s' which is linked to target '%s'", id, target->id, target->target->id);
  704. w = callocz(sizeof(struct target), 1);
  705. strncpyz(w->id, nid, MAX_NAME);
  706. w->idhash = simple_hash(w->id);
  707. if(unlikely(!target))
  708. // copy the name
  709. strncpyz(w->name, name, MAX_NAME);
  710. else
  711. // copy the id
  712. strncpyz(w->name, nid, MAX_NAME);
  713. strncpyz(w->compare, nid, MAX_COMPARE_NAME);
  714. size_t len = strlen(w->compare);
  715. if(w->compare[len - 1] == '*') {
  716. w->compare[len - 1] = '\0';
  717. w->starts_with = 1;
  718. }
  719. w->ends_with = ends_with;
  720. if(w->starts_with && w->ends_with)
  721. proc_pid_cmdline_is_needed = 1;
  722. w->comparehash = simple_hash(w->compare);
  723. w->comparelen = strlen(w->compare);
  724. w->hidden = thidden;
  725. #ifdef NETDATA_INTERNAL_CHECKS
  726. w->debug_enabled = tdebug;
  727. #else
  728. if(tdebug)
  729. fprintf(stderr, "apps.plugin has been compiled without debugging\n");
  730. #endif
  731. w->target = target;
  732. // append it, to maintain the order in apps_groups.conf
  733. if(last) last->next = w;
  734. else apps_groups_root_target = w;
  735. debug_log("ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s"
  736. , w->id
  737. , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
  738. , w->target?w->target->name:w->name
  739. , (w->hidden)?"hidden":"-"
  740. , (w->debug_enabled)?"debug":"-"
  741. );
  742. return w;
  743. }
  744. // read the apps_groups.conf file
  745. static int read_apps_groups_conf(const char *path, const char *file)
  746. {
  747. char filename[FILENAME_MAX + 1];
  748. snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", path, file);
  749. debug_log("process groups file: '%s'", filename);
  750. // ----------------------------------------
  751. procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
  752. if(!ff) return 1;
  753. procfile_set_quotes(ff, "'\"");
  754. ff = procfile_readall(ff);
  755. if(!ff)
  756. return 1;
  757. size_t line, lines = procfile_lines(ff);
  758. for(line = 0; line < lines ;line++) {
  759. size_t word, words = procfile_linewords(ff, line);
  760. if(!words) continue;
  761. char *name = procfile_lineword(ff, line, 0);
  762. if(!name || !*name) continue;
  763. // find a possibly existing target
  764. struct target *w = NULL;
  765. // loop through all words, skipping the first one (the name)
  766. for(word = 0; word < words ;word++) {
  767. char *s = procfile_lineword(ff, line, word);
  768. if(!s || !*s) continue;
  769. if(*s == '#') break;
  770. // is this the first word? skip it
  771. if(s == name) continue;
  772. // add this target
  773. struct target *n = get_apps_groups_target(s, w, name);
  774. if(!n) {
  775. netdata_log_error("Cannot create target '%s' (line %zu, word %zu)", s, line, word);
  776. continue;
  777. }
  778. // just some optimization
  779. // to avoid searching for a target for each process
  780. if(!w) w = n->target?n->target:n;
  781. }
  782. }
  783. procfile_close(ff);
  784. apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL, "other"); // match nothing
  785. if(!apps_groups_default_target)
  786. fatal("Cannot create default target");
  787. // allow the user to override group 'other'
  788. if(apps_groups_default_target->target)
  789. apps_groups_default_target = apps_groups_default_target->target;
  790. return 0;
  791. }
  792. // ----------------------------------------------------------------------------
  793. // struct pid_stat management
  794. static inline void init_pid_fds(struct pid_stat *p, size_t first, size_t size);
  795. static inline struct pid_stat *get_pid_entry(pid_t pid) {
  796. if(unlikely(all_pids[pid]))
  797. return all_pids[pid];
  798. struct pid_stat *p = callocz(sizeof(struct pid_stat), 1);
  799. p->fds = mallocz(sizeof(struct pid_fd) * MAX_SPARE_FDS);
  800. p->fds_size = MAX_SPARE_FDS;
  801. init_pid_fds(p, 0, p->fds_size);
  802. p->pid = pid;
  803. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(root_of_pids, p, prev, next);
  804. all_pids[pid] = p;
  805. all_pids_count++;
  806. return p;
  807. }
  808. static inline void del_pid_entry(pid_t pid) {
  809. struct pid_stat *p = all_pids[pid];
  810. if(unlikely(!p)) {
  811. netdata_log_error("attempted to free pid %d that is not allocated.", pid);
  812. return;
  813. }
  814. debug_log("process %d %s exited, deleting it.", pid, p->comm);
  815. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(root_of_pids, p, prev, next);
  816. // free the filename
  817. #ifndef __FreeBSD__
  818. {
  819. size_t i;
  820. for(i = 0; i < p->fds_size; i++)
  821. if(p->fds[i].filename)
  822. freez(p->fds[i].filename);
  823. }
  824. #endif
  825. freez(p->fds);
  826. freez(p->fds_dirname);
  827. freez(p->stat_filename);
  828. freez(p->status_filename);
  829. freez(p->limits_filename);
  830. #ifndef __FreeBSD__
  831. arl_free(p->status_arl);
  832. #endif
  833. freez(p->io_filename);
  834. freez(p->cmdline_filename);
  835. freez(p->cmdline);
  836. freez(p);
  837. all_pids[pid] = NULL;
  838. all_pids_count--;
  839. }
  840. // ----------------------------------------------------------------------------
  841. static inline int managed_log(struct pid_stat *p, PID_LOG log, int status) {
  842. if(unlikely(!status)) {
  843. // netdata_log_error("command failed log %u, errno %d", log, errno);
  844. if(unlikely(debug_enabled || errno != ENOENT)) {
  845. if(unlikely(debug_enabled || !(p->log_thrown & log))) {
  846. p->log_thrown |= log;
  847. switch(log) {
  848. case PID_LOG_IO:
  849. #ifdef __FreeBSD__
  850. netdata_log_error("Cannot fetch process %d I/O info (command '%s')", p->pid, p->comm);
  851. #else
  852. netdata_log_error("Cannot process %s/proc/%d/io (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
  853. #endif
  854. break;
  855. case PID_LOG_STATUS:
  856. #ifdef __FreeBSD__
  857. netdata_log_error("Cannot fetch process %d status info (command '%s')", p->pid, p->comm);
  858. #else
  859. netdata_log_error("Cannot process %s/proc/%d/status (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
  860. #endif
  861. break;
  862. case PID_LOG_CMDLINE:
  863. #ifdef __FreeBSD__
  864. netdata_log_error("Cannot fetch process %d command line (command '%s')", p->pid, p->comm);
  865. #else
  866. netdata_log_error("Cannot process %s/proc/%d/cmdline (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
  867. #endif
  868. break;
  869. case PID_LOG_FDS:
  870. #ifdef __FreeBSD__
  871. netdata_log_error("Cannot fetch process %d files (command '%s')", p->pid, p->comm);
  872. #else
  873. netdata_log_error("Cannot process entries in %s/proc/%d/fd (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
  874. #endif
  875. break;
  876. case PID_LOG_LIMITS:
  877. #ifdef __FreeBSD__
  878. ;
  879. #else
  880. netdata_log_error("Cannot process %s/proc/%d/limits (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
  881. #endif
  882. case PID_LOG_STAT:
  883. break;
  884. default:
  885. netdata_log_error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
  886. break;
  887. }
  888. }
  889. }
  890. errno = 0;
  891. }
  892. else if(unlikely(p->log_thrown & log)) {
  893. // netdata_log_error("unsetting log %u on pid %d", log, p->pid);
  894. p->log_thrown &= ~log;
  895. }
  896. return status;
  897. }
  898. static inline void assign_target_to_pid(struct pid_stat *p) {
  899. targets_assignment_counter++;
  900. uint32_t hash = simple_hash(p->comm);
  901. size_t pclen = strlen(p->comm);
  902. struct target *w;
  903. for(w = apps_groups_root_target; w ; w = w->next) {
  904. // if(debug_enabled || (p->target && p->target->debug_enabled)) debug_log_int("\t\tcomparing '%s' with '%s'", w->compare, p->comm);
  905. // find it - 4 cases:
  906. // 1. the target is not a pattern
  907. // 2. the target has the prefix
  908. // 3. the target has the suffix
  909. // 4. the target is something inside cmdline
  910. if(unlikely(( (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
  911. || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
  912. || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
  913. || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && p->cmdline && strstr(p->cmdline, w->compare))
  914. ))) {
  915. p->matched_by_config = true;
  916. if(w->target) p->target = w->target;
  917. else p->target = w;
  918. if(debug_enabled || (p->target && p->target->debug_enabled))
  919. debug_log_int("%s linked to target %s", p->comm, p->target->name);
  920. break;
  921. }
  922. }
  923. }
  924. // ----------------------------------------------------------------------------
  925. // update pids from proc
  926. static inline int read_proc_pid_cmdline(struct pid_stat *p) {
  927. static char cmdline[MAX_CMDLINE + 1];
  928. #ifdef __FreeBSD__
  929. size_t i, bytes = MAX_CMDLINE;
  930. int mib[4];
  931. mib[0] = CTL_KERN;
  932. mib[1] = KERN_PROC;
  933. mib[2] = KERN_PROC_ARGS;
  934. mib[3] = p->pid;
  935. if (unlikely(sysctl(mib, 4, cmdline, &bytes, NULL, 0)))
  936. goto cleanup;
  937. #else
  938. if(unlikely(!p->cmdline_filename)) {
  939. char filename[FILENAME_MAX + 1];
  940. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", netdata_configured_host_prefix, p->pid);
  941. p->cmdline_filename = strdupz(filename);
  942. }
  943. int fd = open(p->cmdline_filename, procfile_open_flags, 0666);
  944. if(unlikely(fd == -1)) goto cleanup;
  945. ssize_t i, bytes = read(fd, cmdline, MAX_CMDLINE);
  946. close(fd);
  947. if(unlikely(bytes < 0)) goto cleanup;
  948. #endif
  949. cmdline[bytes] = '\0';
  950. for(i = 0; i < bytes ; i++) {
  951. if(unlikely(!cmdline[i])) cmdline[i] = ' ';
  952. }
  953. if(p->cmdline) freez(p->cmdline);
  954. p->cmdline = strdupz(cmdline);
  955. debug_log("Read file '%s' contents: %s", p->cmdline_filename, p->cmdline);
  956. return 1;
  957. cleanup:
  958. // copy the command to the command line
  959. if(p->cmdline) freez(p->cmdline);
  960. p->cmdline = strdupz(p->comm);
  961. return 0;
  962. }
  963. // ----------------------------------------------------------------------------
  964. // macro to calculate the incremental rate of a value
  965. // each parameter is accessed only ONCE - so it is safe to pass function calls
  966. // or other macros as parameters
  967. #define incremental_rate(rate_variable, last_kernel_variable, new_kernel_value, collected_usec, last_collected_usec) { \
  968. kernel_uint_t _new_tmp = new_kernel_value; \
  969. (rate_variable) = (_new_tmp - (last_kernel_variable)) * (USEC_PER_SEC * RATES_DETAIL) / ((collected_usec) - (last_collected_usec)); \
  970. (last_kernel_variable) = _new_tmp; \
  971. }
  972. // the same macro for struct pid members
  973. #define pid_incremental_rate(type, var, value) \
  974. incremental_rate(var, var##_raw, value, p->type##_collected_usec, p->last_##type##_collected_usec)
  975. // ----------------------------------------------------------------------------
  976. #ifndef __FreeBSD__
  977. struct arl_callback_ptr {
  978. struct pid_stat *p;
  979. procfile *ff;
  980. size_t line;
  981. };
  982. void arl_callback_status_uid(const char *name, uint32_t hash, const char *value, void *dst) {
  983. (void)name; (void)hash; (void)value;
  984. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  985. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 5)) return;
  986. //const char *real_uid = procfile_lineword(aptr->ff, aptr->line, 1);
  987. const char *effective_uid = procfile_lineword(aptr->ff, aptr->line, 2);
  988. //const char *saved_uid = procfile_lineword(aptr->ff, aptr->line, 3);
  989. //const char *filesystem_uid = procfile_lineword(aptr->ff, aptr->line, 4);
  990. if(likely(effective_uid && *effective_uid))
  991. aptr->p->uid = (uid_t)str2l(effective_uid);
  992. }
  993. void arl_callback_status_gid(const char *name, uint32_t hash, const char *value, void *dst) {
  994. (void)name; (void)hash; (void)value;
  995. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  996. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 5)) return;
  997. //const char *real_gid = procfile_lineword(aptr->ff, aptr->line, 1);
  998. const char *effective_gid = procfile_lineword(aptr->ff, aptr->line, 2);
  999. //const char *saved_gid = procfile_lineword(aptr->ff, aptr->line, 3);
  1000. //const char *filesystem_gid = procfile_lineword(aptr->ff, aptr->line, 4);
  1001. if(likely(effective_gid && *effective_gid))
  1002. aptr->p->gid = (uid_t)str2l(effective_gid);
  1003. }
  1004. void arl_callback_status_vmsize(const char *name, uint32_t hash, const char *value, void *dst) {
  1005. (void)name; (void)hash; (void)value;
  1006. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1007. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 3)) return;
  1008. aptr->p->status_vmsize = str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1));
  1009. }
  1010. void arl_callback_status_vmswap(const char *name, uint32_t hash, const char *value, void *dst) {
  1011. (void)name; (void)hash; (void)value;
  1012. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1013. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 3)) return;
  1014. aptr->p->status_vmswap = str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1));
  1015. }
  1016. void arl_callback_status_vmrss(const char *name, uint32_t hash, const char *value, void *dst) {
  1017. (void)name; (void)hash; (void)value;
  1018. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1019. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 3)) return;
  1020. aptr->p->status_vmrss = str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1));
  1021. }
  1022. void arl_callback_status_rssfile(const char *name, uint32_t hash, const char *value, void *dst) {
  1023. (void)name; (void)hash; (void)value;
  1024. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1025. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 3)) return;
  1026. aptr->p->status_rssfile = str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1));
  1027. }
  1028. void arl_callback_status_rssshmem(const char *name, uint32_t hash, const char *value, void *dst) {
  1029. (void)name; (void)hash; (void)value;
  1030. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1031. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 3)) return;
  1032. aptr->p->status_rssshmem = str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1));
  1033. }
  1034. void arl_callback_status_voluntary_ctxt_switches(const char *name, uint32_t hash, const char *value, void *dst) {
  1035. (void)name; (void)hash; (void)value;
  1036. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1037. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 2)) return;
  1038. struct pid_stat *p = aptr->p;
  1039. pid_incremental_rate(stat, p->status_voluntary_ctxt_switches, str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1)));
  1040. }
  1041. void arl_callback_status_nonvoluntary_ctxt_switches(const char *name, uint32_t hash, const char *value, void *dst) {
  1042. (void)name; (void)hash; (void)value;
  1043. struct arl_callback_ptr *aptr = (struct arl_callback_ptr *)dst;
  1044. if(unlikely(procfile_linewords(aptr->ff, aptr->line) < 2)) return;
  1045. struct pid_stat *p = aptr->p;
  1046. pid_incremental_rate(stat, p->status_nonvoluntary_ctxt_switches, str2kernel_uint_t(procfile_lineword(aptr->ff, aptr->line, 1)));
  1047. }
  1048. static void update_proc_state_count(char proc_state) {
  1049. switch (proc_state) {
  1050. case 'S':
  1051. proc_state_count[PROC_STATUS_SLEEPING] += 1;
  1052. break;
  1053. case 'R':
  1054. proc_state_count[PROC_STATUS_RUNNING] += 1;
  1055. break;
  1056. case 'D':
  1057. proc_state_count[PROC_STATUS_SLEEPING_D] += 1;
  1058. break;
  1059. case 'Z':
  1060. proc_state_count[PROC_STATUS_ZOMBIE] += 1;
  1061. break;
  1062. case 'T':
  1063. proc_state_count[PROC_STATUS_STOPPED] += 1;
  1064. break;
  1065. default:
  1066. break;
  1067. }
  1068. }
  1069. #endif // !__FreeBSD__
  1070. #define MAX_PROC_PID_LIMITS 8192
  1071. #define PROC_PID_LIMITS_MAX_OPEN_FILES_KEY "\nMax open files "
  1072. static inline kernel_uint_t get_proc_pid_limits_limit(char *buf, const char *key, size_t key_len, kernel_uint_t def) {
  1073. char *line = strstr(buf, key);
  1074. if(!line)
  1075. return def;
  1076. char *v = &line[key_len];
  1077. while(isspace(*v)) v++;
  1078. if(strcmp(v, "unlimited") == 0)
  1079. return 0;
  1080. return str2ull(v, NULL);
  1081. }
  1082. static inline int read_proc_pid_limits(struct pid_stat *p, void *ptr) {
  1083. (void)ptr;
  1084. #ifdef __FreeBSD__
  1085. return 0;
  1086. #else
  1087. static char proc_pid_limits_buffer[MAX_PROC_PID_LIMITS + 1];
  1088. int ret = 0;
  1089. bool read_limits = false;
  1090. errno = 0;
  1091. proc_pid_limits_buffer[0] = '\0';
  1092. kernel_uint_t all_fds = pid_openfds_sum(p);
  1093. if(all_fds < p->limits.max_open_files / 2 && p->io_collected_usec > p->last_limits_collected_usec && p->io_collected_usec - p->last_limits_collected_usec <= 60 * USEC_PER_SEC) {
  1094. // too frequent, we want to collect limits once per minute
  1095. ret = 1;
  1096. goto cleanup;
  1097. }
  1098. if(unlikely(!p->limits_filename)) {
  1099. char filename[FILENAME_MAX + 1];
  1100. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/limits", netdata_configured_host_prefix, p->pid);
  1101. p->limits_filename = strdupz(filename);
  1102. }
  1103. int fd = open(p->limits_filename, procfile_open_flags, 0666);
  1104. if(unlikely(fd == -1)) goto cleanup;
  1105. ssize_t bytes = read(fd, proc_pid_limits_buffer, MAX_PROC_PID_LIMITS);
  1106. close(fd);
  1107. if(bytes <= 0)
  1108. goto cleanup;
  1109. // make it '\0' terminated
  1110. if(bytes < MAX_PROC_PID_LIMITS)
  1111. proc_pid_limits_buffer[bytes] = '\0';
  1112. else
  1113. proc_pid_limits_buffer[MAX_PROC_PID_LIMITS - 1] = '\0';
  1114. p->limits.max_open_files = get_proc_pid_limits_limit(proc_pid_limits_buffer, PROC_PID_LIMITS_MAX_OPEN_FILES_KEY, sizeof(PROC_PID_LIMITS_MAX_OPEN_FILES_KEY) - 1, 0);
  1115. if(p->limits.max_open_files == 1) {
  1116. // it seems a bug in the kernel or something similar
  1117. // it sets max open files to 1 but the number of files
  1118. // the process has open are more than 1...
  1119. // https://github.com/netdata/netdata/issues/15443
  1120. p->limits.max_open_files = 0;
  1121. ret = 1;
  1122. goto cleanup;
  1123. }
  1124. p->last_limits_collected_usec = p->io_collected_usec;
  1125. read_limits = true;
  1126. ret = 1;
  1127. cleanup:
  1128. if(p->limits.max_open_files)
  1129. p->openfds_limits_percent = (NETDATA_DOUBLE)all_fds * 100.0 / (NETDATA_DOUBLE)p->limits.max_open_files;
  1130. else
  1131. p->openfds_limits_percent = 0.0;
  1132. if(p->openfds_limits_percent > 100.0) {
  1133. if(!(p->log_thrown & PID_LOG_LIMITS_DETAIL)) {
  1134. char *line;
  1135. if(!read_limits) {
  1136. proc_pid_limits_buffer[0] = '\0';
  1137. line = "NOT READ";
  1138. }
  1139. else {
  1140. line = strstr(proc_pid_limits_buffer, PROC_PID_LIMITS_MAX_OPEN_FILES_KEY);
  1141. if (line) {
  1142. line++; // skip the initial newline
  1143. char *end = strchr(line, '\n');
  1144. if (end)
  1145. *end = '\0';
  1146. }
  1147. }
  1148. netdata_log_info(
  1149. "FDS_LIMITS: PID %d (%s) is using "
  1150. "%0.2f %% of its fds limits, "
  1151. "open fds = %llu ("
  1152. "files = %llu, "
  1153. "pipes = %llu, "
  1154. "sockets = %llu, "
  1155. "inotifies = %llu, "
  1156. "eventfds = %llu, "
  1157. "timerfds = %llu, "
  1158. "signalfds = %llu, "
  1159. "eventpolls = %llu "
  1160. "other = %llu "
  1161. "), open fds limit = %llu, "
  1162. "%s, "
  1163. "original line [%s]",
  1164. p->pid, p->comm, p->openfds_limits_percent, all_fds,
  1165. p->openfds.files,
  1166. p->openfds.pipes,
  1167. p->openfds.sockets,
  1168. p->openfds.inotifies,
  1169. p->openfds.eventfds,
  1170. p->openfds.timerfds,
  1171. p->openfds.signalfds,
  1172. p->openfds.eventpolls,
  1173. p->openfds.other,
  1174. p->limits.max_open_files,
  1175. read_limits ? "and we have read the limits AFTER counting the fds"
  1176. : "but we have read the limits BEFORE counting the fds",
  1177. line);
  1178. p->log_thrown |= PID_LOG_LIMITS_DETAIL;
  1179. }
  1180. }
  1181. else
  1182. p->log_thrown &= ~PID_LOG_LIMITS_DETAIL;
  1183. return ret;
  1184. #endif
  1185. }
  1186. static inline int read_proc_pid_status(struct pid_stat *p, void *ptr) {
  1187. p->status_vmsize = 0;
  1188. p->status_vmrss = 0;
  1189. p->status_vmshared = 0;
  1190. p->status_rssfile = 0;
  1191. p->status_rssshmem = 0;
  1192. p->status_vmswap = 0;
  1193. p->status_voluntary_ctxt_switches = 0;
  1194. p->status_nonvoluntary_ctxt_switches = 0;
  1195. #ifdef __FreeBSD__
  1196. struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
  1197. p->uid = proc_info->ki_uid;
  1198. p->gid = proc_info->ki_groups[0];
  1199. p->status_vmsize = proc_info->ki_size / 1024; // in KiB
  1200. p->status_vmrss = proc_info->ki_rssize * pagesize / 1024; // in KiB
  1201. // TODO: what about shared and swap memory on FreeBSD?
  1202. return 1;
  1203. #else
  1204. (void)ptr;
  1205. static struct arl_callback_ptr arl_ptr;
  1206. static procfile *ff = NULL;
  1207. if(unlikely(!p->status_arl)) {
  1208. p->status_arl = arl_create("/proc/pid/status", NULL, 60);
  1209. arl_expect_custom(p->status_arl, "Uid", arl_callback_status_uid, &arl_ptr);
  1210. arl_expect_custom(p->status_arl, "Gid", arl_callback_status_gid, &arl_ptr);
  1211. arl_expect_custom(p->status_arl, "VmSize", arl_callback_status_vmsize, &arl_ptr);
  1212. arl_expect_custom(p->status_arl, "VmRSS", arl_callback_status_vmrss, &arl_ptr);
  1213. arl_expect_custom(p->status_arl, "RssFile", arl_callback_status_rssfile, &arl_ptr);
  1214. arl_expect_custom(p->status_arl, "RssShmem", arl_callback_status_rssshmem, &arl_ptr);
  1215. arl_expect_custom(p->status_arl, "VmSwap", arl_callback_status_vmswap, &arl_ptr);
  1216. arl_expect_custom(p->status_arl, "voluntary_ctxt_switches", arl_callback_status_voluntary_ctxt_switches, &arl_ptr);
  1217. arl_expect_custom(p->status_arl, "nonvoluntary_ctxt_switches", arl_callback_status_nonvoluntary_ctxt_switches, &arl_ptr);
  1218. }
  1219. if(unlikely(!p->status_filename)) {
  1220. char filename[FILENAME_MAX + 1];
  1221. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/status", netdata_configured_host_prefix, p->pid);
  1222. p->status_filename = strdupz(filename);
  1223. }
  1224. ff = procfile_reopen(ff, p->status_filename, (!ff)?" \t:,-()/":NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
  1225. if(unlikely(!ff)) return 0;
  1226. ff = procfile_readall(ff);
  1227. if(unlikely(!ff)) return 0;
  1228. calls_counter++;
  1229. // let ARL use this pid
  1230. arl_ptr.p = p;
  1231. arl_ptr.ff = ff;
  1232. size_t lines = procfile_lines(ff), l;
  1233. arl_begin(p->status_arl);
  1234. for(l = 0; l < lines ;l++) {
  1235. // debug_log("CHECK: line %zu of %zu, key '%s' = '%s'", l, lines, procfile_lineword(ff, l, 0), procfile_lineword(ff, l, 1));
  1236. arl_ptr.line = l;
  1237. if(unlikely(arl_check(p->status_arl,
  1238. procfile_lineword(ff, l, 0),
  1239. procfile_lineword(ff, l, 1)))) break;
  1240. }
  1241. p->status_vmshared = p->status_rssfile + p->status_rssshmem;
  1242. // debug_log("%s uid %d, gid %d, VmSize %zu, VmRSS %zu, RssFile %zu, RssShmem %zu, shared %zu", p->comm, (int)p->uid, (int)p->gid, p->status_vmsize, p->status_vmrss, p->status_rssfile, p->status_rssshmem, p->status_vmshared);
  1243. return 1;
  1244. #endif
  1245. }
  1246. // ----------------------------------------------------------------------------
  1247. static inline int read_proc_pid_stat(struct pid_stat *p, void *ptr) {
  1248. (void)ptr;
  1249. #ifdef __FreeBSD__
  1250. struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
  1251. if (unlikely(proc_info->ki_tdflags & TDF_IDLETD))
  1252. goto cleanup;
  1253. #else
  1254. static procfile *ff = NULL;
  1255. if(unlikely(!p->stat_filename)) {
  1256. char filename[FILENAME_MAX + 1];
  1257. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", netdata_configured_host_prefix, p->pid);
  1258. p->stat_filename = strdupz(filename);
  1259. }
  1260. int set_quotes = (!ff)?1:0;
  1261. ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
  1262. if(unlikely(!ff)) goto cleanup;
  1263. // if(set_quotes) procfile_set_quotes(ff, "()");
  1264. if(unlikely(set_quotes))
  1265. procfile_set_open_close(ff, "(", ")");
  1266. ff = procfile_readall(ff);
  1267. if(unlikely(!ff)) goto cleanup;
  1268. #endif
  1269. p->last_stat_collected_usec = p->stat_collected_usec;
  1270. p->stat_collected_usec = now_monotonic_usec();
  1271. calls_counter++;
  1272. #ifdef __FreeBSD__
  1273. char *comm = proc_info->ki_comm;
  1274. p->ppid = proc_info->ki_ppid;
  1275. #else
  1276. // p->pid = str2pid_t(procfile_lineword(ff, 0, 0));
  1277. char *comm = procfile_lineword(ff, 0, 1);
  1278. p->state = *(procfile_lineword(ff, 0, 2));
  1279. p->ppid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 3));
  1280. // p->pgrp = (int32_t)str2pid_t(procfile_lineword(ff, 0, 4));
  1281. // p->session = (int32_t)str2pid_t(procfile_lineword(ff, 0, 5));
  1282. // p->tty_nr = (int32_t)str2pid_t(procfile_lineword(ff, 0, 6));
  1283. // p->tpgid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 7));
  1284. // p->flags = str2uint64_t(procfile_lineword(ff, 0, 8));
  1285. #endif
  1286. if(strcmp(p->comm, comm) != 0) {
  1287. if(unlikely(debug_enabled)) {
  1288. if(p->comm[0])
  1289. debug_log("\tpid %d (%s) changed name to '%s'", p->pid, p->comm, comm);
  1290. else
  1291. debug_log("\tJust added %d (%s)", p->pid, comm);
  1292. }
  1293. strncpyz(p->comm, comm, MAX_COMPARE_NAME);
  1294. // /proc/<pid>/cmdline
  1295. if(likely(proc_pid_cmdline_is_needed))
  1296. managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
  1297. assign_target_to_pid(p);
  1298. }
  1299. #ifdef __FreeBSD__
  1300. pid_incremental_rate(stat, p->minflt, (kernel_uint_t)proc_info->ki_rusage.ru_minflt);
  1301. pid_incremental_rate(stat, p->cminflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_minflt);
  1302. pid_incremental_rate(stat, p->majflt, (kernel_uint_t)proc_info->ki_rusage.ru_majflt);
  1303. pid_incremental_rate(stat, p->cmajflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_majflt);
  1304. pid_incremental_rate(stat, p->utime, (kernel_uint_t)proc_info->ki_rusage.ru_utime.tv_sec * 100 + proc_info->ki_rusage.ru_utime.tv_usec / 10000);
  1305. pid_incremental_rate(stat, p->stime, (kernel_uint_t)proc_info->ki_rusage.ru_stime.tv_sec * 100 + proc_info->ki_rusage.ru_stime.tv_usec / 10000);
  1306. pid_incremental_rate(stat, p->cutime, (kernel_uint_t)proc_info->ki_rusage_ch.ru_utime.tv_sec * 100 + proc_info->ki_rusage_ch.ru_utime.tv_usec / 10000);
  1307. pid_incremental_rate(stat, p->cstime, (kernel_uint_t)proc_info->ki_rusage_ch.ru_stime.tv_sec * 100 + proc_info->ki_rusage_ch.ru_stime.tv_usec / 10000);
  1308. p->num_threads = proc_info->ki_numthreads;
  1309. if(enable_guest_charts) {
  1310. enable_guest_charts = 0;
  1311. netdata_log_info("Guest charts aren't supported by FreeBSD");
  1312. }
  1313. #else
  1314. pid_incremental_rate(stat, p->minflt, str2kernel_uint_t(procfile_lineword(ff, 0, 9)));
  1315. pid_incremental_rate(stat, p->cminflt, str2kernel_uint_t(procfile_lineword(ff, 0, 10)));
  1316. pid_incremental_rate(stat, p->majflt, str2kernel_uint_t(procfile_lineword(ff, 0, 11)));
  1317. pid_incremental_rate(stat, p->cmajflt, str2kernel_uint_t(procfile_lineword(ff, 0, 12)));
  1318. pid_incremental_rate(stat, p->utime, str2kernel_uint_t(procfile_lineword(ff, 0, 13)));
  1319. pid_incremental_rate(stat, p->stime, str2kernel_uint_t(procfile_lineword(ff, 0, 14)));
  1320. pid_incremental_rate(stat, p->cutime, str2kernel_uint_t(procfile_lineword(ff, 0, 15)));
  1321. pid_incremental_rate(stat, p->cstime, str2kernel_uint_t(procfile_lineword(ff, 0, 16)));
  1322. // p->priority = str2kernel_uint_t(procfile_lineword(ff, 0, 17));
  1323. // p->nice = str2kernel_uint_t(procfile_lineword(ff, 0, 18));
  1324. p->num_threads = (int32_t) str2uint32_t(procfile_lineword(ff, 0, 19), NULL);
  1325. // p->itrealvalue = str2kernel_uint_t(procfile_lineword(ff, 0, 20));
  1326. p->collected_starttime = str2kernel_uint_t(procfile_lineword(ff, 0, 21)) / system_hz;
  1327. p->uptime = (global_uptime > p->collected_starttime)?(global_uptime - p->collected_starttime):0;
  1328. // p->vsize = str2kernel_uint_t(procfile_lineword(ff, 0, 22));
  1329. // p->rss = str2kernel_uint_t(procfile_lineword(ff, 0, 23));
  1330. // p->rsslim = str2kernel_uint_t(procfile_lineword(ff, 0, 24));
  1331. // p->starcode = str2kernel_uint_t(procfile_lineword(ff, 0, 25));
  1332. // p->endcode = str2kernel_uint_t(procfile_lineword(ff, 0, 26));
  1333. // p->startstack = str2kernel_uint_t(procfile_lineword(ff, 0, 27));
  1334. // p->kstkesp = str2kernel_uint_t(procfile_lineword(ff, 0, 28));
  1335. // p->kstkeip = str2kernel_uint_t(procfile_lineword(ff, 0, 29));
  1336. // p->signal = str2kernel_uint_t(procfile_lineword(ff, 0, 30));
  1337. // p->blocked = str2kernel_uint_t(procfile_lineword(ff, 0, 31));
  1338. // p->sigignore = str2kernel_uint_t(procfile_lineword(ff, 0, 32));
  1339. // p->sigcatch = str2kernel_uint_t(procfile_lineword(ff, 0, 33));
  1340. // p->wchan = str2kernel_uint_t(procfile_lineword(ff, 0, 34));
  1341. // p->nswap = str2kernel_uint_t(procfile_lineword(ff, 0, 35));
  1342. // p->cnswap = str2kernel_uint_t(procfile_lineword(ff, 0, 36));
  1343. // p->exit_signal = str2kernel_uint_t(procfile_lineword(ff, 0, 37));
  1344. // p->processor = str2kernel_uint_t(procfile_lineword(ff, 0, 38));
  1345. // p->rt_priority = str2kernel_uint_t(procfile_lineword(ff, 0, 39));
  1346. // p->policy = str2kernel_uint_t(procfile_lineword(ff, 0, 40));
  1347. // p->delayacct_blkio_ticks = str2kernel_uint_t(procfile_lineword(ff, 0, 41));
  1348. if(enable_guest_charts) {
  1349. pid_incremental_rate(stat, p->gtime, str2kernel_uint_t(procfile_lineword(ff, 0, 42)));
  1350. pid_incremental_rate(stat, p->cgtime, str2kernel_uint_t(procfile_lineword(ff, 0, 43)));
  1351. if (show_guest_time || p->gtime || p->cgtime) {
  1352. p->utime -= (p->utime >= p->gtime) ? p->gtime : p->utime;
  1353. p->cutime -= (p->cutime >= p->cgtime) ? p->cgtime : p->cutime;
  1354. show_guest_time = 1;
  1355. }
  1356. }
  1357. #endif
  1358. if(unlikely(debug_enabled || (p->target && p->target->debug_enabled)))
  1359. debug_log_int("READ PROC/PID/STAT: %s/proc/%d/stat, process: '%s' on target '%s' (dt=%llu) VALUES: utime=" KERNEL_UINT_FORMAT ", stime=" KERNEL_UINT_FORMAT ", cutime=" KERNEL_UINT_FORMAT ", cstime=" KERNEL_UINT_FORMAT ", minflt=" KERNEL_UINT_FORMAT ", majflt=" KERNEL_UINT_FORMAT ", cminflt=" KERNEL_UINT_FORMAT ", cmajflt=" KERNEL_UINT_FORMAT ", threads=%d", netdata_configured_host_prefix, p->pid, p->comm, (p->target)?p->target->name:"UNSET", p->stat_collected_usec - p->last_stat_collected_usec, p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt, p->num_threads);
  1360. if(unlikely(global_iterations_counter == 1)) {
  1361. p->minflt = 0;
  1362. p->cminflt = 0;
  1363. p->majflt = 0;
  1364. p->cmajflt = 0;
  1365. p->utime = 0;
  1366. p->stime = 0;
  1367. p->gtime = 0;
  1368. p->cutime = 0;
  1369. p->cstime = 0;
  1370. p->cgtime = 0;
  1371. }
  1372. #ifndef __FreeBSD__
  1373. update_proc_state_count(p->state);
  1374. #endif
  1375. return 1;
  1376. cleanup:
  1377. p->minflt = 0;
  1378. p->cminflt = 0;
  1379. p->majflt = 0;
  1380. p->cmajflt = 0;
  1381. p->utime = 0;
  1382. p->stime = 0;
  1383. p->gtime = 0;
  1384. p->cutime = 0;
  1385. p->cstime = 0;
  1386. p->cgtime = 0;
  1387. p->num_threads = 0;
  1388. // p->rss = 0;
  1389. return 0;
  1390. }
  1391. // ----------------------------------------------------------------------------
  1392. static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
  1393. (void)ptr;
  1394. #ifdef __FreeBSD__
  1395. struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
  1396. #else
  1397. static procfile *ff = NULL;
  1398. if(unlikely(!p->io_filename)) {
  1399. char filename[FILENAME_MAX + 1];
  1400. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
  1401. p->io_filename = strdupz(filename);
  1402. }
  1403. // open the file
  1404. ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
  1405. if(unlikely(!ff)) goto cleanup;
  1406. ff = procfile_readall(ff);
  1407. if(unlikely(!ff)) goto cleanup;
  1408. #endif
  1409. calls_counter++;
  1410. p->last_io_collected_usec = p->io_collected_usec;
  1411. p->io_collected_usec = now_monotonic_usec();
  1412. #ifdef __FreeBSD__
  1413. pid_incremental_rate(io, p->io_storage_bytes_read, proc_info->ki_rusage.ru_inblock);
  1414. pid_incremental_rate(io, p->io_storage_bytes_written, proc_info->ki_rusage.ru_oublock);
  1415. #else
  1416. pid_incremental_rate(io, p->io_logical_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 0, 1)));
  1417. pid_incremental_rate(io, p->io_logical_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 1, 1)));
  1418. pid_incremental_rate(io, p->io_read_calls, str2kernel_uint_t(procfile_lineword(ff, 2, 1)));
  1419. pid_incremental_rate(io, p->io_write_calls, str2kernel_uint_t(procfile_lineword(ff, 3, 1)));
  1420. pid_incremental_rate(io, p->io_storage_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 4, 1)));
  1421. pid_incremental_rate(io, p->io_storage_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 5, 1)));
  1422. pid_incremental_rate(io, p->io_cancelled_write_bytes, str2kernel_uint_t(procfile_lineword(ff, 6, 1)));
  1423. #endif
  1424. if(unlikely(global_iterations_counter == 1)) {
  1425. p->io_logical_bytes_read = 0;
  1426. p->io_logical_bytes_written = 0;
  1427. p->io_read_calls = 0;
  1428. p->io_write_calls = 0;
  1429. p->io_storage_bytes_read = 0;
  1430. p->io_storage_bytes_written = 0;
  1431. p->io_cancelled_write_bytes = 0;
  1432. }
  1433. return 1;
  1434. #ifndef __FreeBSD__
  1435. cleanup:
  1436. p->io_logical_bytes_read = 0;
  1437. p->io_logical_bytes_written = 0;
  1438. p->io_read_calls = 0;
  1439. p->io_write_calls = 0;
  1440. p->io_storage_bytes_read = 0;
  1441. p->io_storage_bytes_written = 0;
  1442. p->io_cancelled_write_bytes = 0;
  1443. return 0;
  1444. #endif
  1445. }
  1446. #ifndef __FreeBSD__
  1447. static inline int read_global_time() {
  1448. static char filename[FILENAME_MAX + 1] = "";
  1449. static procfile *ff = NULL;
  1450. static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
  1451. static usec_t collected_usec = 0, last_collected_usec = 0;
  1452. if(unlikely(!ff)) {
  1453. snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
  1454. ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
  1455. if(unlikely(!ff)) goto cleanup;
  1456. }
  1457. ff = procfile_readall(ff);
  1458. if(unlikely(!ff)) goto cleanup;
  1459. last_collected_usec = collected_usec;
  1460. collected_usec = now_monotonic_usec();
  1461. calls_counter++;
  1462. // temporary - it is added global_ntime;
  1463. kernel_uint_t global_ntime = 0;
  1464. incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 1)), collected_usec, last_collected_usec);
  1465. incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 2)), collected_usec, last_collected_usec);
  1466. incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 3)), collected_usec, last_collected_usec);
  1467. incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
  1468. global_utime += global_ntime;
  1469. if(enable_guest_charts) {
  1470. // temporary - it is added global_ntime;
  1471. kernel_uint_t global_gntime = 0;
  1472. // guest nice time, on guest time
  1473. incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
  1474. global_gtime += global_gntime;
  1475. // remove guest time from user time
  1476. global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
  1477. }
  1478. if(unlikely(global_iterations_counter == 1)) {
  1479. global_utime = 0;
  1480. global_stime = 0;
  1481. global_gtime = 0;
  1482. }
  1483. return 1;
  1484. cleanup:
  1485. global_utime = 0;
  1486. global_stime = 0;
  1487. global_gtime = 0;
  1488. return 0;
  1489. }
  1490. #else
  1491. static inline int read_global_time() {
  1492. static kernel_uint_t utime_raw = 0, stime_raw = 0, ntime_raw = 0;
  1493. static usec_t collected_usec = 0, last_collected_usec = 0;
  1494. long cp_time[CPUSTATES];
  1495. if (unlikely(CPUSTATES != 5)) {
  1496. goto cleanup;
  1497. } else {
  1498. static int mib[2] = {0, 0};
  1499. if (unlikely(GETSYSCTL_SIMPLE("kern.cp_time", mib, cp_time))) {
  1500. goto cleanup;
  1501. }
  1502. }
  1503. last_collected_usec = collected_usec;
  1504. collected_usec = now_monotonic_usec();
  1505. calls_counter++;
  1506. // temporary - it is added global_ntime;
  1507. kernel_uint_t global_ntime = 0;
  1508. incremental_rate(global_utime, utime_raw, cp_time[0] * 100LLU / system_hz, collected_usec, last_collected_usec);
  1509. incremental_rate(global_ntime, ntime_raw, cp_time[1] * 100LLU / system_hz, collected_usec, last_collected_usec);
  1510. incremental_rate(global_stime, stime_raw, cp_time[2] * 100LLU / system_hz, collected_usec, last_collected_usec);
  1511. global_utime += global_ntime;
  1512. if(unlikely(global_iterations_counter == 1)) {
  1513. global_utime = 0;
  1514. global_stime = 0;
  1515. global_gtime = 0;
  1516. }
  1517. return 1;
  1518. cleanup:
  1519. global_utime = 0;
  1520. global_stime = 0;
  1521. global_gtime = 0;
  1522. return 0;
  1523. }
  1524. #endif /* !__FreeBSD__ */
  1525. // ----------------------------------------------------------------------------
  1526. int file_descriptor_compare(void* a, void* b) {
  1527. #ifdef NETDATA_INTERNAL_CHECKS
  1528. if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
  1529. netdata_log_error("Corrupted index data detected. Please report this.");
  1530. #endif /* NETDATA_INTERNAL_CHECKS */
  1531. if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
  1532. return -1;
  1533. else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
  1534. return 1;
  1535. else
  1536. return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
  1537. }
  1538. // int file_descriptor_iterator(avl_t *a) { if(a) {}; return 0; }
  1539. avl_tree_type all_files_index = {
  1540. NULL,
  1541. file_descriptor_compare
  1542. };
  1543. static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
  1544. struct file_descriptor tmp;
  1545. tmp.hash = (hash)?hash:simple_hash(name);
  1546. tmp.name = name;
  1547. tmp.count = 0;
  1548. tmp.pos = 0;
  1549. #ifdef NETDATA_INTERNAL_CHECKS
  1550. tmp.magic = 0x0BADCAFE;
  1551. #endif /* NETDATA_INTERNAL_CHECKS */
  1552. return (struct file_descriptor *)avl_search(&all_files_index, (avl_t *) &tmp);
  1553. }
  1554. #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl_t *)(fd))
  1555. #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl_t *)(fd))
  1556. // ----------------------------------------------------------------------------
  1557. static inline void file_descriptor_not_used(int id)
  1558. {
  1559. if(id > 0 && id < all_files_size) {
  1560. #ifdef NETDATA_INTERNAL_CHECKS
  1561. if(all_files[id].magic != 0x0BADCAFE) {
  1562. netdata_log_error("Ignoring request to remove empty file id %d.", id);
  1563. return;
  1564. }
  1565. #endif /* NETDATA_INTERNAL_CHECKS */
  1566. debug_log("decreasing slot %d (count = %d).", id, all_files[id].count);
  1567. if(all_files[id].count > 0) {
  1568. all_files[id].count--;
  1569. if(!all_files[id].count) {
  1570. debug_log(" >> slot %d is empty.", id);
  1571. if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
  1572. netdata_log_error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
  1573. #ifdef NETDATA_INTERNAL_CHECKS
  1574. all_files[id].magic = 0x00000000;
  1575. #endif /* NETDATA_INTERNAL_CHECKS */
  1576. all_files_len--;
  1577. }
  1578. }
  1579. else
  1580. netdata_log_error("Request to decrease counter of fd %d (%s), while the use counter is 0",
  1581. id,
  1582. all_files[id].name);
  1583. }
  1584. else
  1585. netdata_log_error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)",
  1586. id,
  1587. all_files_size);
  1588. }
  1589. static inline void all_files_grow() {
  1590. void *old = all_files;
  1591. int i;
  1592. // there is no empty slot
  1593. debug_log("extending fd array to %d entries", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
  1594. all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
  1595. // if the address changed, we have to rebuild the index
  1596. // since all pointers are now invalid
  1597. if(unlikely(old && old != (void *)all_files)) {
  1598. debug_log(" >> re-indexing.");
  1599. all_files_index.root = NULL;
  1600. for(i = 0; i < all_files_size; i++) {
  1601. if(!all_files[i].count) continue;
  1602. if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
  1603. netdata_log_error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
  1604. }
  1605. debug_log(" >> re-indexing done.");
  1606. }
  1607. // initialize the newly added entries
  1608. for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
  1609. all_files[i].count = 0;
  1610. all_files[i].name = NULL;
  1611. #ifdef NETDATA_INTERNAL_CHECKS
  1612. all_files[i].magic = 0x00000000;
  1613. #endif /* NETDATA_INTERNAL_CHECKS */
  1614. all_files[i].pos = i;
  1615. }
  1616. if(unlikely(!all_files_size)) all_files_len = 1;
  1617. all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
  1618. }
  1619. static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
  1620. // check we have enough memory to add it
  1621. if(!all_files || all_files_len == all_files_size)
  1622. all_files_grow();
  1623. debug_log(" >> searching for empty slot.");
  1624. // search for an empty slot
  1625. static int last_pos = 0;
  1626. int i, c;
  1627. for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
  1628. if(c >= all_files_size) c = 0;
  1629. if(c == 0) continue;
  1630. if(!all_files[c].count) {
  1631. debug_log(" >> Examining slot %d.", c);
  1632. #ifdef NETDATA_INTERNAL_CHECKS
  1633. if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
  1634. netdata_log_error("fd on position %d is not cleared properly. It still has %s in it.", c, all_files[c].name);
  1635. #endif /* NETDATA_INTERNAL_CHECKS */
  1636. debug_log(" >> %s fd position %d for %s (last name: %s)", all_files[c].name?"re-using":"using", c, name, all_files[c].name);
  1637. freez((void *)all_files[c].name);
  1638. all_files[c].name = NULL;
  1639. last_pos = c;
  1640. break;
  1641. }
  1642. }
  1643. all_files_len++;
  1644. if(i == all_files_size) {
  1645. fatal("We should find an empty slot, but there isn't any");
  1646. exit(1);
  1647. }
  1648. // else we have an empty slot in 'c'
  1649. debug_log(" >> updating slot %d.", c);
  1650. all_files[c].name = strdupz(name);
  1651. all_files[c].hash = hash;
  1652. all_files[c].type = type;
  1653. all_files[c].pos = c;
  1654. all_files[c].count = 1;
  1655. #ifdef NETDATA_INTERNAL_CHECKS
  1656. all_files[c].magic = 0x0BADCAFE;
  1657. #endif /* NETDATA_INTERNAL_CHECKS */
  1658. if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
  1659. netdata_log_error("INTERNAL ERROR: duplicate indexing of fd.");
  1660. debug_log("using fd position %d (name: %s)", c, all_files[c].name);
  1661. return c;
  1662. }
  1663. static inline int file_descriptor_find_or_add(const char *name, uint32_t hash) {
  1664. if(unlikely(!hash))
  1665. hash = simple_hash(name);
  1666. debug_log("adding or finding name '%s' with hash %u", name, hash);
  1667. struct file_descriptor *fd = file_descriptor_find(name, hash);
  1668. if(fd) {
  1669. // found
  1670. debug_log(" >> found on slot %d", fd->pos);
  1671. fd->count++;
  1672. return fd->pos;
  1673. }
  1674. // not found
  1675. FD_FILETYPE type;
  1676. if(likely(name[0] == '/')) type = FILETYPE_FILE;
  1677. else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
  1678. else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
  1679. else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
  1680. const char *t = &name[11];
  1681. if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
  1682. else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
  1683. else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
  1684. else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
  1685. else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
  1686. else {
  1687. debug_log("UNKNOWN anonymous inode: %s", name);
  1688. type = FILETYPE_OTHER;
  1689. }
  1690. }
  1691. else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
  1692. else {
  1693. debug_log("UNKNOWN linkname: %s", name);
  1694. type = FILETYPE_OTHER;
  1695. }
  1696. return file_descriptor_set_on_empty_slot(name, hash, type);
  1697. }
  1698. static inline void clear_pid_fd(struct pid_fd *pfd) {
  1699. pfd->fd = 0;
  1700. #ifndef __FreeBSD__
  1701. pfd->link_hash = 0;
  1702. pfd->inode = 0;
  1703. pfd->cache_iterations_counter = 0;
  1704. pfd->cache_iterations_reset = 0;
  1705. #endif
  1706. }
  1707. static inline void make_all_pid_fds_negative(struct pid_stat *p) {
  1708. struct pid_fd *pfd = p->fds, *pfdend = &p->fds[p->fds_size];
  1709. while(pfd < pfdend) {
  1710. pfd->fd = -(pfd->fd);
  1711. pfd++;
  1712. }
  1713. }
  1714. static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
  1715. struct pid_fd *pfd = p->fds, *pfdend = &p->fds[p->fds_size];
  1716. while(pfd < pfdend) {
  1717. int fd = pfd->fd;
  1718. if(unlikely(fd < 0)) {
  1719. file_descriptor_not_used(-(fd));
  1720. clear_pid_fd(pfd);
  1721. }
  1722. pfd++;
  1723. }
  1724. }
  1725. static inline void init_pid_fds(struct pid_stat *p, size_t first, size_t size) {
  1726. struct pid_fd *pfd = &p->fds[first], *pfdend = &p->fds[first + size];
  1727. while(pfd < pfdend) {
  1728. #ifndef __FreeBSD__
  1729. pfd->filename = NULL;
  1730. #endif
  1731. clear_pid_fd(pfd);
  1732. pfd++;
  1733. }
  1734. }
  1735. static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
  1736. (void)ptr;
  1737. #ifdef __FreeBSD__
  1738. int mib[4];
  1739. size_t size;
  1740. struct kinfo_file *fds;
  1741. static char *fdsbuf;
  1742. char *bfdsbuf, *efdsbuf;
  1743. char fdsname[FILENAME_MAX + 1];
  1744. #define SHM_FORMAT_LEN 31 // format: 21 + size: 10
  1745. char shm_name[FILENAME_MAX - SHM_FORMAT_LEN + 1];
  1746. // we make all pid fds negative, so that
  1747. // we can detect unused file descriptors
  1748. // at the end, to free them
  1749. make_all_pid_fds_negative(p);
  1750. mib[0] = CTL_KERN;
  1751. mib[1] = KERN_PROC;
  1752. mib[2] = KERN_PROC_FILEDESC;
  1753. mib[3] = p->pid;
  1754. if (unlikely(sysctl(mib, 4, NULL, &size, NULL, 0))) {
  1755. netdata_log_error("sysctl error: Can't get file descriptors data size for pid %d", p->pid);
  1756. return 0;
  1757. }
  1758. if (likely(size > 0))
  1759. fdsbuf = reallocz(fdsbuf, size);
  1760. if (unlikely(sysctl(mib, 4, fdsbuf, &size, NULL, 0))) {
  1761. netdata_log_error("sysctl error: Can't get file descriptors data for pid %d", p->pid);
  1762. return 0;
  1763. }
  1764. bfdsbuf = fdsbuf;
  1765. efdsbuf = fdsbuf + size;
  1766. while (bfdsbuf < efdsbuf) {
  1767. fds = (struct kinfo_file *)(uintptr_t)bfdsbuf;
  1768. if (unlikely(fds->kf_structsize == 0))
  1769. break;
  1770. // do not process file descriptors for current working directory, root directory,
  1771. // jail directory, ktrace vnode, text vnode and controlling terminal
  1772. if (unlikely(fds->kf_fd < 0)) {
  1773. bfdsbuf += fds->kf_structsize;
  1774. continue;
  1775. }
  1776. // get file descriptors array index
  1777. size_t fdid = fds->kf_fd;
  1778. // check if the fds array is small
  1779. if (unlikely(fdid >= p->fds_size)) {
  1780. // it is small, extend it
  1781. debug_log("extending fd memory slots for %s from %d to %d", p->comm, p->fds_size, fdid + MAX_SPARE_FDS);
  1782. p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(struct pid_fd));
  1783. // and initialize it
  1784. init_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
  1785. p->fds_size = fdid + MAX_SPARE_FDS;
  1786. }
  1787. if (unlikely(p->fds[fdid].fd == 0)) {
  1788. // we don't know this fd, get it
  1789. switch (fds->kf_type) {
  1790. case KF_TYPE_FIFO:
  1791. case KF_TYPE_VNODE:
  1792. if (unlikely(!fds->kf_path[0])) {
  1793. sprintf(fdsname, "other: inode: %lu", fds->kf_un.kf_file.kf_file_fileid);
  1794. break;
  1795. }
  1796. sprintf(fdsname, "%s", fds->kf_path);
  1797. break;
  1798. case KF_TYPE_SOCKET:
  1799. switch (fds->kf_sock_domain) {
  1800. case AF_INET:
  1801. case AF_INET6:
  1802. if (fds->kf_sock_protocol == IPPROTO_TCP)
  1803. sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_inpcb);
  1804. else
  1805. sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_pcb);
  1806. break;
  1807. case AF_UNIX:
  1808. /* print address of pcb and connected pcb */
  1809. sprintf(fdsname, "socket: %lx %lx", fds->kf_un.kf_sock.kf_sock_pcb, fds->kf_un.kf_sock.kf_sock_unpconn);
  1810. break;
  1811. default:
  1812. /* print protocol number and socket address */
  1813. #if __FreeBSD_version < 1200031
  1814. sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_sa_local.__ss_pad1, fds->kf_sa_local.__ss_pad2);
  1815. #else
  1816. sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sa_local.__ss_pad1, fds->kf_un.kf_sock.kf_sa_local.__ss_pad2);
  1817. #endif
  1818. }
  1819. break;
  1820. case KF_TYPE_PIPE:
  1821. sprintf(fdsname, "pipe: %lu %lu", fds->kf_un.kf_pipe.kf_pipe_addr, fds->kf_un.kf_pipe.kf_pipe_peer);
  1822. break;
  1823. case KF_TYPE_PTS:
  1824. #if __FreeBSD_version < 1200031
  1825. sprintf(fdsname, "other: pts: %u", fds->kf_un.kf_pts.kf_pts_dev);
  1826. #else
  1827. sprintf(fdsname, "other: pts: %lu", fds->kf_un.kf_pts.kf_pts_dev);
  1828. #endif
  1829. break;
  1830. case KF_TYPE_SHM:
  1831. strncpyz(shm_name, fds->kf_path, FILENAME_MAX - SHM_FORMAT_LEN);
  1832. sprintf(fdsname, "other: shm: %s size: %lu", shm_name, fds->kf_un.kf_file.kf_file_size);
  1833. break;
  1834. case KF_TYPE_SEM:
  1835. sprintf(fdsname, "other: sem: %u", fds->kf_un.kf_sem.kf_sem_value);
  1836. break;
  1837. default:
  1838. sprintf(fdsname, "other: pid: %d fd: %d", fds->kf_un.kf_proc.kf_pid, fds->kf_fd);
  1839. }
  1840. // if another process already has this, we will get
  1841. // the same id
  1842. p->fds[fdid].fd = file_descriptor_find_or_add(fdsname, 0);
  1843. }
  1844. // else make it positive again, we need it
  1845. // of course, the actual file may have changed
  1846. else
  1847. p->fds[fdid].fd = -p->fds[fdid].fd;
  1848. bfdsbuf += fds->kf_structsize;
  1849. }
  1850. #else
  1851. if(unlikely(!p->fds_dirname)) {
  1852. char dirname[FILENAME_MAX+1];
  1853. snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
  1854. p->fds_dirname = strdupz(dirname);
  1855. }
  1856. DIR *fds = opendir(p->fds_dirname);
  1857. if(unlikely(!fds)) return 0;
  1858. struct dirent *de;
  1859. char linkname[FILENAME_MAX + 1];
  1860. // we make all pid fds negative, so that
  1861. // we can detect unused file descriptors
  1862. // at the end, to free them
  1863. make_all_pid_fds_negative(p);
  1864. while((de = readdir(fds))) {
  1865. // we need only files with numeric names
  1866. if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
  1867. continue;
  1868. // get its number
  1869. int fdid = (int) str2l(de->d_name);
  1870. if(unlikely(fdid < 0)) continue;
  1871. // check if the fds array is small
  1872. if(unlikely((size_t)fdid >= p->fds_size)) {
  1873. // it is small, extend it
  1874. debug_log("extending fd memory slots for %s from %d to %d"
  1875. , p->comm
  1876. , p->fds_size
  1877. , fdid + MAX_SPARE_FDS
  1878. );
  1879. p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(struct pid_fd));
  1880. // and initialize it
  1881. init_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
  1882. p->fds_size = (size_t)fdid + MAX_SPARE_FDS;
  1883. }
  1884. if(unlikely(p->fds[fdid].fd < 0 && de->d_ino != p->fds[fdid].inode)) {
  1885. // inodes do not match, clear the previous entry
  1886. inodes_changed_counter++;
  1887. file_descriptor_not_used(-p->fds[fdid].fd);
  1888. clear_pid_fd(&p->fds[fdid]);
  1889. }
  1890. if(p->fds[fdid].fd < 0 && p->fds[fdid].cache_iterations_counter > 0) {
  1891. p->fds[fdid].fd = -p->fds[fdid].fd;
  1892. p->fds[fdid].cache_iterations_counter--;
  1893. continue;
  1894. }
  1895. if(unlikely(!p->fds[fdid].filename)) {
  1896. filenames_allocated_counter++;
  1897. char fdname[FILENAME_MAX + 1];
  1898. snprintfz(fdname, FILENAME_MAX, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
  1899. p->fds[fdid].filename = strdupz(fdname);
  1900. }
  1901. file_counter++;
  1902. ssize_t l = readlink(p->fds[fdid].filename, linkname, FILENAME_MAX);
  1903. if(unlikely(l == -1)) {
  1904. // cannot read the link
  1905. if(debug_enabled || (p->target && p->target->debug_enabled))
  1906. netdata_log_error("Cannot read link %s", p->fds[fdid].filename);
  1907. if(unlikely(p->fds[fdid].fd < 0)) {
  1908. file_descriptor_not_used(-p->fds[fdid].fd);
  1909. clear_pid_fd(&p->fds[fdid]);
  1910. }
  1911. continue;
  1912. }
  1913. else
  1914. linkname[l] = '\0';
  1915. uint32_t link_hash = simple_hash(linkname);
  1916. if(unlikely(p->fds[fdid].fd < 0 && p->fds[fdid].link_hash != link_hash)) {
  1917. // the link changed
  1918. links_changed_counter++;
  1919. file_descriptor_not_used(-p->fds[fdid].fd);
  1920. clear_pid_fd(&p->fds[fdid]);
  1921. }
  1922. if(unlikely(p->fds[fdid].fd == 0)) {
  1923. // we don't know this fd, get it
  1924. // if another process already has this, we will get
  1925. // the same id
  1926. p->fds[fdid].fd = file_descriptor_find_or_add(linkname, link_hash);
  1927. p->fds[fdid].inode = de->d_ino;
  1928. p->fds[fdid].link_hash = link_hash;
  1929. }
  1930. else {
  1931. // else make it positive again, we need it
  1932. p->fds[fdid].fd = -p->fds[fdid].fd;
  1933. }
  1934. // caching control
  1935. // without this we read all the files on every iteration
  1936. if(max_fds_cache_seconds > 0) {
  1937. size_t spread = ((size_t)max_fds_cache_seconds > 10) ? 10 : (size_t)max_fds_cache_seconds;
  1938. // cache it for a few iterations
  1939. size_t max = ((size_t) max_fds_cache_seconds + (fdid % spread)) / (size_t) update_every;
  1940. p->fds[fdid].cache_iterations_reset++;
  1941. if(unlikely(p->fds[fdid].cache_iterations_reset % spread == (size_t) fdid % spread))
  1942. p->fds[fdid].cache_iterations_reset++;
  1943. if(unlikely((fdid <= 2 && p->fds[fdid].cache_iterations_reset > 5) ||
  1944. p->fds[fdid].cache_iterations_reset > max)) {
  1945. // for stdin, stdout, stderr (fdid <= 2) we have checked a few times, or if it goes above the max, goto max
  1946. p->fds[fdid].cache_iterations_reset = max;
  1947. }
  1948. p->fds[fdid].cache_iterations_counter = p->fds[fdid].cache_iterations_reset;
  1949. }
  1950. }
  1951. closedir(fds);
  1952. #endif
  1953. cleanup_negative_pid_fds(p);
  1954. return 1;
  1955. }
  1956. // ----------------------------------------------------------------------------
  1957. static inline int debug_print_process_and_parents(struct pid_stat *p, usec_t time) {
  1958. char *prefix = "\\_ ";
  1959. int indent = 0;
  1960. if(p->parent)
  1961. indent = debug_print_process_and_parents(p->parent, p->stat_collected_usec);
  1962. else
  1963. prefix = " > ";
  1964. char buffer[indent + 1];
  1965. int i;
  1966. for(i = 0; i < indent ;i++) buffer[i] = ' ';
  1967. buffer[i] = '\0';
  1968. fprintf(stderr, " %s %s%s (%d %s %llu"
  1969. , buffer
  1970. , prefix
  1971. , p->comm
  1972. , p->pid
  1973. , p->updated?"running":"exited"
  1974. , p->stat_collected_usec - time
  1975. );
  1976. if(p->utime) fprintf(stderr, " utime=" KERNEL_UINT_FORMAT, p->utime);
  1977. if(p->stime) fprintf(stderr, " stime=" KERNEL_UINT_FORMAT, p->stime);
  1978. if(p->gtime) fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT, p->gtime);
  1979. if(p->cutime) fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT, p->cutime);
  1980. if(p->cstime) fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT, p->cstime);
  1981. if(p->cgtime) fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT, p->cgtime);
  1982. if(p->minflt) fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT, p->minflt);
  1983. if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
  1984. if(p->majflt) fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT, p->majflt);
  1985. if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
  1986. fprintf(stderr, ")\n");
  1987. return indent + 1;
  1988. }
  1989. static inline void debug_print_process_tree(struct pid_stat *p, char *msg __maybe_unused) {
  1990. debug_log("%s: process %s (%d, %s) with parents:", msg, p->comm, p->pid, p->updated?"running":"exited");
  1991. debug_print_process_and_parents(p, p->stat_collected_usec);
  1992. }
  1993. static inline void debug_find_lost_child(struct pid_stat *pe, kernel_uint_t lost, int type) {
  1994. int found = 0;
  1995. struct pid_stat *p = NULL;
  1996. for(p = root_of_pids; p ; p = p->next) {
  1997. if(p == pe) continue;
  1998. switch(type) {
  1999. case 1:
  2000. if(p->cminflt > lost) {
  2001. fprintf(stderr, " > process %d (%s) could use the lost exited child minflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
  2002. found++;
  2003. }
  2004. break;
  2005. case 2:
  2006. if(p->cmajflt > lost) {
  2007. fprintf(stderr, " > process %d (%s) could use the lost exited child majflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
  2008. found++;
  2009. }
  2010. break;
  2011. case 3:
  2012. if(p->cutime > lost) {
  2013. fprintf(stderr, " > process %d (%s) could use the lost exited child utime " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
  2014. found++;
  2015. }
  2016. break;
  2017. case 4:
  2018. if(p->cstime > lost) {
  2019. fprintf(stderr, " > process %d (%s) could use the lost exited child stime " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
  2020. found++;
  2021. }
  2022. break;
  2023. case 5:
  2024. if(p->cgtime > lost) {
  2025. fprintf(stderr, " > process %d (%s) could use the lost exited child gtime " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
  2026. found++;
  2027. }
  2028. break;
  2029. }
  2030. }
  2031. if(!found) {
  2032. switch(type) {
  2033. case 1:
  2034. fprintf(stderr, " > cannot find any process to use the lost exited child minflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
  2035. break;
  2036. case 2:
  2037. fprintf(stderr, " > cannot find any process to use the lost exited child majflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
  2038. break;
  2039. case 3:
  2040. fprintf(stderr, " > cannot find any process to use the lost exited child utime " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
  2041. break;
  2042. case 4:
  2043. fprintf(stderr, " > cannot find any process to use the lost exited child stime " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
  2044. break;
  2045. case 5:
  2046. fprintf(stderr, " > cannot find any process to use the lost exited child gtime " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
  2047. break;
  2048. }
  2049. }
  2050. }
  2051. static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
  2052. kernel_uint_t absorbed = 0;
  2053. if(*field > *pfield) {
  2054. absorbed += *pfield;
  2055. *field -= *pfield;
  2056. *pfield = 0;
  2057. }
  2058. else {
  2059. absorbed += *field;
  2060. *pfield -= *field;
  2061. *field = 0;
  2062. }
  2063. return absorbed;
  2064. }
  2065. static inline void process_exited_processes() {
  2066. struct pid_stat *p;
  2067. for(p = root_of_pids; p ; p = p->next) {
  2068. if(p->updated || !p->stat_collected_usec)
  2069. continue;
  2070. kernel_uint_t utime = (p->utime_raw + p->cutime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
  2071. kernel_uint_t stime = (p->stime_raw + p->cstime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
  2072. kernel_uint_t gtime = (p->gtime_raw + p->cgtime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
  2073. kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
  2074. kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
  2075. if(utime + stime + gtime + minflt + majflt == 0)
  2076. continue;
  2077. if(unlikely(debug_enabled)) {
  2078. debug_log("Absorb %s (%d %s total resources: utime=" KERNEL_UINT_FORMAT " stime=" KERNEL_UINT_FORMAT " gtime=" KERNEL_UINT_FORMAT " minflt=" KERNEL_UINT_FORMAT " majflt=" KERNEL_UINT_FORMAT ")"
  2079. , p->comm
  2080. , p->pid
  2081. , p->updated?"running":"exited"
  2082. , utime
  2083. , stime
  2084. , gtime
  2085. , minflt
  2086. , majflt
  2087. );
  2088. debug_print_process_tree(p, "Searching parents");
  2089. }
  2090. struct pid_stat *pp;
  2091. for(pp = p->parent; pp ; pp = pp->parent) {
  2092. if(!pp->updated) continue;
  2093. kernel_uint_t absorbed;
  2094. absorbed = remove_exited_child_from_parent(&utime, &pp->cutime);
  2095. if(unlikely(debug_enabled && absorbed))
  2096. debug_log(" > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " utime (remaining: " KERNEL_UINT_FORMAT ")", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, utime);
  2097. absorbed = remove_exited_child_from_parent(&stime, &pp->cstime);
  2098. if(unlikely(debug_enabled && absorbed))
  2099. debug_log(" > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " stime (remaining: " KERNEL_UINT_FORMAT ")", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, stime);
  2100. absorbed = remove_exited_child_from_parent(&gtime, &pp->cgtime);
  2101. if(unlikely(debug_enabled && absorbed))
  2102. debug_log(" > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " gtime (remaining: " KERNEL_UINT_FORMAT ")", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, gtime);
  2103. absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
  2104. if(unlikely(debug_enabled && absorbed))
  2105. debug_log(" > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " minflt (remaining: " KERNEL_UINT_FORMAT ")", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, minflt);
  2106. absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
  2107. if(unlikely(debug_enabled && absorbed))
  2108. debug_log(" > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " majflt (remaining: " KERNEL_UINT_FORMAT ")", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, majflt);
  2109. }
  2110. if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
  2111. if(unlikely(debug_enabled)) {
  2112. if(utime) debug_find_lost_child(p, utime, 3);
  2113. if(stime) debug_find_lost_child(p, stime, 4);
  2114. if(gtime) debug_find_lost_child(p, gtime, 5);
  2115. if(minflt) debug_find_lost_child(p, minflt, 1);
  2116. if(majflt) debug_find_lost_child(p, majflt, 2);
  2117. }
  2118. p->keep = true;
  2119. debug_log(" > remaining resources - KEEP - for another loop: %s (%d %s total resources: utime=" KERNEL_UINT_FORMAT " stime=" KERNEL_UINT_FORMAT " gtime=" KERNEL_UINT_FORMAT " minflt=" KERNEL_UINT_FORMAT " majflt=" KERNEL_UINT_FORMAT ")"
  2120. , p->comm
  2121. , p->pid
  2122. , p->updated?"running":"exited"
  2123. , utime
  2124. , stime
  2125. , gtime
  2126. , minflt
  2127. , majflt
  2128. );
  2129. for(pp = p->parent; pp ; pp = pp->parent) {
  2130. if(pp->updated) break;
  2131. pp->keep = true;
  2132. debug_log(" > - KEEP - parent for another loop: %s (%d %s)"
  2133. , pp->comm
  2134. , pp->pid
  2135. , pp->updated?"running":"exited"
  2136. );
  2137. }
  2138. p->utime_raw = utime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
  2139. p->stime_raw = stime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
  2140. p->gtime_raw = gtime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
  2141. p->minflt_raw = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
  2142. p->majflt_raw = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
  2143. p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
  2144. debug_log(" ");
  2145. }
  2146. else
  2147. debug_log(" > totally absorbed - DONE - %s (%d %s)"
  2148. , p->comm
  2149. , p->pid
  2150. , p->updated?"running":"exited"
  2151. );
  2152. }
  2153. }
  2154. static inline void link_all_processes_to_their_parents(void) {
  2155. struct pid_stat *p, *pp;
  2156. // link all children to their parents
  2157. // and update children count on parents
  2158. for(p = root_of_pids; p ; p = p->next) {
  2159. // for each process found
  2160. p->sortlist = 0;
  2161. p->parent = NULL;
  2162. if(unlikely(!p->ppid)) {
  2163. //unnecessary code from apps_plugin.c
  2164. //p->parent = NULL;
  2165. continue;
  2166. }
  2167. pp = all_pids[p->ppid];
  2168. if(likely(pp)) {
  2169. p->parent = pp;
  2170. pp->children_count++;
  2171. if(unlikely(debug_enabled || (p->target && p->target->debug_enabled)))
  2172. debug_log_int("child %d (%s, %s) on target '%s' has parent %d (%s, %s). Parent: utime=" KERNEL_UINT_FORMAT ", stime=" KERNEL_UINT_FORMAT ", gtime=" KERNEL_UINT_FORMAT ", minflt=" KERNEL_UINT_FORMAT ", majflt=" KERNEL_UINT_FORMAT ", cutime=" KERNEL_UINT_FORMAT ", cstime=" KERNEL_UINT_FORMAT ", cgtime=" KERNEL_UINT_FORMAT ", cminflt=" KERNEL_UINT_FORMAT ", cmajflt=" KERNEL_UINT_FORMAT "", p->pid, p->comm, p->updated?"running":"exited", (p->target)?p->target->name:"UNSET", pp->pid, pp->comm, pp->updated?"running":"exited", pp->utime, pp->stime, pp->gtime, pp->minflt, pp->majflt, pp->cutime, pp->cstime, pp->cgtime, pp->cminflt, pp->cmajflt);
  2173. }
  2174. else {
  2175. p->parent = NULL;
  2176. netdata_log_error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
  2177. }
  2178. }
  2179. }
  2180. // ----------------------------------------------------------------------------
  2181. // 1. read all files in /proc
  2182. // 2. for each numeric directory:
  2183. // i. read /proc/pid/stat
  2184. // ii. read /proc/pid/status
  2185. // iii. read /proc/pid/io (requires root access)
  2186. // iii. read the entries in directory /proc/pid/fd (requires root access)
  2187. // for each entry:
  2188. // a. find or create a struct file_descriptor
  2189. // b. cleanup any old/unused file_descriptors
  2190. // after all these, some pids may be linked to targets, while others may not
  2191. // in case of errors, only 1 every 1000 errors is printed
  2192. // to avoid filling up all disk space
  2193. // if debug is enabled, all errors are printed
  2194. #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
  2195. static int compar_pid(const void *pid1, const void *pid2) {
  2196. struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
  2197. struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
  2198. if(p1->sortlist > p2->sortlist)
  2199. return -1;
  2200. else
  2201. return 1;
  2202. }
  2203. #endif
  2204. static inline int collect_data_for_pid(pid_t pid, void *ptr) {
  2205. if(unlikely(pid < 0 || pid > pid_max)) {
  2206. netdata_log_error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, 0, pid_max);
  2207. return 0;
  2208. }
  2209. struct pid_stat *p = get_pid_entry(pid);
  2210. if(unlikely(!p || p->read)) return 0;
  2211. p->read = true;
  2212. // debug_log("Reading process %d (%s), sortlist %d", p->pid, p->comm, p->sortlist);
  2213. // --------------------------------------------------------------------
  2214. // /proc/<pid>/stat
  2215. if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
  2216. // there is no reason to proceed if we cannot get its status
  2217. return 0;
  2218. // check its parent pid
  2219. if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
  2220. netdata_log_error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
  2221. p->ppid = 0;
  2222. }
  2223. // --------------------------------------------------------------------
  2224. // /proc/<pid>/io
  2225. managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
  2226. // --------------------------------------------------------------------
  2227. // /proc/<pid>/status
  2228. if(unlikely(!managed_log(p, PID_LOG_STATUS, read_proc_pid_status(p, ptr))))
  2229. // there is no reason to proceed if we cannot get its status
  2230. return 0;
  2231. // --------------------------------------------------------------------
  2232. // /proc/<pid>/fd
  2233. if(enable_file_charts) {
  2234. managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
  2235. managed_log(p, PID_LOG_LIMITS, read_proc_pid_limits(p, ptr));
  2236. }
  2237. // --------------------------------------------------------------------
  2238. // done!
  2239. if(unlikely(debug_enabled && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
  2240. debug_log("Read process %d (%s) sortlisted %d, but its parent %d (%s) sortlisted %d, is not read", p->pid, p->comm, p->sortlist, all_pids[p->ppid]->pid, all_pids[p->ppid]->comm, all_pids[p->ppid]->sortlist);
  2241. // mark it as updated
  2242. p->updated = true;
  2243. p->keep = false;
  2244. p->keeploops = 0;
  2245. return 1;
  2246. }
  2247. static int collect_data_for_all_processes(void) {
  2248. struct pid_stat *p = NULL;
  2249. #ifndef __FreeBSD__
  2250. // clear process state counter
  2251. memset(proc_state_count, 0, sizeof proc_state_count);
  2252. #else
  2253. int i, procnum;
  2254. static size_t procbase_size = 0;
  2255. static struct kinfo_proc *procbase = NULL;
  2256. size_t new_procbase_size;
  2257. int mib[3] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC };
  2258. if (unlikely(sysctl(mib, 3, NULL, &new_procbase_size, NULL, 0))) {
  2259. netdata_log_error("sysctl error: Can't get processes data size");
  2260. return 0;
  2261. }
  2262. // give it some air for processes that may be started
  2263. // during this little time.
  2264. new_procbase_size += 100 * sizeof(struct kinfo_proc);
  2265. // increase the buffer if needed
  2266. if(new_procbase_size > procbase_size) {
  2267. procbase_size = new_procbase_size;
  2268. procbase = reallocz(procbase, procbase_size);
  2269. }
  2270. // sysctl() gets from new_procbase_size the buffer size
  2271. // and also returns to it the amount of data filled in
  2272. new_procbase_size = procbase_size;
  2273. // get the processes from the system
  2274. if (unlikely(sysctl(mib, 3, procbase, &new_procbase_size, NULL, 0))) {
  2275. netdata_log_error("sysctl error: Can't get processes data");
  2276. return 0;
  2277. }
  2278. // based on the amount of data filled in
  2279. // calculate the number of processes we got
  2280. procnum = new_procbase_size / sizeof(struct kinfo_proc);
  2281. #endif
  2282. if(all_pids_count) {
  2283. #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
  2284. size_t slc = 0;
  2285. #endif
  2286. for(p = root_of_pids; p ; p = p->next) {
  2287. p->read = false; // mark it as not read, so that collect_data_for_pid() will read it
  2288. p->updated = false;
  2289. p->merged = false;
  2290. p->children_count = 0;
  2291. p->parent = NULL;
  2292. #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
  2293. all_pids_sortlist[slc++] = p->pid;
  2294. #endif
  2295. }
  2296. #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
  2297. if(unlikely(slc != all_pids_count)) {
  2298. netdata_log_error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are %zu.", all_pids_count, slc);
  2299. all_pids_count = slc;
  2300. }
  2301. if(include_exited_childs) {
  2302. // Read parents before childs
  2303. // This is needed to prevent a situation where
  2304. // a child is found running, but until we read
  2305. // its parent, it has exited and its parent
  2306. // has accumulated its resources.
  2307. qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
  2308. // we forward read all running processes
  2309. // collect_data_for_pid() is smart enough,
  2310. // not to read the same pid twice per iteration
  2311. for(slc = 0; slc < all_pids_count; slc++) {
  2312. collect_data_for_pid(all_pids_sortlist[slc], NULL);
  2313. }
  2314. }
  2315. #endif
  2316. }
  2317. #ifdef __FreeBSD__
  2318. for (i = 0 ; i < procnum ; ++i) {
  2319. pid_t pid = procbase[i].ki_pid;
  2320. collect_data_for_pid(pid, &procbase[i]);
  2321. }
  2322. #else
  2323. static char uptime_filename[FILENAME_MAX + 1] = "";
  2324. if(*uptime_filename == '\0')
  2325. snprintfz(uptime_filename, FILENAME_MAX, "%s/proc/uptime", netdata_configured_host_prefix);
  2326. global_uptime = (kernel_uint_t)(uptime_msec(uptime_filename) / MSEC_PER_SEC);
  2327. char dirname[FILENAME_MAX + 1];
  2328. snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
  2329. DIR *dir = opendir(dirname);
  2330. if(!dir) return 0;
  2331. struct dirent *de = NULL;
  2332. while((de = readdir(dir))) {
  2333. char *endptr = de->d_name;
  2334. if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
  2335. continue;
  2336. pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
  2337. // make sure we read a valid number
  2338. if(unlikely(endptr == de->d_name || *endptr != '\0'))
  2339. continue;
  2340. collect_data_for_pid(pid, NULL);
  2341. }
  2342. closedir(dir);
  2343. #endif
  2344. if(!all_pids_count)
  2345. return 0;
  2346. // we need /proc/stat to normalize the cpu consumption of the exited childs
  2347. read_global_time();
  2348. // build the process tree
  2349. link_all_processes_to_their_parents();
  2350. // normally this is done
  2351. // however we may have processes exited while we collected values
  2352. // so let's find the exited ones
  2353. // we do this by collecting the ownership of process
  2354. // if we manage to get the ownership, the process still runs
  2355. process_exited_processes();
  2356. return 1;
  2357. }
  2358. // ----------------------------------------------------------------------------
  2359. // update statistics on the targets
  2360. // 1. link all childs to their parents
  2361. // 2. go from bottom to top, marking as merged all childs to their parents
  2362. // this step links all parents without a target to the child target, if any
  2363. // 3. link all top level processes (the ones not merged) to the default target
  2364. // 4. go from top to bottom, linking all childs without a target, to their parent target
  2365. // after this step, all processes have a target
  2366. // [5. for each killed pid (updated = 0), remove its usage from its target]
  2367. // 6. zero all apps_groups_targets
  2368. // 7. concentrate all values on the apps_groups_targets
  2369. // 8. remove all killed processes
  2370. // 9. find the unique file count for each target
  2371. // check: update_apps_groups_statistics()
  2372. static void cleanup_exited_pids(void) {
  2373. size_t c;
  2374. struct pid_stat *p = NULL;
  2375. for(p = root_of_pids; p ;) {
  2376. if(!p->updated && (!p->keep || p->keeploops > 0)) {
  2377. if(unlikely(debug_enabled && (p->keep || p->keeploops)))
  2378. debug_log(" > CLEANUP cannot keep exited process %d (%s) anymore - removing it.", p->pid, p->comm);
  2379. for(c = 0; c < p->fds_size; c++)
  2380. if(p->fds[c].fd > 0) {
  2381. file_descriptor_not_used(p->fds[c].fd);
  2382. clear_pid_fd(&p->fds[c]);
  2383. }
  2384. pid_t r = p->pid;
  2385. p = p->next;
  2386. del_pid_entry(r);
  2387. }
  2388. else {
  2389. if(unlikely(p->keep)) p->keeploops++;
  2390. p->keep = false;
  2391. p = p->next;
  2392. }
  2393. }
  2394. }
  2395. static void apply_apps_groups_targets_inheritance(void) {
  2396. struct pid_stat *p = NULL;
  2397. // children that do not have a target
  2398. // inherit their target from their parent
  2399. int found = 1, loops = 0;
  2400. while(found) {
  2401. if(unlikely(debug_enabled)) loops++;
  2402. found = 0;
  2403. for(p = root_of_pids; p ; p = p->next) {
  2404. // if this process does not have a target,
  2405. // and it has a parent
  2406. // and its parent has a target
  2407. // then, set the parent's target to this process
  2408. if(unlikely(!p->target && p->parent && p->parent->target)) {
  2409. p->target = p->parent->target;
  2410. found++;
  2411. if(debug_enabled || (p->target && p->target->debug_enabled))
  2412. debug_log_int("TARGET INHERITANCE: %s is inherited by %d (%s) from its parent %d (%s).", p->target->name, p->pid, p->comm, p->parent->pid, p->parent->comm);
  2413. }
  2414. }
  2415. }
  2416. // find all the procs with 0 childs and merge them to their parents
  2417. // repeat, until nothing more can be done.
  2418. int sortlist = 1;
  2419. found = 1;
  2420. while(found) {
  2421. if(unlikely(debug_enabled)) loops++;
  2422. found = 0;
  2423. for(p = root_of_pids; p ; p = p->next) {
  2424. if(unlikely(!p->sortlist && !p->children_count))
  2425. p->sortlist = sortlist++;
  2426. if(unlikely(
  2427. !p->children_count // if this process does not have any children
  2428. && !p->merged // and is not already merged
  2429. && p->parent // and has a parent
  2430. && p->parent->children_count // and its parent has children
  2431. // and the target of this process and its parent is the same,
  2432. // or the parent does not have a target
  2433. && (p->target == p->parent->target || !p->parent->target)
  2434. && p->ppid != INIT_PID // and its parent is not init
  2435. )) {
  2436. // mark it as merged
  2437. p->parent->children_count--;
  2438. p->merged = true;
  2439. // the parent inherits the child's target, if it does not have a target itself
  2440. if(unlikely(p->target && !p->parent->target)) {
  2441. p->parent->target = p->target;
  2442. if(debug_enabled || (p->target && p->target->debug_enabled))
  2443. debug_log_int("TARGET INHERITANCE: %s is inherited by %d (%s) from its child %d (%s).", p->target->name, p->parent->pid, p->parent->comm, p->pid, p->comm);
  2444. }
  2445. found++;
  2446. }
  2447. }
  2448. debug_log("TARGET INHERITANCE: merged %d processes", found);
  2449. }
  2450. // init goes always to default target
  2451. if(all_pids[INIT_PID] && !all_pids[INIT_PID]->matched_by_config)
  2452. all_pids[INIT_PID]->target = apps_groups_default_target;
  2453. // pid 0 goes always to default target
  2454. if(all_pids[0] && !all_pids[INIT_PID]->matched_by_config)
  2455. all_pids[0]->target = apps_groups_default_target;
  2456. // give a default target on all top level processes
  2457. if(unlikely(debug_enabled)) loops++;
  2458. for(p = root_of_pids; p ; p = p->next) {
  2459. // if the process is not merged itself
  2460. // then it is a top level process
  2461. if(unlikely(!p->merged && !p->target))
  2462. p->target = apps_groups_default_target;
  2463. // make sure all processes have a sortlist
  2464. if(unlikely(!p->sortlist))
  2465. p->sortlist = sortlist++;
  2466. }
  2467. if(all_pids[1])
  2468. all_pids[1]->sortlist = sortlist++;
  2469. // give a target to all merged child processes
  2470. found = 1;
  2471. while(found) {
  2472. if(unlikely(debug_enabled)) loops++;
  2473. found = 0;
  2474. for(p = root_of_pids; p ; p = p->next) {
  2475. if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
  2476. p->target = p->parent->target;
  2477. found++;
  2478. if(debug_enabled || (p->target && p->target->debug_enabled))
  2479. debug_log_int("TARGET INHERITANCE: %s is inherited by %d (%s) from its parent %d (%s) at phase 2.", p->target->name, p->pid, p->comm, p->parent->pid, p->parent->comm);
  2480. }
  2481. }
  2482. }
  2483. debug_log("apply_apps_groups_targets_inheritance() made %d loops on the process tree", loops);
  2484. }
  2485. static size_t zero_all_targets(struct target *root) {
  2486. struct target *w;
  2487. size_t count = 0;
  2488. for (w = root; w ; w = w->next) {
  2489. count++;
  2490. w->minflt = 0;
  2491. w->majflt = 0;
  2492. w->utime = 0;
  2493. w->stime = 0;
  2494. w->gtime = 0;
  2495. w->cminflt = 0;
  2496. w->cmajflt = 0;
  2497. w->cutime = 0;
  2498. w->cstime = 0;
  2499. w->cgtime = 0;
  2500. w->num_threads = 0;
  2501. // w->rss = 0;
  2502. w->processes = 0;
  2503. w->status_vmsize = 0;
  2504. w->status_vmrss = 0;
  2505. w->status_vmshared = 0;
  2506. w->status_rssfile = 0;
  2507. w->status_rssshmem = 0;
  2508. w->status_vmswap = 0;
  2509. w->status_voluntary_ctxt_switches = 0;
  2510. w->status_nonvoluntary_ctxt_switches = 0;
  2511. w->io_logical_bytes_read = 0;
  2512. w->io_logical_bytes_written = 0;
  2513. w->io_read_calls = 0;
  2514. w->io_write_calls = 0;
  2515. w->io_storage_bytes_read = 0;
  2516. w->io_storage_bytes_written = 0;
  2517. w->io_cancelled_write_bytes = 0;
  2518. // zero file counters
  2519. if(w->target_fds) {
  2520. memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
  2521. w->openfds.files = 0;
  2522. w->openfds.pipes = 0;
  2523. w->openfds.sockets = 0;
  2524. w->openfds.inotifies = 0;
  2525. w->openfds.eventfds = 0;
  2526. w->openfds.timerfds = 0;
  2527. w->openfds.signalfds = 0;
  2528. w->openfds.eventpolls = 0;
  2529. w->openfds.other = 0;
  2530. w->max_open_files_percent = 0.0;
  2531. }
  2532. w->collected_starttime = 0;
  2533. w->uptime_min = 0;
  2534. w->uptime_sum = 0;
  2535. w->uptime_max = 0;
  2536. if(unlikely(w->root_pid)) {
  2537. struct pid_on_target *pid_on_target_to_free, *pid_on_target = w->root_pid;
  2538. while(pid_on_target) {
  2539. pid_on_target_to_free = pid_on_target;
  2540. pid_on_target = pid_on_target->next;
  2541. freez(pid_on_target_to_free);
  2542. }
  2543. w->root_pid = NULL;
  2544. }
  2545. }
  2546. return count;
  2547. }
  2548. static inline void reallocate_target_fds(struct target *w) {
  2549. if(unlikely(!w))
  2550. return;
  2551. if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
  2552. w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
  2553. memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
  2554. w->target_fds_size = all_files_size;
  2555. }
  2556. }
  2557. static void aggregage_fd_type_on_openfds(FD_FILETYPE type, struct openfds *openfds) {
  2558. switch(type) {
  2559. case FILETYPE_FILE:
  2560. openfds->files++;
  2561. break;
  2562. case FILETYPE_PIPE:
  2563. openfds->pipes++;
  2564. break;
  2565. case FILETYPE_SOCKET:
  2566. openfds->sockets++;
  2567. break;
  2568. case FILETYPE_INOTIFY:
  2569. openfds->inotifies++;
  2570. break;
  2571. case FILETYPE_EVENTFD:
  2572. openfds->eventfds++;
  2573. break;
  2574. case FILETYPE_TIMERFD:
  2575. openfds->timerfds++;
  2576. break;
  2577. case FILETYPE_SIGNALFD:
  2578. openfds->signalfds++;
  2579. break;
  2580. case FILETYPE_EVENTPOLL:
  2581. openfds->eventpolls++;
  2582. break;
  2583. case FILETYPE_OTHER:
  2584. openfds->other++;
  2585. break;
  2586. }
  2587. }
  2588. static inline void aggregate_fd_on_target(int fd, struct target *w) {
  2589. if(unlikely(!w))
  2590. return;
  2591. if(unlikely(w->target_fds[fd])) {
  2592. // it is already aggregated
  2593. // just increase its usage counter
  2594. w->target_fds[fd]++;
  2595. return;
  2596. }
  2597. // increase its usage counter
  2598. // so that we will not add it again
  2599. w->target_fds[fd]++;
  2600. aggregage_fd_type_on_openfds(all_files[fd].type, &w->openfds);
  2601. }
  2602. static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
  2603. if(unlikely(!p->updated)) {
  2604. // the process is not running
  2605. return;
  2606. }
  2607. struct target *w = p->target, *u = p->user_target, *g = p->group_target;
  2608. reallocate_target_fds(w);
  2609. reallocate_target_fds(u);
  2610. reallocate_target_fds(g);
  2611. p->openfds.files = 0;
  2612. p->openfds.pipes = 0;
  2613. p->openfds.sockets = 0;
  2614. p->openfds.inotifies = 0;
  2615. p->openfds.eventfds = 0;
  2616. p->openfds.timerfds = 0;
  2617. p->openfds.signalfds = 0;
  2618. p->openfds.eventpolls = 0;
  2619. p->openfds.other = 0;
  2620. long currentfds = 0;
  2621. size_t c, size = p->fds_size;
  2622. struct pid_fd *fds = p->fds;
  2623. for(c = 0; c < size ;c++) {
  2624. int fd = fds[c].fd;
  2625. if(likely(fd <= 0 || fd >= all_files_size))
  2626. continue;
  2627. currentfds++;
  2628. aggregage_fd_type_on_openfds(all_files[fd].type, &p->openfds);
  2629. aggregate_fd_on_target(fd, w);
  2630. aggregate_fd_on_target(fd, u);
  2631. aggregate_fd_on_target(fd, g);
  2632. }
  2633. }
  2634. static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
  2635. (void)o;
  2636. if(unlikely(!p->updated)) {
  2637. // the process is not running
  2638. return;
  2639. }
  2640. if(unlikely(!w)) {
  2641. netdata_log_error("pid %d %s was left without a target!", p->pid, p->comm);
  2642. return;
  2643. }
  2644. if(p->openfds_limits_percent > w->max_open_files_percent)
  2645. w->max_open_files_percent = p->openfds_limits_percent;
  2646. w->cutime += p->cutime;
  2647. w->cstime += p->cstime;
  2648. w->cgtime += p->cgtime;
  2649. w->cminflt += p->cminflt;
  2650. w->cmajflt += p->cmajflt;
  2651. w->utime += p->utime;
  2652. w->stime += p->stime;
  2653. w->gtime += p->gtime;
  2654. w->minflt += p->minflt;
  2655. w->majflt += p->majflt;
  2656. // w->rss += p->rss;
  2657. w->status_vmsize += p->status_vmsize;
  2658. w->status_vmrss += p->status_vmrss;
  2659. w->status_vmshared += p->status_vmshared;
  2660. w->status_rssfile += p->status_rssfile;
  2661. w->status_rssshmem += p->status_rssshmem;
  2662. w->status_vmswap += p->status_vmswap;
  2663. w->status_voluntary_ctxt_switches += p->status_voluntary_ctxt_switches;
  2664. w->status_nonvoluntary_ctxt_switches += p->status_nonvoluntary_ctxt_switches;
  2665. w->io_logical_bytes_read += p->io_logical_bytes_read;
  2666. w->io_logical_bytes_written += p->io_logical_bytes_written;
  2667. w->io_read_calls += p->io_read_calls;
  2668. w->io_write_calls += p->io_write_calls;
  2669. w->io_storage_bytes_read += p->io_storage_bytes_read;
  2670. w->io_storage_bytes_written += p->io_storage_bytes_written;
  2671. w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
  2672. w->processes++;
  2673. w->num_threads += p->num_threads;
  2674. if(!w->collected_starttime || p->collected_starttime < w->collected_starttime) w->collected_starttime = p->collected_starttime;
  2675. if(!w->uptime_min || p->uptime < w->uptime_min) w->uptime_min = p->uptime;
  2676. w->uptime_sum += p->uptime;
  2677. if(!w->uptime_max || w->uptime_max < p->uptime) w->uptime_max = p->uptime;
  2678. if(unlikely(debug_enabled || w->debug_enabled)) {
  2679. debug_log_int("aggregating '%s' pid %d on target '%s' utime=" KERNEL_UINT_FORMAT ", stime=" KERNEL_UINT_FORMAT ", gtime=" KERNEL_UINT_FORMAT ", cutime=" KERNEL_UINT_FORMAT ", cstime=" KERNEL_UINT_FORMAT ", cgtime=" KERNEL_UINT_FORMAT ", minflt=" KERNEL_UINT_FORMAT ", majflt=" KERNEL_UINT_FORMAT ", cminflt=" KERNEL_UINT_FORMAT ", cmajflt=" KERNEL_UINT_FORMAT "", p->comm, p->pid, w->name, p->utime, p->stime, p->gtime, p->cutime, p->cstime, p->cgtime, p->minflt, p->majflt, p->cminflt, p->cmajflt);
  2680. struct pid_on_target *pid_on_target = mallocz(sizeof(struct pid_on_target));
  2681. pid_on_target->pid = p->pid;
  2682. pid_on_target->next = w->root_pid;
  2683. w->root_pid = pid_on_target;
  2684. }
  2685. }
  2686. static inline void post_aggregate_targets(struct target *root) {
  2687. struct target *w;
  2688. for (w = root; w ; w = w->next) {
  2689. if(w->collected_starttime) {
  2690. if (!w->starttime || w->collected_starttime < w->starttime) {
  2691. w->starttime = w->collected_starttime;
  2692. }
  2693. } else {
  2694. w->starttime = 0;
  2695. }
  2696. }
  2697. }
  2698. static void calculate_netdata_statistics(void) {
  2699. apply_apps_groups_targets_inheritance();
  2700. zero_all_targets(users_root_target);
  2701. zero_all_targets(groups_root_target);
  2702. apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
  2703. // this has to be done, before the cleanup
  2704. struct pid_stat *p = NULL;
  2705. struct target *w = NULL, *o = NULL;
  2706. // concentrate everything on the targets
  2707. for(p = root_of_pids; p ; p = p->next) {
  2708. // --------------------------------------------------------------------
  2709. // apps_groups target
  2710. aggregate_pid_on_target(p->target, p, NULL);
  2711. // --------------------------------------------------------------------
  2712. // user target
  2713. o = p->user_target;
  2714. if(likely(p->user_target && p->user_target->uid == p->uid))
  2715. w = p->user_target;
  2716. else {
  2717. if(unlikely(debug_enabled && p->user_target))
  2718. debug_log("pid %d (%s) switched user from %u (%s) to %u.", p->pid, p->comm, p->user_target->uid, p->user_target->name, p->uid);
  2719. w = p->user_target = get_users_target(p->uid);
  2720. }
  2721. aggregate_pid_on_target(w, p, o);
  2722. // --------------------------------------------------------------------
  2723. // user group target
  2724. o = p->group_target;
  2725. if(likely(p->group_target && p->group_target->gid == p->gid))
  2726. w = p->group_target;
  2727. else {
  2728. if(unlikely(debug_enabled && p->group_target))
  2729. debug_log("pid %d (%s) switched group from %u (%s) to %u.", p->pid, p->comm, p->group_target->gid, p->group_target->name, p->gid);
  2730. w = p->group_target = get_groups_target(p->gid);
  2731. }
  2732. aggregate_pid_on_target(w, p, o);
  2733. // --------------------------------------------------------------------
  2734. // aggregate all file descriptors
  2735. if(enable_file_charts)
  2736. aggregate_pid_fds_on_targets(p);
  2737. }
  2738. post_aggregate_targets(apps_groups_root_target);
  2739. post_aggregate_targets(users_root_target);
  2740. post_aggregate_targets(groups_root_target);
  2741. cleanup_exited_pids();
  2742. }
  2743. // ----------------------------------------------------------------------------
  2744. // update chart dimensions
  2745. static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
  2746. fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
  2747. }
  2748. static inline void send_SET(const char *name, kernel_uint_t value) {
  2749. fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
  2750. }
  2751. static inline void send_END(void) {
  2752. fprintf(stdout, "END\n");
  2753. }
  2754. void send_resource_usage_to_netdata(usec_t dt) {
  2755. static struct timeval last = { 0, 0 };
  2756. static struct rusage me_last;
  2757. struct timeval now;
  2758. struct rusage me;
  2759. usec_t cpuuser;
  2760. usec_t cpusyst;
  2761. if(!last.tv_sec) {
  2762. now_monotonic_timeval(&last);
  2763. getrusage(RUSAGE_SELF, &me_last);
  2764. cpuuser = 0;
  2765. cpusyst = 0;
  2766. }
  2767. else {
  2768. now_monotonic_timeval(&now);
  2769. getrusage(RUSAGE_SELF, &me);
  2770. cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
  2771. cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
  2772. memmove(&last, &now, sizeof(struct timeval));
  2773. memmove(&me_last, &me, sizeof(struct rusage));
  2774. }
  2775. static char created_charts = 0;
  2776. if(unlikely(!created_charts)) {
  2777. created_charts = 1;
  2778. fprintf(stdout,
  2779. "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
  2780. "DIMENSION user '' incremental 1 1000\n"
  2781. "DIMENSION system '' incremental 1 1000\n"
  2782. "CHART netdata.apps_sizes '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_sizes line 140001 %1$d\n"
  2783. "DIMENSION calls '' incremental 1 1\n"
  2784. "DIMENSION files '' incremental 1 1\n"
  2785. "DIMENSION filenames '' incremental 1 1\n"
  2786. "DIMENSION inode_changes '' incremental 1 1\n"
  2787. "DIMENSION link_changes '' incremental 1 1\n"
  2788. "DIMENSION pids '' absolute 1 1\n"
  2789. "DIMENSION fds '' absolute 1 1\n"
  2790. "DIMENSION targets '' absolute 1 1\n"
  2791. "DIMENSION new_pids 'new pids' incremental 1 1\n"
  2792. , update_every
  2793. );
  2794. fprintf(stdout,
  2795. "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
  2796. "DIMENSION utime '' absolute 1 %2$llu\n"
  2797. "DIMENSION stime '' absolute 1 %2$llu\n"
  2798. "DIMENSION gtime '' absolute 1 %2$llu\n"
  2799. "DIMENSION minflt '' absolute 1 %2$llu\n"
  2800. "DIMENSION majflt '' absolute 1 %2$llu\n"
  2801. , update_every
  2802. , RATES_DETAIL
  2803. );
  2804. if(include_exited_childs)
  2805. fprintf(stdout,
  2806. "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
  2807. "DIMENSION cutime '' absolute 1 %2$llu\n"
  2808. "DIMENSION cstime '' absolute 1 %2$llu\n"
  2809. "DIMENSION cgtime '' absolute 1 %2$llu\n"
  2810. "DIMENSION cminflt '' absolute 1 %2$llu\n"
  2811. "DIMENSION cmajflt '' absolute 1 %2$llu\n"
  2812. , update_every
  2813. , RATES_DETAIL
  2814. );
  2815. }
  2816. fprintf(stdout,
  2817. "BEGIN netdata.apps_cpu %llu\n"
  2818. "SET user = %llu\n"
  2819. "SET system = %llu\n"
  2820. "END\n"
  2821. "BEGIN netdata.apps_sizes %llu\n"
  2822. "SET calls = %zu\n"
  2823. "SET files = %zu\n"
  2824. "SET filenames = %zu\n"
  2825. "SET inode_changes = %zu\n"
  2826. "SET link_changes = %zu\n"
  2827. "SET pids = %zu\n"
  2828. "SET fds = %d\n"
  2829. "SET targets = %zu\n"
  2830. "SET new_pids = %zu\n"
  2831. "END\n"
  2832. , dt
  2833. , cpuuser
  2834. , cpusyst
  2835. , dt
  2836. , calls_counter
  2837. , file_counter
  2838. , filenames_allocated_counter
  2839. , inodes_changed_counter
  2840. , links_changed_counter
  2841. , all_pids_count
  2842. , all_files_len
  2843. , apps_groups_targets_count
  2844. , targets_assignment_counter
  2845. );
  2846. fprintf(stdout,
  2847. "BEGIN netdata.apps_fix %llu\n"
  2848. "SET utime = %u\n"
  2849. "SET stime = %u\n"
  2850. "SET gtime = %u\n"
  2851. "SET minflt = %u\n"
  2852. "SET majflt = %u\n"
  2853. "END\n"
  2854. , dt
  2855. , (unsigned int)(utime_fix_ratio * 100 * RATES_DETAIL)
  2856. , (unsigned int)(stime_fix_ratio * 100 * RATES_DETAIL)
  2857. , (unsigned int)(gtime_fix_ratio * 100 * RATES_DETAIL)
  2858. , (unsigned int)(minflt_fix_ratio * 100 * RATES_DETAIL)
  2859. , (unsigned int)(majflt_fix_ratio * 100 * RATES_DETAIL)
  2860. );
  2861. if(include_exited_childs)
  2862. fprintf(stdout,
  2863. "BEGIN netdata.apps_children_fix %llu\n"
  2864. "SET cutime = %u\n"
  2865. "SET cstime = %u\n"
  2866. "SET cgtime = %u\n"
  2867. "SET cminflt = %u\n"
  2868. "SET cmajflt = %u\n"
  2869. "END\n"
  2870. , dt
  2871. , (unsigned int)(cutime_fix_ratio * 100 * RATES_DETAIL)
  2872. , (unsigned int)(cstime_fix_ratio * 100 * RATES_DETAIL)
  2873. , (unsigned int)(cgtime_fix_ratio * 100 * RATES_DETAIL)
  2874. , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
  2875. , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
  2876. );
  2877. }
  2878. static void normalize_utilization(struct target *root) {
  2879. struct target *w;
  2880. // childs processing introduces spikes
  2881. // here we try to eliminate them by disabling childs processing either for specific dimensions
  2882. // or entirely. Of course, either way, we disable it just a single iteration.
  2883. kernel_uint_t max_time = get_system_cpus() * time_factor * RATES_DETAIL;
  2884. kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
  2885. if(global_utime > max_time) global_utime = max_time;
  2886. if(global_stime > max_time) global_stime = max_time;
  2887. if(global_gtime > max_time) global_gtime = max_time;
  2888. for(w = root; w ; w = w->next) {
  2889. if(w->target || (!w->processes && !w->exposed)) continue;
  2890. utime += w->utime;
  2891. stime += w->stime;
  2892. gtime += w->gtime;
  2893. cutime += w->cutime;
  2894. cstime += w->cstime;
  2895. cgtime += w->cgtime;
  2896. minflt += w->minflt;
  2897. majflt += w->majflt;
  2898. cminflt += w->cminflt;
  2899. cmajflt += w->cmajflt;
  2900. }
  2901. if(global_utime || global_stime || global_gtime) {
  2902. if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
  2903. // everything we collected fits
  2904. utime_fix_ratio =
  2905. stime_fix_ratio =
  2906. gtime_fix_ratio =
  2907. cutime_fix_ratio =
  2908. cstime_fix_ratio =
  2909. cgtime_fix_ratio = 1.0; //(NETDATA_DOUBLE)(global_utime + global_stime) / (NETDATA_DOUBLE)(utime + cutime + stime + cstime);
  2910. }
  2911. else if((global_utime + global_stime > utime + stime) && (cutime || cstime)) {
  2912. // children resources are too high
  2913. // lower only the children resources
  2914. utime_fix_ratio =
  2915. stime_fix_ratio =
  2916. gtime_fix_ratio = 1.0;
  2917. cutime_fix_ratio =
  2918. cstime_fix_ratio =
  2919. cgtime_fix_ratio = (NETDATA_DOUBLE)((global_utime + global_stime) - (utime + stime)) / (NETDATA_DOUBLE)(cutime + cstime);
  2920. }
  2921. else if(utime || stime) {
  2922. // even running processes are unrealistic
  2923. // zero the children resources
  2924. // lower the running processes resources
  2925. utime_fix_ratio =
  2926. stime_fix_ratio =
  2927. gtime_fix_ratio = (NETDATA_DOUBLE)(global_utime + global_stime) / (NETDATA_DOUBLE)(utime + stime);
  2928. cutime_fix_ratio =
  2929. cstime_fix_ratio =
  2930. cgtime_fix_ratio = 0.0;
  2931. }
  2932. else {
  2933. utime_fix_ratio =
  2934. stime_fix_ratio =
  2935. gtime_fix_ratio =
  2936. cutime_fix_ratio =
  2937. cstime_fix_ratio =
  2938. cgtime_fix_ratio = 0.0;
  2939. }
  2940. }
  2941. else {
  2942. utime_fix_ratio =
  2943. stime_fix_ratio =
  2944. gtime_fix_ratio =
  2945. cutime_fix_ratio =
  2946. cstime_fix_ratio =
  2947. cgtime_fix_ratio = 0.0;
  2948. }
  2949. if(utime_fix_ratio > 1.0) utime_fix_ratio = 1.0;
  2950. if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
  2951. if(stime_fix_ratio > 1.0) stime_fix_ratio = 1.0;
  2952. if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
  2953. if(gtime_fix_ratio > 1.0) gtime_fix_ratio = 1.0;
  2954. if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
  2955. // if(utime_fix_ratio < 0.0) utime_fix_ratio = 0.0;
  2956. // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
  2957. // if(stime_fix_ratio < 0.0) stime_fix_ratio = 0.0;
  2958. // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
  2959. // if(gtime_fix_ratio < 0.0) gtime_fix_ratio = 0.0;
  2960. // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
  2961. // TODO
  2962. // we use cpu time to normalize page faults
  2963. // the problem is that to find the proper max values
  2964. // for page faults we have to parse /proc/vmstat
  2965. // which is quite big to do it again (netdata does it already)
  2966. //
  2967. // a better solution could be to somehow have netdata
  2968. // do this normalization for us
  2969. if(utime || stime || gtime)
  2970. majflt_fix_ratio =
  2971. minflt_fix_ratio = (NETDATA_DOUBLE)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (NETDATA_DOUBLE)(utime + stime + gtime);
  2972. else
  2973. minflt_fix_ratio =
  2974. majflt_fix_ratio = 1.0;
  2975. if(cutime || cstime || cgtime)
  2976. cmajflt_fix_ratio =
  2977. cminflt_fix_ratio = (NETDATA_DOUBLE)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (NETDATA_DOUBLE)(cutime + cstime + cgtime);
  2978. else
  2979. cminflt_fix_ratio =
  2980. cmajflt_fix_ratio = 1.0;
  2981. // the report
  2982. debug_log(
  2983. "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
  2984. "COLLECTED: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " cu=" KERNEL_UINT_FORMAT " cs=" KERNEL_UINT_FORMAT " cg=" KERNEL_UINT_FORMAT " "
  2985. "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
  2986. "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
  2987. "FINALLY: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " cu=" KERNEL_UINT_FORMAT " cs=" KERNEL_UINT_FORMAT " cg=" KERNEL_UINT_FORMAT " "
  2988. , global_utime
  2989. , global_stime
  2990. , global_gtime
  2991. , utime
  2992. , stime
  2993. , gtime
  2994. , cutime
  2995. , cstime
  2996. , cgtime
  2997. , utime + cutime - global_utime
  2998. , stime + cstime - global_stime
  2999. , gtime + cgtime - global_gtime
  3000. , utime_fix_ratio
  3001. , stime_fix_ratio
  3002. , gtime_fix_ratio
  3003. , cutime_fix_ratio
  3004. , cstime_fix_ratio
  3005. , cgtime_fix_ratio
  3006. , (kernel_uint_t)(utime * utime_fix_ratio)
  3007. , (kernel_uint_t)(stime * stime_fix_ratio)
  3008. , (kernel_uint_t)(gtime * gtime_fix_ratio)
  3009. , (kernel_uint_t)(cutime * cutime_fix_ratio)
  3010. , (kernel_uint_t)(cstime * cstime_fix_ratio)
  3011. , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
  3012. );
  3013. }
  3014. static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t dt) {
  3015. struct target *w;
  3016. send_BEGIN(type, "cpu", dt);
  3017. for (w = root; w ; w = w->next) {
  3018. if(unlikely(w->exposed && w->processes))
  3019. send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (kernel_uint_t)(w->stime * stime_fix_ratio) + (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio) + (kernel_uint_t)(w->cstime * cstime_fix_ratio) + (kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
  3020. }
  3021. send_END();
  3022. send_BEGIN(type, "cpu_user", dt);
  3023. for (w = root; w ; w = w->next) {
  3024. if(unlikely(w->exposed && w->processes))
  3025. send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
  3026. }
  3027. send_END();
  3028. send_BEGIN(type, "cpu_system", dt);
  3029. for (w = root; w ; w = w->next) {
  3030. if(unlikely(w->exposed && w->processes))
  3031. send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
  3032. }
  3033. send_END();
  3034. if(show_guest_time) {
  3035. send_BEGIN(type, "cpu_guest", dt);
  3036. for (w = root; w ; w = w->next) {
  3037. if(unlikely(w->exposed && w->processes))
  3038. send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
  3039. }
  3040. send_END();
  3041. }
  3042. #ifndef __FreeBSD__
  3043. send_BEGIN(type, "voluntary_ctxt_switches", dt);
  3044. for (w = root; w ; w = w->next) {
  3045. if(unlikely(w->exposed && w->processes))
  3046. send_SET(w->name, w->status_voluntary_ctxt_switches);
  3047. }
  3048. send_END();
  3049. send_BEGIN(type, "involuntary_ctxt_switches", dt);
  3050. for (w = root; w ; w = w->next) {
  3051. if(unlikely(w->exposed && w->processes))
  3052. send_SET(w->name, w->status_nonvoluntary_ctxt_switches);
  3053. }
  3054. send_END();
  3055. #endif
  3056. send_BEGIN(type, "threads", dt);
  3057. for (w = root; w ; w = w->next) {
  3058. if(unlikely(w->exposed))
  3059. send_SET(w->name, w->num_threads);
  3060. }
  3061. send_END();
  3062. send_BEGIN(type, "processes", dt);
  3063. for (w = root; w ; w = w->next) {
  3064. if(unlikely(w->exposed))
  3065. send_SET(w->name, w->processes);
  3066. }
  3067. send_END();
  3068. #ifndef __FreeBSD__
  3069. send_BEGIN(type, "uptime", dt);
  3070. for (w = root; w ; w = w->next) {
  3071. if(unlikely(w->exposed && w->processes))
  3072. send_SET(w->name, (global_uptime > w->starttime)?(global_uptime - w->starttime):0);
  3073. }
  3074. send_END();
  3075. if (enable_detailed_uptime_charts) {
  3076. send_BEGIN(type, "uptime_min", dt);
  3077. for (w = root; w ; w = w->next) {
  3078. if(unlikely(w->exposed && w->processes))
  3079. send_SET(w->name, w->uptime_min);
  3080. }
  3081. send_END();
  3082. send_BEGIN(type, "uptime_avg", dt);
  3083. for (w = root; w ; w = w->next) {
  3084. if(unlikely(w->exposed && w->processes))
  3085. send_SET(w->name, w->uptime_sum / w->processes);
  3086. }
  3087. send_END();
  3088. send_BEGIN(type, "uptime_max", dt);
  3089. for (w = root; w ; w = w->next) {
  3090. if(unlikely(w->exposed && w->processes))
  3091. send_SET(w->name, w->uptime_max);
  3092. }
  3093. send_END();
  3094. }
  3095. #endif
  3096. send_BEGIN(type, "mem", dt);
  3097. for (w = root; w ; w = w->next) {
  3098. if(unlikely(w->exposed && w->processes))
  3099. send_SET(w->name, (w->status_vmrss > w->status_vmshared)?(w->status_vmrss - w->status_vmshared):0ULL);
  3100. }
  3101. send_END();
  3102. send_BEGIN(type, "rss", dt);
  3103. for (w = root; w ; w = w->next) {
  3104. if(unlikely(w->exposed && w->processes))
  3105. send_SET(w->name, w->status_vmrss);
  3106. }
  3107. send_END();
  3108. send_BEGIN(type, "vmem", dt);
  3109. for (w = root; w ; w = w->next) {
  3110. if(unlikely(w->exposed && w->processes))
  3111. send_SET(w->name, w->status_vmsize);
  3112. }
  3113. send_END();
  3114. #ifndef __FreeBSD__
  3115. send_BEGIN(type, "swap", dt);
  3116. for (w = root; w ; w = w->next) {
  3117. if(unlikely(w->exposed && w->processes))
  3118. send_SET(w->name, w->status_vmswap);
  3119. }
  3120. send_END();
  3121. #endif
  3122. send_BEGIN(type, "minor_faults", dt);
  3123. for (w = root; w ; w = w->next) {
  3124. if(unlikely(w->exposed && w->processes))
  3125. send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
  3126. }
  3127. send_END();
  3128. send_BEGIN(type, "major_faults", dt);
  3129. for (w = root; w ; w = w->next) {
  3130. if(unlikely(w->exposed && w->processes))
  3131. send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
  3132. }
  3133. send_END();
  3134. #ifndef __FreeBSD__
  3135. send_BEGIN(type, "lreads", dt);
  3136. for (w = root; w ; w = w->next) {
  3137. if(unlikely(w->exposed && w->processes))
  3138. send_SET(w->name, w->io_logical_bytes_read);
  3139. }
  3140. send_END();
  3141. send_BEGIN(type, "lwrites", dt);
  3142. for (w = root; w ; w = w->next) {
  3143. if(unlikely(w->exposed && w->processes))
  3144. send_SET(w->name, w->io_logical_bytes_written);
  3145. }
  3146. send_END();
  3147. #endif
  3148. send_BEGIN(type, "preads", dt);
  3149. for (w = root; w ; w = w->next) {
  3150. if(unlikely(w->exposed && w->processes))
  3151. send_SET(w->name, w->io_storage_bytes_read);
  3152. }
  3153. send_END();
  3154. send_BEGIN(type, "pwrites", dt);
  3155. for (w = root; w ; w = w->next) {
  3156. if(unlikely(w->exposed && w->processes))
  3157. send_SET(w->name, w->io_storage_bytes_written);
  3158. }
  3159. send_END();
  3160. if(enable_file_charts) {
  3161. send_BEGIN(type, "fds_open_limit", dt);
  3162. for (w = root; w; w = w->next) {
  3163. if (unlikely(w->exposed && w->processes))
  3164. send_SET(w->name, w->max_open_files_percent * 100.0);
  3165. }
  3166. send_END();
  3167. send_BEGIN(type, "fds_open", dt);
  3168. for (w = root; w; w = w->next) {
  3169. if (unlikely(w->exposed && w->processes))
  3170. send_SET(w->name, pid_openfds_sum(w));
  3171. }
  3172. send_END();
  3173. send_BEGIN(type, "fds_files", dt);
  3174. for (w = root; w; w = w->next) {
  3175. if (unlikely(w->exposed && w->processes))
  3176. send_SET(w->name, w->openfds.files);
  3177. }
  3178. send_END();
  3179. send_BEGIN(type, "fds_sockets", dt);
  3180. for (w = root; w; w = w->next) {
  3181. if (unlikely(w->exposed && w->processes))
  3182. send_SET(w->name, w->openfds.sockets);
  3183. }
  3184. send_END();
  3185. send_BEGIN(type, "fds_pipes", dt);
  3186. for (w = root; w; w = w->next) {
  3187. if (unlikely(w->exposed && w->processes))
  3188. send_SET(w->name, w->openfds.pipes);
  3189. }
  3190. send_END();
  3191. send_BEGIN(type, "fds_inotifies", dt);
  3192. for (w = root; w; w = w->next) {
  3193. if (unlikely(w->exposed && w->processes))
  3194. send_SET(w->name, w->openfds.inotifies);
  3195. }
  3196. send_END();
  3197. send_BEGIN(type, "fds_eventfds", dt);
  3198. for (w = root; w; w = w->next) {
  3199. if (unlikely(w->exposed && w->processes))
  3200. send_SET(w->name, w->openfds.eventfds);
  3201. }
  3202. send_END();
  3203. send_BEGIN(type, "fds_timerfds", dt);
  3204. for (w = root; w; w = w->next) {
  3205. if (unlikely(w->exposed && w->processes))
  3206. send_SET(w->name, w->openfds.timerfds);
  3207. }
  3208. send_END();
  3209. send_BEGIN(type, "fds_signalfds", dt);
  3210. for (w = root; w; w = w->next) {
  3211. if (unlikely(w->exposed && w->processes))
  3212. send_SET(w->name, w->openfds.signalfds);
  3213. }
  3214. send_END();
  3215. send_BEGIN(type, "fds_eventpolls", dt);
  3216. for (w = root; w; w = w->next) {
  3217. if (unlikely(w->exposed && w->processes))
  3218. send_SET(w->name, w->openfds.eventpolls);
  3219. }
  3220. send_END();
  3221. send_BEGIN(type, "fds_other", dt);
  3222. for (w = root; w; w = w->next) {
  3223. if (unlikely(w->exposed && w->processes))
  3224. send_SET(w->name, w->openfds.other);
  3225. }
  3226. send_END();
  3227. }
  3228. }
  3229. // ----------------------------------------------------------------------------
  3230. // generate the charts
  3231. static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
  3232. {
  3233. struct target *w;
  3234. int newly_added = 0;
  3235. for(w = root ; w ; w = w->next) {
  3236. if (w->target) continue;
  3237. if(unlikely(w->processes && (debug_enabled || w->debug_enabled))) {
  3238. struct pid_on_target *pid_on_target;
  3239. fprintf(stderr, "apps.plugin: target '%s' has aggregated %u process%s:", w->name, w->processes, (w->processes == 1)?"":"es");
  3240. for(pid_on_target = w->root_pid; pid_on_target; pid_on_target = pid_on_target->next) {
  3241. fprintf(stderr, " %d", pid_on_target->pid);
  3242. }
  3243. fputc('\n', stderr);
  3244. }
  3245. if (!w->exposed && w->processes) {
  3246. newly_added++;
  3247. w->exposed = 1;
  3248. if (debug_enabled || w->debug_enabled)
  3249. debug_log_int("%s just added - regenerating charts.", w->name);
  3250. }
  3251. }
  3252. // nothing more to show
  3253. if(!newly_added && show_guest_time == show_guest_time_old) return;
  3254. // we have something new to show
  3255. // update the charts
  3256. fprintf(stdout, "CHART %s.cpu '' '%s CPU Time (100%% = 1 core)' 'percentage' cpu %s.cpu stacked 20001 %d\n", type, title, type, update_every);
  3257. for (w = root; w ; w = w->next) {
  3258. if(unlikely(w->exposed))
  3259. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, time_factor * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
  3260. }
  3261. APPS_PLUGIN_FUNCTIONS();
  3262. fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MiB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
  3263. for (w = root; w ; w = w->next) {
  3264. if(unlikely(w->exposed))
  3265. fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, 1L, 1024L);
  3266. }
  3267. APPS_PLUGIN_FUNCTIONS();
  3268. fprintf(stdout, "CHART %s.rss '' '%s Resident Set Size (w/shared)' 'MiB' mem %s.rss stacked 20004 %d\n", type, title, type, update_every);
  3269. for (w = root; w ; w = w->next) {
  3270. if(unlikely(w->exposed))
  3271. fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, 1L, 1024L);
  3272. }
  3273. APPS_PLUGIN_FUNCTIONS();
  3274. fprintf(stdout, "CHART %s.vmem '' '%s Virtual Memory Size' 'MiB' mem %s.vmem stacked 20005 %d\n", type, title, type, update_every);
  3275. for (w = root; w ; w = w->next) {
  3276. if(unlikely(w->exposed))
  3277. fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, 1L, 1024L);
  3278. }
  3279. APPS_PLUGIN_FUNCTIONS();
  3280. fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20006 %d\n", type, title, type, update_every);
  3281. for (w = root; w ; w = w->next) {
  3282. if(unlikely(w->exposed))
  3283. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3284. }
  3285. APPS_PLUGIN_FUNCTIONS();
  3286. fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20007 %d\n", type, title, type, update_every);
  3287. for (w = root; w ; w = w->next) {
  3288. if(unlikely(w->exposed))
  3289. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3290. }
  3291. APPS_PLUGIN_FUNCTIONS();
  3292. #ifndef __FreeBSD__
  3293. fprintf(stdout, "CHART %s.uptime '' '%s Carried Over Uptime' 'seconds' processes %s.uptime line 20008 %d\n", type, title, type, update_every);
  3294. for (w = root; w ; w = w->next) {
  3295. if(unlikely(w->exposed))
  3296. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3297. }
  3298. APPS_PLUGIN_FUNCTIONS();
  3299. if (enable_detailed_uptime_charts) {
  3300. fprintf(stdout, "CHART %s.uptime_min '' '%s Minimum Uptime' 'seconds' processes %s.uptime_min line 20009 %d\n", type, title, type, update_every);
  3301. for (w = root; w ; w = w->next) {
  3302. if(unlikely(w->exposed))
  3303. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3304. }
  3305. APPS_PLUGIN_FUNCTIONS();
  3306. fprintf(stdout, "CHART %s.uptime_avg '' '%s Average Uptime' 'seconds' processes %s.uptime_avg line 20010 %d\n", type, title, type, update_every);
  3307. for (w = root; w ; w = w->next) {
  3308. if(unlikely(w->exposed))
  3309. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3310. }
  3311. APPS_PLUGIN_FUNCTIONS();
  3312. fprintf(stdout, "CHART %s.uptime_max '' '%s Maximum Uptime' 'seconds' processes %s.uptime_max line 20011 %d\n", type, title, type, update_every);
  3313. for (w = root; w ; w = w->next) {
  3314. if(unlikely(w->exposed))
  3315. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3316. }
  3317. APPS_PLUGIN_FUNCTIONS();
  3318. }
  3319. #endif
  3320. fprintf(stdout, "CHART %s.cpu_user '' '%s CPU User Time (100%% = 1 core)' 'percentage' cpu %s.cpu_user stacked 20020 %d\n", type, title, type, update_every);
  3321. for (w = root; w ; w = w->next) {
  3322. if(unlikely(w->exposed))
  3323. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, time_factor * RATES_DETAIL / 100LLU);
  3324. }
  3325. APPS_PLUGIN_FUNCTIONS();
  3326. fprintf(stdout, "CHART %s.cpu_system '' '%s CPU System Time (100%% = 1 core)' 'percentage' cpu %s.cpu_system stacked 20021 %d\n", type, title, type, update_every);
  3327. for (w = root; w ; w = w->next) {
  3328. if(unlikely(w->exposed))
  3329. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, time_factor * RATES_DETAIL / 100LLU);
  3330. }
  3331. APPS_PLUGIN_FUNCTIONS();
  3332. if(show_guest_time) {
  3333. fprintf(stdout, "CHART %s.cpu_guest '' '%s CPU Guest Time (100%% = 1 core)' 'percentage' cpu %s.cpu_guest stacked 20022 %d\n", type, title, type, update_every);
  3334. for (w = root; w; w = w->next) {
  3335. if(unlikely(w->exposed))
  3336. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, time_factor * RATES_DETAIL / 100LLU);
  3337. }
  3338. APPS_PLUGIN_FUNCTIONS();
  3339. }
  3340. #ifndef __FreeBSD__
  3341. fprintf(stdout, "CHART %s.voluntary_ctxt_switches '' '%s Voluntary Context Switches' 'switches/s' cpu %s.voluntary_ctxt_switches stacked 20023 %d\n", type, title, type, update_every);
  3342. for (w = root; w ; w = w->next) {
  3343. if(unlikely(w->exposed))
  3344. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
  3345. }
  3346. APPS_PLUGIN_FUNCTIONS();
  3347. fprintf(stdout, "CHART %s.involuntary_ctxt_switches '' '%s Involuntary Context Switches' 'switches/s' cpu %s.involuntary_ctxt_switches stacked 20024 %d\n", type, title, type, update_every);
  3348. for (w = root; w ; w = w->next) {
  3349. if(unlikely(w->exposed))
  3350. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
  3351. }
  3352. APPS_PLUGIN_FUNCTIONS();
  3353. #endif
  3354. #ifndef __FreeBSD__
  3355. fprintf(stdout, "CHART %s.swap '' '%s Swap Memory' 'MiB' swap %s.swap stacked 20011 %d\n", type, title, type, update_every);
  3356. for (w = root; w ; w = w->next) {
  3357. if(unlikely(w->exposed))
  3358. fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, 1L, 1024L);
  3359. }
  3360. APPS_PLUGIN_FUNCTIONS();
  3361. #endif
  3362. fprintf(stdout, "CHART %s.major_faults '' '%s Major Page Faults (swap read)' 'page faults/s' swap %s.major_faults stacked 20012 %d\n", type, title, type, update_every);
  3363. for (w = root; w ; w = w->next) {
  3364. if(unlikely(w->exposed))
  3365. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
  3366. }
  3367. APPS_PLUGIN_FUNCTIONS();
  3368. fprintf(stdout, "CHART %s.minor_faults '' '%s Minor Page Faults' 'page faults/s' mem %s.minor_faults stacked 20011 %d\n", type, title, type, update_every);
  3369. for (w = root; w ; w = w->next) {
  3370. if(unlikely(w->exposed))
  3371. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
  3372. }
  3373. APPS_PLUGIN_FUNCTIONS();
  3374. #ifdef __FreeBSD__
  3375. // FIXME: same metric name as in Linux but different units.
  3376. fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'blocks/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
  3377. for (w = root; w ; w = w->next) {
  3378. if(unlikely(w->exposed))
  3379. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
  3380. }
  3381. APPS_PLUGIN_FUNCTIONS();
  3382. fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'blocks/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
  3383. for (w = root; w ; w = w->next) {
  3384. if(unlikely(w->exposed))
  3385. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
  3386. }
  3387. APPS_PLUGIN_FUNCTIONS();
  3388. #else
  3389. fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'KiB/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
  3390. for (w = root; w ; w = w->next) {
  3391. if(unlikely(w->exposed))
  3392. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
  3393. }
  3394. APPS_PLUGIN_FUNCTIONS();
  3395. fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'KiB/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
  3396. for (w = root; w ; w = w->next) {
  3397. if(unlikely(w->exposed))
  3398. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
  3399. }
  3400. APPS_PLUGIN_FUNCTIONS();
  3401. fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'KiB/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
  3402. for (w = root; w ; w = w->next) {
  3403. if(unlikely(w->exposed))
  3404. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
  3405. }
  3406. APPS_PLUGIN_FUNCTIONS();
  3407. fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'KiB/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
  3408. for (w = root; w ; w = w->next) {
  3409. if(unlikely(w->exposed))
  3410. fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
  3411. }
  3412. APPS_PLUGIN_FUNCTIONS();
  3413. #endif
  3414. if(enable_file_charts) {
  3415. fprintf(stdout, "CHART %s.fds_open_limit '' '%s Open File Descriptors Limit' '%%' fds %s.fds_open_limit line 20050 %d\n", type,
  3416. title, type, update_every);
  3417. for (w = root; w; w = w->next) {
  3418. if (unlikely(w->exposed))
  3419. fprintf(stdout, "DIMENSION %s '' absolute 1 100\n", w->name);
  3420. }
  3421. APPS_PLUGIN_FUNCTIONS();
  3422. fprintf(stdout, "CHART %s.fds_open '' '%s Open File Descriptors' 'fds' fds %s.fds_open stacked 20051 %d\n", type,
  3423. title, type, update_every);
  3424. for (w = root; w; w = w->next) {
  3425. if (unlikely(w->exposed))
  3426. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3427. }
  3428. APPS_PLUGIN_FUNCTIONS();
  3429. fprintf(stdout, "CHART %s.fds_files '' '%s Open Files' 'fds' fds %s.fds_files stacked 20052 %d\n", type,
  3430. title, type, update_every);
  3431. for (w = root; w; w = w->next) {
  3432. if (unlikely(w->exposed))
  3433. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3434. }
  3435. APPS_PLUGIN_FUNCTIONS();
  3436. fprintf(stdout, "CHART %s.fds_sockets '' '%s Open Sockets' 'fds' fds %s.fds_sockets stacked 20053 %d\n",
  3437. type, title, type, update_every);
  3438. for (w = root; w; w = w->next) {
  3439. if (unlikely(w->exposed))
  3440. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3441. }
  3442. APPS_PLUGIN_FUNCTIONS();
  3443. fprintf(stdout, "CHART %s.fds_pipes '' '%s Pipes' 'fds' fds %s.fds_pipes stacked 20054 %d\n", type,
  3444. title, type, update_every);
  3445. for (w = root; w; w = w->next) {
  3446. if (unlikely(w->exposed))
  3447. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3448. }
  3449. APPS_PLUGIN_FUNCTIONS();
  3450. fprintf(stdout, "CHART %s.fds_inotifies '' '%s iNotify File Descriptors' 'fds' fds %s.fds_inotifies stacked 20055 %d\n", type,
  3451. title, type, update_every);
  3452. for (w = root; w; w = w->next) {
  3453. if (unlikely(w->exposed))
  3454. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3455. }
  3456. APPS_PLUGIN_FUNCTIONS();
  3457. fprintf(stdout, "CHART %s.fds_eventfds '' '%s Event File Descriptors' 'fds' fds %s.fds_eventfds stacked 20056 %d\n", type,
  3458. title, type, update_every);
  3459. for (w = root; w; w = w->next) {
  3460. if (unlikely(w->exposed))
  3461. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3462. }
  3463. APPS_PLUGIN_FUNCTIONS();
  3464. fprintf(stdout, "CHART %s.fds_timerfds '' '%s Timer File Descriptors' 'fds' fds %s.fds_timerfds stacked 20057 %d\n", type,
  3465. title, type, update_every);
  3466. for (w = root; w; w = w->next) {
  3467. if (unlikely(w->exposed))
  3468. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3469. }
  3470. APPS_PLUGIN_FUNCTIONS();
  3471. fprintf(stdout, "CHART %s.fds_signalfds '' '%s Signal File Descriptors' 'fds' fds %s.fds_signalfds stacked 20058 %d\n", type,
  3472. title, type, update_every);
  3473. for (w = root; w; w = w->next) {
  3474. if (unlikely(w->exposed))
  3475. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3476. }
  3477. APPS_PLUGIN_FUNCTIONS();
  3478. fprintf(stdout, "CHART %s.fds_eventpolls '' '%s Event Poll File Descriptors' 'fds' fds %s.fds_eventpolls stacked 20059 %d\n", type,
  3479. title, type, update_every);
  3480. for (w = root; w; w = w->next) {
  3481. if (unlikely(w->exposed))
  3482. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3483. }
  3484. APPS_PLUGIN_FUNCTIONS();
  3485. fprintf(stdout, "CHART %s.fds_other '' '%s Other File Descriptors' 'fds' fds %s.fds_other stacked 20060 %d\n", type,
  3486. title, type, update_every);
  3487. for (w = root; w; w = w->next) {
  3488. if (unlikely(w->exposed))
  3489. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
  3490. }
  3491. APPS_PLUGIN_FUNCTIONS();
  3492. }
  3493. }
  3494. #ifndef __FreeBSD__
  3495. static void send_proc_states_count(usec_t dt)
  3496. {
  3497. static bool chart_added = false;
  3498. // create chart for count of processes in different states
  3499. if (!chart_added) {
  3500. fprintf(
  3501. stdout,
  3502. "CHART system.processes_state '' 'System Processes State' 'processes' processes system.processes_state line %d %d\n",
  3503. NETDATA_CHART_PRIO_SYSTEM_PROCESS_STATES,
  3504. update_every);
  3505. for (proc_state i = PROC_STATUS_RUNNING; i < PROC_STATUS_END; i++) {
  3506. fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", proc_states[i]);
  3507. }
  3508. chart_added = true;
  3509. }
  3510. // send process state count
  3511. send_BEGIN("system", "processes_state", dt);
  3512. for (proc_state i = PROC_STATUS_RUNNING; i < PROC_STATUS_END; i++) {
  3513. send_SET(proc_states[i], proc_state_count[i]);
  3514. }
  3515. send_END();
  3516. }
  3517. #endif
  3518. // ----------------------------------------------------------------------------
  3519. // parse command line arguments
  3520. int check_proc_1_io() {
  3521. int ret = 0;
  3522. procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
  3523. if(!ff) goto cleanup;
  3524. ff = procfile_readall(ff);
  3525. if(!ff) goto cleanup;
  3526. ret = 1;
  3527. cleanup:
  3528. procfile_close(ff);
  3529. return ret;
  3530. }
  3531. static void parse_args(int argc, char **argv)
  3532. {
  3533. int i, freq = 0;
  3534. for(i = 1; i < argc; i++) {
  3535. if(!freq) {
  3536. int n = (int)str2l(argv[i]);
  3537. if(n > 0) {
  3538. freq = n;
  3539. continue;
  3540. }
  3541. }
  3542. if(strcmp("version", argv[i]) == 0 || strcmp("-version", argv[i]) == 0 || strcmp("--version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0 || strcmp("-V", argv[i]) == 0) {
  3543. printf("apps.plugin %s\n", VERSION);
  3544. exit(0);
  3545. }
  3546. if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
  3547. if(!check_proc_1_io()) {
  3548. perror("Tried to read /proc/1/io and it failed");
  3549. exit(1);
  3550. }
  3551. printf("OK\n");
  3552. exit(0);
  3553. }
  3554. if(strcmp("debug", argv[i]) == 0) {
  3555. debug_enabled = 1;
  3556. #ifndef NETDATA_INTERNAL_CHECKS
  3557. fprintf(stderr, "apps.plugin has been compiled without debugging\n");
  3558. #endif
  3559. continue;
  3560. }
  3561. #ifndef __FreeBSD__
  3562. if(strcmp("fds-cache-secs", argv[i]) == 0) {
  3563. if(argc <= i + 1) {
  3564. fprintf(stderr, "Parameter 'fds-cache-secs' requires a number as argument.\n");
  3565. exit(1);
  3566. }
  3567. i++;
  3568. max_fds_cache_seconds = str2i(argv[i]);
  3569. if(max_fds_cache_seconds < 0) max_fds_cache_seconds = 0;
  3570. continue;
  3571. }
  3572. #endif
  3573. if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
  3574. include_exited_childs = 0;
  3575. continue;
  3576. }
  3577. if(strcmp("with-childs", argv[i]) == 0) {
  3578. include_exited_childs = 1;
  3579. continue;
  3580. }
  3581. if(strcmp("with-guest", argv[i]) == 0) {
  3582. enable_guest_charts = 1;
  3583. continue;
  3584. }
  3585. if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
  3586. enable_guest_charts = 0;
  3587. continue;
  3588. }
  3589. if(strcmp("with-files", argv[i]) == 0) {
  3590. enable_file_charts = 1;
  3591. continue;
  3592. }
  3593. if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
  3594. enable_file_charts = 0;
  3595. continue;
  3596. }
  3597. if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
  3598. enable_users_charts = 0;
  3599. continue;
  3600. }
  3601. if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
  3602. enable_groups_charts = 0;
  3603. continue;
  3604. }
  3605. if(strcmp("with-detailed-uptime", argv[i]) == 0) {
  3606. enable_detailed_uptime_charts = 1;
  3607. continue;
  3608. }
  3609. if(strcmp("with-function-cmdline", argv[i]) == 0) {
  3610. enable_function_cmdline = 1;
  3611. continue;
  3612. }
  3613. if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
  3614. fprintf(stderr,
  3615. "\n"
  3616. " netdata apps.plugin %s\n"
  3617. " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
  3618. " Released under GNU General Public License v3 or later.\n"
  3619. " All rights reserved.\n"
  3620. "\n"
  3621. " This program is a data collector plugin for netdata.\n"
  3622. "\n"
  3623. " Available command line options:\n"
  3624. "\n"
  3625. " SECONDS set the data collection frequency\n"
  3626. "\n"
  3627. " debug enable debugging (lot of output)\n"
  3628. "\n"
  3629. " with-function-cmdline enable reporting the complete command line for processes\n"
  3630. " it includes the command and passed arguments\n"
  3631. " it may include sensitive data such as passwords and tokens\n"
  3632. " enabling this could be a security risk\n"
  3633. "\n"
  3634. " with-childs\n"
  3635. " without-childs enable / disable aggregating exited\n"
  3636. " children resources into parents\n"
  3637. " (default is enabled)\n"
  3638. "\n"
  3639. " with-guest\n"
  3640. " without-guest enable / disable reporting guest charts\n"
  3641. " (default is disabled)\n"
  3642. "\n"
  3643. " with-files\n"
  3644. " without-files enable / disable reporting files, sockets, pipes\n"
  3645. " (default is enabled)\n"
  3646. "\n"
  3647. " without-users disable reporting per user charts\n"
  3648. "\n"
  3649. " without-groups disable reporting per user group charts\n"
  3650. "\n"
  3651. " with-detailed-uptime enable reporting min/avg/max uptime charts\n"
  3652. "\n"
  3653. #ifndef __FreeBSD__
  3654. " fds-cache-secs N cache the files of processed for N seconds\n"
  3655. " caching is adaptive per file (when a file\n"
  3656. " is found, it starts at 0 and while the file\n"
  3657. " remains open, it is incremented up to the\n"
  3658. " max given)\n"
  3659. " (default is %d seconds)\n"
  3660. "\n"
  3661. #endif
  3662. " version or -v or -V print program version and exit\n"
  3663. "\n"
  3664. , VERSION
  3665. #ifndef __FreeBSD__
  3666. , max_fds_cache_seconds
  3667. #endif
  3668. );
  3669. exit(1);
  3670. }
  3671. netdata_log_error("Cannot understand option %s", argv[i]);
  3672. exit(1);
  3673. }
  3674. if(freq > 0) update_every = freq;
  3675. if(read_apps_groups_conf(user_config_dir, "groups")) {
  3676. netdata_log_info("Cannot read process groups configuration file '%s/apps_groups.conf'. Will try '%s/apps_groups.conf'", user_config_dir, stock_config_dir);
  3677. if(read_apps_groups_conf(stock_config_dir, "groups")) {
  3678. netdata_log_error("Cannot read process groups '%s/apps_groups.conf'. There are no internal defaults. Failing.", stock_config_dir);
  3679. exit(1);
  3680. }
  3681. else
  3682. netdata_log_info("Loaded config file '%s/apps_groups.conf'", stock_config_dir);
  3683. }
  3684. else
  3685. netdata_log_info("Loaded config file '%s/apps_groups.conf'", user_config_dir);
  3686. }
  3687. static int am_i_running_as_root() {
  3688. uid_t uid = getuid(), euid = geteuid();
  3689. if(uid == 0 || euid == 0) {
  3690. if(debug_enabled) netdata_log_info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
  3691. return 1;
  3692. }
  3693. if(debug_enabled) netdata_log_info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
  3694. return 0;
  3695. }
  3696. #ifdef HAVE_CAPABILITY
  3697. static int check_capabilities() {
  3698. cap_t caps = cap_get_proc();
  3699. if(!caps) {
  3700. netdata_log_error("Cannot get current capabilities.");
  3701. return 0;
  3702. }
  3703. else if(debug_enabled)
  3704. netdata_log_info("Received my capabilities from the system.");
  3705. int ret = 1;
  3706. cap_flag_value_t cfv = CAP_CLEAR;
  3707. if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
  3708. netdata_log_error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
  3709. ret = 0;
  3710. }
  3711. else {
  3712. if(cfv != CAP_SET) {
  3713. netdata_log_error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
  3714. ret = 0;
  3715. }
  3716. else if(debug_enabled)
  3717. netdata_log_info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
  3718. }
  3719. cfv = CAP_CLEAR;
  3720. if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
  3721. netdata_log_error("Cannot find if CAP_SYS_PTRACE is effective.");
  3722. ret = 0;
  3723. }
  3724. else {
  3725. if(cfv != CAP_SET) {
  3726. netdata_log_error("apps.plugin should run with CAP_SYS_PTRACE.");
  3727. ret = 0;
  3728. }
  3729. else if(debug_enabled)
  3730. netdata_log_info("apps.plugin runs with CAP_SYS_PTRACE.");
  3731. }
  3732. cap_free(caps);
  3733. return ret;
  3734. }
  3735. #else
  3736. static int check_capabilities() {
  3737. return 0;
  3738. }
  3739. #endif
  3740. static netdata_mutex_t mutex = NETDATA_MUTEX_INITIALIZER;
  3741. #define PROCESS_FILTER_CATEGORY "category:"
  3742. #define PROCESS_FILTER_USER "user:"
  3743. #define PROCESS_FILTER_GROUP "group:"
  3744. #define PROCESS_FILTER_PROCESS "process:"
  3745. #define PROCESS_FILTER_PID "pid:"
  3746. #define PROCESS_FILTER_UID "uid:"
  3747. #define PROCESS_FILTER_GID "gid:"
  3748. static struct target *find_target_by_name(struct target *base, const char *name) {
  3749. struct target *t;
  3750. for(t = base; t ; t = t->next) {
  3751. if (strcmp(t->name, name) == 0)
  3752. return t;
  3753. }
  3754. return NULL;
  3755. }
  3756. static kernel_uint_t MemTotal = 0;
  3757. static void get_MemTotal(void) {
  3758. #ifdef __FreeBSD__
  3759. // TODO - fix this for FreeBSD
  3760. return;
  3761. #else
  3762. char filename[FILENAME_MAX + 1];
  3763. snprintfz(filename, FILENAME_MAX, "%s/proc/meminfo", netdata_configured_host_prefix);
  3764. procfile *ff = procfile_open(filename, ": \t", PROCFILE_FLAG_DEFAULT);
  3765. if(!ff)
  3766. return;
  3767. ff = procfile_readall(ff);
  3768. if(!ff)
  3769. return;
  3770. size_t line, lines = procfile_lines(ff);
  3771. for(line = 0; line < lines ;line++) {
  3772. size_t words = procfile_linewords(ff, line);
  3773. if(words == 3 && strcmp(procfile_lineword(ff, line, 0), "MemTotal") == 0 && strcmp(procfile_lineword(ff, line, 2), "kB") == 0) {
  3774. kernel_uint_t n = str2ull(procfile_lineword(ff, line, 1), NULL);
  3775. if(n) MemTotal = n;
  3776. break;
  3777. }
  3778. }
  3779. procfile_close(ff);
  3780. #endif
  3781. }
  3782. static void apps_plugin_function_processes_help(const char *transaction) {
  3783. pluginsd_function_result_begin_to_stdout(transaction, HTTP_RESP_OK, "text/plain", now_realtime_sec() + 3600);
  3784. fprintf(stdout, "%s",
  3785. "apps.plugin / processes\n"
  3786. "\n"
  3787. "Function `processes` presents all the currently running processes of the system.\n"
  3788. "\n"
  3789. "The following filters are supported:\n"
  3790. "\n"
  3791. " category:NAME\n"
  3792. " Shows only processes that are assigned the category `NAME` in apps_groups.conf\n"
  3793. "\n"
  3794. " user:NAME\n"
  3795. " Shows only processes that are running as user name `NAME`.\n"
  3796. "\n"
  3797. " group:NAME\n"
  3798. " Shows only processes that are running as group name `NAME`.\n"
  3799. "\n"
  3800. " process:NAME\n"
  3801. " Shows only processes that their Command is `NAME` or their parent's Command is `NAME`.\n"
  3802. "\n"
  3803. " pid:NUMBER\n"
  3804. " Shows only processes that their PID is `NUMBER` or their parent's PID is `NUMBER`\n"
  3805. "\n"
  3806. " uid:NUMBER\n"
  3807. " Shows only processes that their UID is `NUMBER`\n"
  3808. "\n"
  3809. " gid:NUMBER\n"
  3810. " Shows only processes that their GID is `NUMBER`\n"
  3811. "\n"
  3812. "Filters can be combined. Each filter can be given only one time.\n"
  3813. );
  3814. pluginsd_function_result_end_to_stdout();
  3815. }
  3816. #define add_value_field_llu_with_max(wb, key, value) do { \
  3817. unsigned long long _tmp = (value); \
  3818. key ## _max = (rows == 0) ? (_tmp) : MAX(key ## _max, _tmp); \
  3819. buffer_json_add_array_item_uint64(wb, _tmp); \
  3820. } while(0)
  3821. #define add_value_field_ndd_with_max(wb, key, value) do { \
  3822. NETDATA_DOUBLE _tmp = (value); \
  3823. key ## _max = (rows == 0) ? (_tmp) : MAX(key ## _max, _tmp); \
  3824. buffer_json_add_array_item_double(wb, _tmp); \
  3825. } while(0)
  3826. static void function_processes(const char *transaction, char *function __maybe_unused, char *line_buffer __maybe_unused, int line_max __maybe_unused, int timeout __maybe_unused) {
  3827. struct pid_stat *p;
  3828. char *words[PLUGINSD_MAX_WORDS] = { NULL };
  3829. size_t num_words = quoted_strings_splitter_pluginsd(function, words, PLUGINSD_MAX_WORDS);
  3830. struct target *category = NULL, *user = NULL, *group = NULL;
  3831. const char *process_name = NULL;
  3832. pid_t pid = 0;
  3833. uid_t uid = 0;
  3834. gid_t gid = 0;
  3835. bool filter_pid = false, filter_uid = false, filter_gid = false;
  3836. for(int i = 1; i < PLUGINSD_MAX_WORDS ;i++) {
  3837. const char *keyword = get_word(words, num_words, i);
  3838. if(!keyword) break;
  3839. if(!category && strncmp(keyword, PROCESS_FILTER_CATEGORY, strlen(PROCESS_FILTER_CATEGORY)) == 0) {
  3840. category = find_target_by_name(apps_groups_root_target, &keyword[strlen(PROCESS_FILTER_CATEGORY)]);
  3841. if(!category) {
  3842. pluginsd_function_json_error(transaction, HTTP_RESP_BAD_REQUEST, "No category with that name found.");
  3843. return;
  3844. }
  3845. }
  3846. else if(!user && strncmp(keyword, PROCESS_FILTER_USER, strlen(PROCESS_FILTER_USER)) == 0) {
  3847. user = find_target_by_name(users_root_target, &keyword[strlen(PROCESS_FILTER_USER)]);
  3848. if(!user) {
  3849. pluginsd_function_json_error(transaction, HTTP_RESP_BAD_REQUEST, "No user with that name found.");
  3850. return;
  3851. }
  3852. }
  3853. else if(strncmp(keyword, PROCESS_FILTER_GROUP, strlen(PROCESS_FILTER_GROUP)) == 0) {
  3854. group = find_target_by_name(groups_root_target, &keyword[strlen(PROCESS_FILTER_GROUP)]);
  3855. if(!group) {
  3856. pluginsd_function_json_error(transaction, HTTP_RESP_BAD_REQUEST, "No group with that name found.");
  3857. return;
  3858. }
  3859. }
  3860. else if(!process_name && strncmp(keyword, PROCESS_FILTER_PROCESS, strlen(PROCESS_FILTER_PROCESS)) == 0) {
  3861. process_name = &keyword[strlen(PROCESS_FILTER_PROCESS)];
  3862. }
  3863. else if(!pid && strncmp(keyword, PROCESS_FILTER_PID, strlen(PROCESS_FILTER_PID)) == 0) {
  3864. pid = str2i(&keyword[strlen(PROCESS_FILTER_PID)]);
  3865. filter_pid = true;
  3866. }
  3867. else if(!uid && strncmp(keyword, PROCESS_FILTER_UID, strlen(PROCESS_FILTER_UID)) == 0) {
  3868. uid = str2i(&keyword[strlen(PROCESS_FILTER_UID)]);
  3869. filter_uid = true;
  3870. }
  3871. else if(!gid && strncmp(keyword, PROCESS_FILTER_GID, strlen(PROCESS_FILTER_GID)) == 0) {
  3872. gid = str2i(&keyword[strlen(PROCESS_FILTER_GID)]);
  3873. filter_gid = true;
  3874. }
  3875. else if(strcmp(keyword, "help") == 0) {
  3876. apps_plugin_function_processes_help(transaction);
  3877. return;
  3878. }
  3879. else {
  3880. char msg[PLUGINSD_LINE_MAX];
  3881. snprintfz(msg, PLUGINSD_LINE_MAX, "Invalid parameter '%s'", keyword);
  3882. pluginsd_function_json_error(transaction, HTTP_RESP_BAD_REQUEST, msg);
  3883. return;
  3884. }
  3885. }
  3886. time_t expires = now_realtime_sec() + update_every;
  3887. pluginsd_function_result_begin_to_stdout(transaction, HTTP_RESP_OK, "application/json", expires);
  3888. unsigned int cpu_divisor = time_factor * RATES_DETAIL / 100;
  3889. unsigned int memory_divisor = 1024;
  3890. unsigned int io_divisor = 1024 * RATES_DETAIL;
  3891. BUFFER *wb = buffer_create(PLUGINSD_LINE_MAX, NULL);
  3892. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_NEWLINE_ON_ARRAY_ITEMS);
  3893. buffer_json_member_add_uint64(wb, "status", HTTP_RESP_OK);
  3894. buffer_json_member_add_string(wb, "type", "table");
  3895. buffer_json_member_add_time_t(wb, "update_every", update_every);
  3896. buffer_json_member_add_string(wb, "help", APPS_PLUGIN_PROCESSES_FUNCTION_DESCRIPTION);
  3897. buffer_json_member_add_array(wb, "data");
  3898. NETDATA_DOUBLE
  3899. UserCPU_max = 0.0
  3900. , SysCPU_max = 0.0
  3901. , GuestCPU_max = 0.0
  3902. , CUserCPU_max = 0.0
  3903. , CSysCPU_max = 0.0
  3904. , CGuestCPU_max = 0.0
  3905. , CPU_max = 0.0
  3906. , VMSize_max = 0.0
  3907. , RSS_max = 0.0
  3908. , Shared_max = 0.0
  3909. , Swap_max = 0.0
  3910. , Memory_max = 0.0
  3911. , FDsLimitPercent_max = 0.0
  3912. ;
  3913. unsigned long long
  3914. Processes_max = 0
  3915. , Threads_max = 0
  3916. , VoluntaryCtxtSwitches_max = 0
  3917. , NonVoluntaryCtxtSwitches_max = 0
  3918. , Uptime_max = 0
  3919. , MinFlt_max = 0
  3920. , CMinFlt_max = 0
  3921. , TMinFlt_max = 0
  3922. , MajFlt_max = 0
  3923. , CMajFlt_max = 0
  3924. , TMajFlt_max = 0
  3925. , PReads_max = 0
  3926. , PWrites_max = 0
  3927. , RCalls_max = 0
  3928. , WCalls_max = 0
  3929. , Files_max = 0
  3930. , Pipes_max = 0
  3931. , Sockets_max = 0
  3932. , iNotiFDs_max = 0
  3933. , EventFDs_max = 0
  3934. , TimerFDs_max = 0
  3935. , SigFDs_max = 0
  3936. , EvPollFDs_max = 0
  3937. , OtherFDs_max = 0
  3938. , FDs_max = 0
  3939. ;
  3940. #ifndef __FreeBSD__
  3941. unsigned long long
  3942. LReads_max = 0
  3943. , LWrites_max = 0
  3944. ;
  3945. #endif
  3946. int rows= 0;
  3947. for(p = root_of_pids; p ; p = p->next) {
  3948. if(!p->updated)
  3949. continue;
  3950. if(category && p->target != category)
  3951. continue;
  3952. if(user && p->user_target != user)
  3953. continue;
  3954. if(group && p->group_target != group)
  3955. continue;
  3956. if(process_name && ((strcmp(p->comm, process_name) != 0 && !p->parent) || (p->parent && strcmp(p->comm, process_name) != 0 && strcmp(p->parent->comm, process_name) != 0)))
  3957. continue;
  3958. if(filter_pid && p->pid != pid && p->ppid != pid)
  3959. continue;
  3960. if(filter_uid && p->uid != uid)
  3961. continue;
  3962. if(filter_gid && p->gid != gid)
  3963. continue;
  3964. rows++;
  3965. buffer_json_add_array_item_array(wb); // for each pid
  3966. // IMPORTANT!
  3967. // THE ORDER SHOULD BE THE SAME WITH THE FIELDS!
  3968. // pid
  3969. buffer_json_add_array_item_uint64(wb, p->pid);
  3970. // cmd
  3971. buffer_json_add_array_item_string(wb, p->comm);
  3972. // cmdline
  3973. if (enable_function_cmdline) {
  3974. buffer_json_add_array_item_string(wb, (p->cmdline && *p->cmdline) ? p->cmdline : p->comm);
  3975. }
  3976. // ppid
  3977. buffer_json_add_array_item_uint64(wb, p->ppid);
  3978. // category
  3979. buffer_json_add_array_item_string(wb, p->target ? p->target->name : "-");
  3980. // user
  3981. buffer_json_add_array_item_string(wb, p->user_target ? p->user_target->name : "-");
  3982. // uid
  3983. buffer_json_add_array_item_uint64(wb, p->uid);
  3984. // group
  3985. buffer_json_add_array_item_string(wb, p->group_target ? p->group_target->name : "-");
  3986. // gid
  3987. buffer_json_add_array_item_uint64(wb, p->gid);
  3988. // CPU utilization %
  3989. add_value_field_ndd_with_max(wb, CPU, (NETDATA_DOUBLE)(p->utime + p->stime + p->gtime + p->cutime + p->cstime + p->cgtime) / cpu_divisor);
  3990. add_value_field_ndd_with_max(wb, UserCPU, (NETDATA_DOUBLE)(p->utime) / cpu_divisor);
  3991. add_value_field_ndd_with_max(wb, SysCPU, (NETDATA_DOUBLE)(p->stime) / cpu_divisor);
  3992. add_value_field_ndd_with_max(wb, GuestCPU, (NETDATA_DOUBLE)(p->gtime) / cpu_divisor);
  3993. add_value_field_ndd_with_max(wb, CUserCPU, (NETDATA_DOUBLE)(p->cutime) / cpu_divisor);
  3994. add_value_field_ndd_with_max(wb, CSysCPU, (NETDATA_DOUBLE)(p->cstime) / cpu_divisor);
  3995. add_value_field_ndd_with_max(wb, CGuestCPU, (NETDATA_DOUBLE)(p->cgtime) / cpu_divisor);
  3996. add_value_field_llu_with_max(wb, VoluntaryCtxtSwitches, p->status_voluntary_ctxt_switches / RATES_DETAIL);
  3997. add_value_field_llu_with_max(wb, NonVoluntaryCtxtSwitches, p->status_nonvoluntary_ctxt_switches / RATES_DETAIL);
  3998. // memory MiB
  3999. if(MemTotal)
  4000. add_value_field_ndd_with_max(wb, Memory, (NETDATA_DOUBLE)p->status_vmrss * 100.0 / (NETDATA_DOUBLE)MemTotal);
  4001. add_value_field_ndd_with_max(wb, RSS, (NETDATA_DOUBLE)p->status_vmrss / memory_divisor);
  4002. add_value_field_ndd_with_max(wb, Shared, (NETDATA_DOUBLE)p->status_vmshared / memory_divisor);
  4003. add_value_field_ndd_with_max(wb, VMSize, (NETDATA_DOUBLE)p->status_vmsize / memory_divisor);
  4004. add_value_field_ndd_with_max(wb, Swap, (NETDATA_DOUBLE)p->status_vmswap / memory_divisor);
  4005. // Physical I/O
  4006. add_value_field_llu_with_max(wb, PReads, p->io_storage_bytes_read / io_divisor);
  4007. add_value_field_llu_with_max(wb, PWrites, p->io_storage_bytes_written / io_divisor);
  4008. // Logical I/O
  4009. #ifndef __FreeBSD__
  4010. add_value_field_llu_with_max(wb, LReads, p->io_logical_bytes_read / io_divisor);
  4011. add_value_field_llu_with_max(wb, LWrites, p->io_logical_bytes_written / io_divisor);
  4012. #endif
  4013. // I/O calls
  4014. add_value_field_llu_with_max(wb, RCalls, p->io_read_calls / RATES_DETAIL);
  4015. add_value_field_llu_with_max(wb, WCalls, p->io_write_calls / RATES_DETAIL);
  4016. // minor page faults
  4017. add_value_field_llu_with_max(wb, MinFlt, p->minflt / RATES_DETAIL);
  4018. add_value_field_llu_with_max(wb, CMinFlt, p->cminflt / RATES_DETAIL);
  4019. add_value_field_llu_with_max(wb, TMinFlt, (p->minflt + p->cminflt) / RATES_DETAIL);
  4020. // major page faults
  4021. add_value_field_llu_with_max(wb, MajFlt, p->majflt / RATES_DETAIL);
  4022. add_value_field_llu_with_max(wb, CMajFlt, p->cmajflt / RATES_DETAIL);
  4023. add_value_field_llu_with_max(wb, TMajFlt, (p->majflt + p->cmajflt) / RATES_DETAIL);
  4024. // open file descriptors
  4025. add_value_field_ndd_with_max(wb, FDsLimitPercent, p->openfds_limits_percent);
  4026. add_value_field_llu_with_max(wb, FDs, pid_openfds_sum(p));
  4027. add_value_field_llu_with_max(wb, Files, p->openfds.files);
  4028. add_value_field_llu_with_max(wb, Pipes, p->openfds.pipes);
  4029. add_value_field_llu_with_max(wb, Sockets, p->openfds.sockets);
  4030. add_value_field_llu_with_max(wb, iNotiFDs, p->openfds.inotifies);
  4031. add_value_field_llu_with_max(wb, EventFDs, p->openfds.eventfds);
  4032. add_value_field_llu_with_max(wb, TimerFDs, p->openfds.timerfds);
  4033. add_value_field_llu_with_max(wb, SigFDs, p->openfds.signalfds);
  4034. add_value_field_llu_with_max(wb, EvPollFDs, p->openfds.eventpolls);
  4035. add_value_field_llu_with_max(wb, OtherFDs, p->openfds.other);
  4036. // processes, threads, uptime
  4037. add_value_field_llu_with_max(wb, Processes, p->children_count);
  4038. add_value_field_llu_with_max(wb, Threads, p->num_threads);
  4039. add_value_field_llu_with_max(wb, Uptime, p->uptime);
  4040. buffer_json_array_close(wb); // for each pid
  4041. }
  4042. buffer_json_array_close(wb); // data
  4043. buffer_json_member_add_object(wb, "columns");
  4044. {
  4045. int field_id = 0;
  4046. // IMPORTANT!
  4047. // THE ORDER SHOULD BE THE SAME WITH THE VALUES!
  4048. // wb, key, name, visible, type, visualization, transform, decimal_points, units, max, sort, sortable, sticky, unique_key, pointer_to, summary, range
  4049. buffer_rrdf_table_add_field(wb, field_id++, "PID", "Process ID", RRDF_FIELD_TYPE_INTEGER,
  4050. RRDF_FIELD_VISUAL_VALUE, RRDF_FIELD_TRANSFORM_NUMBER, 0, NULL, NAN,
  4051. RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4052. RRDF_FIELD_FILTER_MULTISELECT,
  4053. RRDF_FIELD_OPTS_VISIBLE | RRDF_FIELD_OPTS_STICKY |
  4054. RRDF_FIELD_OPTS_UNIQUE_KEY, NULL);
  4055. buffer_rrdf_table_add_field(wb, field_id++, "Cmd", "Process Name", RRDF_FIELD_TYPE_STRING,
  4056. RRDF_FIELD_VISUAL_VALUE, RRDF_FIELD_TRANSFORM_NONE, 0, NULL, NAN,
  4057. RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4058. RRDF_FIELD_FILTER_MULTISELECT,
  4059. RRDF_FIELD_OPTS_VISIBLE | RRDF_FIELD_OPTS_STICKY, NULL);
  4060. if (enable_function_cmdline) {
  4061. buffer_rrdf_table_add_field(wb, field_id++, "CmdLine", "Command Line", RRDF_FIELD_TYPE_STRING,
  4062. RRDF_FIELD_VISUAL_VALUE, RRDF_FIELD_TRANSFORM_NONE, 0,
  4063. NULL, NAN, RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4064. RRDF_FIELD_FILTER_MULTISELECT,
  4065. RRDF_FIELD_OPTS_NONE, NULL);
  4066. }
  4067. buffer_rrdf_table_add_field(wb, field_id++, "PPID", "Parent Process ID", RRDF_FIELD_TYPE_INTEGER,
  4068. RRDF_FIELD_VISUAL_VALUE, RRDF_FIELD_TRANSFORM_NUMBER, 0, NULL,
  4069. NAN, RRDF_FIELD_SORT_ASCENDING, "PID", RRDF_FIELD_SUMMARY_COUNT,
  4070. RRDF_FIELD_FILTER_MULTISELECT,
  4071. RRDF_FIELD_OPTS_NONE, NULL);
  4072. buffer_rrdf_table_add_field(wb, field_id++, "Category", "Category (apps_groups.conf)", RRDF_FIELD_TYPE_STRING,
  4073. RRDF_FIELD_VISUAL_VALUE,
  4074. RRDF_FIELD_TRANSFORM_NONE,
  4075. 0, NULL, NAN, RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4076. RRDF_FIELD_FILTER_MULTISELECT,
  4077. RRDF_FIELD_OPTS_VISIBLE | RRDF_FIELD_OPTS_STICKY, NULL);
  4078. buffer_rrdf_table_add_field(wb, field_id++, "User", "User Owner", RRDF_FIELD_TYPE_STRING,
  4079. RRDF_FIELD_VISUAL_VALUE, RRDF_FIELD_TRANSFORM_NONE, 0, NULL, NAN,
  4080. RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4081. RRDF_FIELD_FILTER_MULTISELECT,
  4082. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4083. buffer_rrdf_table_add_field(wb, field_id++, "Uid", "User ID", RRDF_FIELD_TYPE_INTEGER, RRDF_FIELD_VISUAL_VALUE,
  4084. RRDF_FIELD_TRANSFORM_NUMBER, 0, NULL, NAN,
  4085. RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4086. RRDF_FIELD_FILTER_MULTISELECT,
  4087. RRDF_FIELD_OPTS_NONE, NULL);
  4088. buffer_rrdf_table_add_field(wb, field_id++, "Group", "Group Owner", RRDF_FIELD_TYPE_STRING,
  4089. RRDF_FIELD_VISUAL_VALUE, RRDF_FIELD_TRANSFORM_NONE, 0, NULL, NAN,
  4090. RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4091. RRDF_FIELD_FILTER_MULTISELECT,
  4092. RRDF_FIELD_OPTS_NONE, NULL);
  4093. buffer_rrdf_table_add_field(wb, field_id++, "Gid", "Group ID", RRDF_FIELD_TYPE_INTEGER, RRDF_FIELD_VISUAL_VALUE,
  4094. RRDF_FIELD_TRANSFORM_NUMBER, 0, NULL, NAN,
  4095. RRDF_FIELD_SORT_ASCENDING, NULL, RRDF_FIELD_SUMMARY_COUNT,
  4096. RRDF_FIELD_FILTER_MULTISELECT,
  4097. RRDF_FIELD_OPTS_NONE, NULL);
  4098. // CPU utilization
  4099. buffer_rrdf_table_add_field(wb, field_id++, "CPU", "Total CPU Time (100% = 1 core)",
  4100. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4101. RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", CPU_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4102. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4103. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4104. buffer_rrdf_table_add_field(wb, field_id++, "UserCPU", "User CPU time (100% = 1 core)",
  4105. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4106. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", UserCPU_max,
  4107. RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4108. RRDF_FIELD_OPTS_NONE, NULL);
  4109. buffer_rrdf_table_add_field(wb, field_id++, "SysCPU", "System CPU Time (100% = 1 core)",
  4110. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4111. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", SysCPU_max,
  4112. RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4113. RRDF_FIELD_OPTS_NONE, NULL);
  4114. buffer_rrdf_table_add_field(wb, field_id++, "GuestCPU", "Guest CPU Time (100% = 1 core)",
  4115. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4116. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", GuestCPU_max,
  4117. RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4118. RRDF_FIELD_OPTS_NONE, NULL);
  4119. buffer_rrdf_table_add_field(wb, field_id++, "CUserCPU", "Children User CPU Time (100% = 1 core)",
  4120. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4121. RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", CUserCPU_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4122. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4123. RRDF_FIELD_OPTS_NONE, NULL);
  4124. buffer_rrdf_table_add_field(wb, field_id++, "CSysCPU", "Children System CPU Time (100% = 1 core)",
  4125. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4126. RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", CSysCPU_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4127. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4128. RRDF_FIELD_OPTS_NONE, NULL);
  4129. buffer_rrdf_table_add_field(wb, field_id++, "CGuestCPU", "Children Guest CPU Time (100% = 1 core)",
  4130. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4131. RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", CGuestCPU_max, RRDF_FIELD_SORT_DESCENDING,
  4132. NULL,
  4133. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE, RRDF_FIELD_OPTS_NONE, NULL);
  4134. // CPU context switches
  4135. buffer_rrdf_table_add_field(wb, field_id++, "vCtxSwitch", "Voluntary Context Switches",
  4136. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4137. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2, "switches/s",
  4138. VoluntaryCtxtSwitches_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4139. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE, RRDF_FIELD_OPTS_NONE, NULL);
  4140. buffer_rrdf_table_add_field(wb, field_id++, "iCtxSwitch", "Involuntary Context Switches",
  4141. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4142. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2, "switches/s",
  4143. NonVoluntaryCtxtSwitches_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4144. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE, RRDF_FIELD_OPTS_NONE, NULL);
  4145. // memory
  4146. if (MemTotal)
  4147. buffer_rrdf_table_add_field(wb, field_id++, "Memory", "Memory Percentage", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4148. RRDF_FIELD_VISUAL_BAR,
  4149. RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", 100.0, RRDF_FIELD_SORT_DESCENDING, NULL,
  4150. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4151. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4152. buffer_rrdf_table_add_field(wb, field_id++, "Resident", "Resident Set Size", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4153. RRDF_FIELD_VISUAL_BAR,
  4154. RRDF_FIELD_TRANSFORM_NUMBER,
  4155. 2, "MiB", RSS_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4156. RRDF_FIELD_FILTER_RANGE,
  4157. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4158. buffer_rrdf_table_add_field(wb, field_id++, "Shared", "Shared Pages", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4159. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2,
  4160. "MiB", Shared_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4161. RRDF_FIELD_FILTER_RANGE,
  4162. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4163. buffer_rrdf_table_add_field(wb, field_id++, "Virtual", "Virtual Memory Size", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4164. RRDF_FIELD_VISUAL_BAR,
  4165. RRDF_FIELD_TRANSFORM_NUMBER, 2, "MiB", VMSize_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4166. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4167. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4168. buffer_rrdf_table_add_field(wb, field_id++, "Swap", "Swap Memory", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4169. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2,
  4170. "MiB",
  4171. Swap_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4172. RRDF_FIELD_FILTER_RANGE,
  4173. RRDF_FIELD_OPTS_NONE, NULL);
  4174. // Physical I/O
  4175. buffer_rrdf_table_add_field(wb, field_id++, "PReads", "Physical I/O Reads", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4176. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER,
  4177. 2, "KiB/s", PReads_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4178. RRDF_FIELD_FILTER_RANGE,
  4179. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4180. buffer_rrdf_table_add_field(wb, field_id++, "PWrites", "Physical I/O Writes", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4181. RRDF_FIELD_VISUAL_BAR,
  4182. RRDF_FIELD_TRANSFORM_NUMBER, 2, "KiB/s", PWrites_max, RRDF_FIELD_SORT_DESCENDING,
  4183. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4184. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4185. // Logical I/O
  4186. #ifndef __FreeBSD__
  4187. buffer_rrdf_table_add_field(wb, field_id++, "LReads", "Logical I/O Reads", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4188. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER,
  4189. 2, "KiB/s", LReads_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4190. RRDF_FIELD_FILTER_RANGE,
  4191. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4192. buffer_rrdf_table_add_field(wb, field_id++, "LWrites", "Logical I/O Writes", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4193. RRDF_FIELD_VISUAL_BAR,
  4194. RRDF_FIELD_TRANSFORM_NUMBER,
  4195. 2, "KiB/s", LWrites_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4196. RRDF_FIELD_FILTER_RANGE,
  4197. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4198. #endif
  4199. // I/O calls
  4200. buffer_rrdf_table_add_field(wb, field_id++, "RCalls", "I/O Read Calls", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4201. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2,
  4202. "calls/s", RCalls_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4203. RRDF_FIELD_FILTER_RANGE,
  4204. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4205. buffer_rrdf_table_add_field(wb, field_id++, "WCalls", "I/O Write Calls", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4206. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 2,
  4207. "calls/s", WCalls_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4208. RRDF_FIELD_FILTER_RANGE,
  4209. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4210. // minor page faults
  4211. buffer_rrdf_table_add_field(wb, field_id++, "MinFlt", "Minor Page Faults/s", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4212. RRDF_FIELD_VISUAL_BAR,
  4213. RRDF_FIELD_TRANSFORM_NUMBER,
  4214. 2, "pgflts/s", MinFlt_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4215. RRDF_FIELD_FILTER_RANGE,
  4216. RRDF_FIELD_OPTS_NONE, NULL);
  4217. buffer_rrdf_table_add_field(wb, field_id++, "CMinFlt", "Children Minor Page Faults/s",
  4218. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4219. RRDF_FIELD_VISUAL_BAR,
  4220. RRDF_FIELD_TRANSFORM_NUMBER, 2, "pgflts/s", CMinFlt_max, RRDF_FIELD_SORT_DESCENDING,
  4221. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4222. RRDF_FIELD_OPTS_NONE, NULL);
  4223. buffer_rrdf_table_add_field(wb, field_id++, "TMinFlt", "Total Minor Page Faults/s",
  4224. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4225. RRDF_FIELD_TRANSFORM_NUMBER, 2, "pgflts/s", TMinFlt_max, RRDF_FIELD_SORT_DESCENDING,
  4226. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4227. RRDF_FIELD_OPTS_NONE, NULL);
  4228. // major page faults
  4229. buffer_rrdf_table_add_field(wb, field_id++, "MajFlt", "Major Page Faults/s", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4230. RRDF_FIELD_VISUAL_BAR,
  4231. RRDF_FIELD_TRANSFORM_NUMBER,
  4232. 2, "pgflts/s", MajFlt_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4233. RRDF_FIELD_FILTER_RANGE,
  4234. RRDF_FIELD_OPTS_NONE, NULL);
  4235. buffer_rrdf_table_add_field(wb, field_id++, "CMajFlt", "Children Major Page Faults/s",
  4236. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4237. RRDF_FIELD_VISUAL_BAR,
  4238. RRDF_FIELD_TRANSFORM_NUMBER, 2, "pgflts/s", CMajFlt_max, RRDF_FIELD_SORT_DESCENDING,
  4239. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4240. RRDF_FIELD_OPTS_NONE, NULL);
  4241. buffer_rrdf_table_add_field(wb, field_id++, "TMajFlt", "Total Major Page Faults/s",
  4242. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4243. RRDF_FIELD_TRANSFORM_NUMBER, 2, "pgflts/s", TMajFlt_max, RRDF_FIELD_SORT_DESCENDING,
  4244. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4245. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4246. // open file descriptors
  4247. buffer_rrdf_table_add_field(wb, field_id++, "FDsLimitPercent", "Percentage of Open Descriptors vs Limits",
  4248. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4249. RRDF_FIELD_TRANSFORM_NUMBER, 2, "%", FDsLimitPercent_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4250. RRDF_FIELD_SUMMARY_MAX, RRDF_FIELD_FILTER_RANGE,
  4251. RRDF_FIELD_OPTS_NONE, NULL);
  4252. buffer_rrdf_table_add_field(wb, field_id++, "FDs", "All Open File Descriptors",
  4253. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4254. RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", FDs_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4255. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4256. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4257. buffer_rrdf_table_add_field(wb, field_id++, "Files", "Open Files", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4258. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 0,
  4259. "fds",
  4260. Files_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4261. RRDF_FIELD_FILTER_RANGE,
  4262. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4263. buffer_rrdf_table_add_field(wb, field_id++, "Pipes", "Open Pipes", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4264. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 0,
  4265. "fds",
  4266. Pipes_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4267. RRDF_FIELD_FILTER_RANGE,
  4268. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4269. buffer_rrdf_table_add_field(wb, field_id++, "Sockets", "Open Sockets", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4270. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 0,
  4271. "fds", Sockets_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4272. RRDF_FIELD_FILTER_RANGE,
  4273. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4274. buffer_rrdf_table_add_field(wb, field_id++, "iNotiFDs", "Open iNotify Descriptors",
  4275. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4276. RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", iNotiFDs_max, RRDF_FIELD_SORT_DESCENDING,
  4277. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4278. RRDF_FIELD_OPTS_NONE, NULL);
  4279. buffer_rrdf_table_add_field(wb, field_id++, "EventFDs", "Open Event Descriptors",
  4280. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4281. RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", EventFDs_max, RRDF_FIELD_SORT_DESCENDING,
  4282. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4283. RRDF_FIELD_OPTS_NONE, NULL);
  4284. buffer_rrdf_table_add_field(wb, field_id++, "TimerFDs", "Open Timer Descriptors",
  4285. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4286. RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", TimerFDs_max, RRDF_FIELD_SORT_DESCENDING,
  4287. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4288. RRDF_FIELD_OPTS_NONE, NULL);
  4289. buffer_rrdf_table_add_field(wb, field_id++, "SigFDs", "Open Signal Descriptors",
  4290. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4291. RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", SigFDs_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4292. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4293. RRDF_FIELD_OPTS_NONE, NULL);
  4294. buffer_rrdf_table_add_field(wb, field_id++, "EvPollFDs", "Open Event Poll Descriptors",
  4295. RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4296. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", EvPollFDs_max,
  4297. RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4298. RRDF_FIELD_OPTS_NONE, NULL);
  4299. buffer_rrdf_table_add_field(wb, field_id++, "OtherFDs", "Other Open Descriptors",
  4300. RRDF_FIELD_TYPE_BAR_WITH_INTEGER, RRDF_FIELD_VISUAL_BAR,
  4301. RRDF_FIELD_TRANSFORM_NUMBER, 0, "fds", OtherFDs_max, RRDF_FIELD_SORT_DESCENDING,
  4302. NULL, RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4303. RRDF_FIELD_OPTS_NONE, NULL);
  4304. // processes, threads, uptime
  4305. buffer_rrdf_table_add_field(wb, field_id++, "Processes", "Processes", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4306. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 0,
  4307. "processes", Processes_max, RRDF_FIELD_SORT_DESCENDING, NULL,
  4308. RRDF_FIELD_SUMMARY_SUM, RRDF_FIELD_FILTER_RANGE,
  4309. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4310. buffer_rrdf_table_add_field(wb, field_id++, "Threads", "Threads", RRDF_FIELD_TYPE_BAR_WITH_INTEGER,
  4311. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_NUMBER, 0,
  4312. "threads", Threads_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_SUM,
  4313. RRDF_FIELD_FILTER_RANGE,
  4314. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4315. buffer_rrdf_table_add_field(wb, field_id++, "Uptime", "Uptime in seconds", RRDF_FIELD_TYPE_DURATION,
  4316. RRDF_FIELD_VISUAL_BAR, RRDF_FIELD_TRANSFORM_DURATION_S, 2,
  4317. "seconds", Uptime_max, RRDF_FIELD_SORT_DESCENDING, NULL, RRDF_FIELD_SUMMARY_MAX,
  4318. RRDF_FIELD_FILTER_RANGE,
  4319. RRDF_FIELD_OPTS_VISIBLE, NULL);
  4320. }
  4321. buffer_json_object_close(wb); // columns
  4322. buffer_json_member_add_string(wb, "default_sort_column", "CPU");
  4323. buffer_json_member_add_object(wb, "charts");
  4324. {
  4325. // CPU chart
  4326. buffer_json_member_add_object(wb, "CPU");
  4327. {
  4328. buffer_json_member_add_string(wb, "name", "CPU Utilization");
  4329. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4330. buffer_json_member_add_array(wb, "columns");
  4331. {
  4332. buffer_json_add_array_item_string(wb, "UserCPU");
  4333. buffer_json_add_array_item_string(wb, "SysCPU");
  4334. buffer_json_add_array_item_string(wb, "GuestCPU");
  4335. buffer_json_add_array_item_string(wb, "CUserCPU");
  4336. buffer_json_add_array_item_string(wb, "CSysCPU");
  4337. buffer_json_add_array_item_string(wb, "CGuestCPU");
  4338. }
  4339. buffer_json_array_close(wb);
  4340. }
  4341. buffer_json_object_close(wb);
  4342. buffer_json_member_add_object(wb, "CPUCtxSwitches");
  4343. {
  4344. buffer_json_member_add_string(wb, "name", "CPU Context Switches");
  4345. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4346. buffer_json_member_add_array(wb, "columns");
  4347. {
  4348. buffer_json_add_array_item_string(wb, "vCtxSwitch");
  4349. buffer_json_add_array_item_string(wb, "iCtxSwitch");
  4350. }
  4351. buffer_json_array_close(wb);
  4352. }
  4353. buffer_json_object_close(wb);
  4354. // Memory chart
  4355. buffer_json_member_add_object(wb, "Memory");
  4356. {
  4357. buffer_json_member_add_string(wb, "name", "Memory");
  4358. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4359. buffer_json_member_add_array(wb, "columns");
  4360. {
  4361. buffer_json_add_array_item_string(wb, "Virtual");
  4362. buffer_json_add_array_item_string(wb, "Resident");
  4363. buffer_json_add_array_item_string(wb, "Shared");
  4364. buffer_json_add_array_item_string(wb, "Swap");
  4365. }
  4366. buffer_json_array_close(wb);
  4367. }
  4368. buffer_json_object_close(wb);
  4369. if(MemTotal) {
  4370. // Memory chart
  4371. buffer_json_member_add_object(wb, "MemoryPercent");
  4372. {
  4373. buffer_json_member_add_string(wb, "name", "Memory Percentage");
  4374. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4375. buffer_json_member_add_array(wb, "columns");
  4376. {
  4377. buffer_json_add_array_item_string(wb, "Memory");
  4378. }
  4379. buffer_json_array_close(wb);
  4380. }
  4381. buffer_json_object_close(wb);
  4382. }
  4383. #ifndef __FreeBSD__
  4384. // I/O Reads chart
  4385. buffer_json_member_add_object(wb, "Reads");
  4386. {
  4387. buffer_json_member_add_string(wb, "name", "I/O Reads");
  4388. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4389. buffer_json_member_add_array(wb, "columns");
  4390. {
  4391. buffer_json_add_array_item_string(wb, "LReads");
  4392. buffer_json_add_array_item_string(wb, "PReads");
  4393. }
  4394. buffer_json_array_close(wb);
  4395. }
  4396. buffer_json_object_close(wb);
  4397. // I/O Writes chart
  4398. buffer_json_member_add_object(wb, "Writes");
  4399. {
  4400. buffer_json_member_add_string(wb, "name", "I/O Writes");
  4401. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4402. buffer_json_member_add_array(wb, "columns");
  4403. {
  4404. buffer_json_add_array_item_string(wb, "LWrites");
  4405. buffer_json_add_array_item_string(wb, "PWrites");
  4406. }
  4407. buffer_json_array_close(wb);
  4408. }
  4409. buffer_json_object_close(wb);
  4410. // Logical I/O chart
  4411. buffer_json_member_add_object(wb, "LogicalIO");
  4412. {
  4413. buffer_json_member_add_string(wb, "name", "Logical I/O");
  4414. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4415. buffer_json_member_add_array(wb, "columns");
  4416. {
  4417. buffer_json_add_array_item_string(wb, "LReads");
  4418. buffer_json_add_array_item_string(wb, "LWrites");
  4419. }
  4420. buffer_json_array_close(wb);
  4421. }
  4422. buffer_json_object_close(wb);
  4423. #endif
  4424. // Physical I/O chart
  4425. buffer_json_member_add_object(wb, "PhysicalIO");
  4426. {
  4427. buffer_json_member_add_string(wb, "name", "Physical I/O");
  4428. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4429. buffer_json_member_add_array(wb, "columns");
  4430. {
  4431. buffer_json_add_array_item_string(wb, "PReads");
  4432. buffer_json_add_array_item_string(wb, "PWrites");
  4433. }
  4434. buffer_json_array_close(wb);
  4435. }
  4436. buffer_json_object_close(wb);
  4437. // I/O Calls chart
  4438. buffer_json_member_add_object(wb, "IOCalls");
  4439. {
  4440. buffer_json_member_add_string(wb, "name", "I/O Calls");
  4441. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4442. buffer_json_member_add_array(wb, "columns");
  4443. {
  4444. buffer_json_add_array_item_string(wb, "RCalls");
  4445. buffer_json_add_array_item_string(wb, "WCalls");
  4446. }
  4447. buffer_json_array_close(wb);
  4448. }
  4449. buffer_json_object_close(wb);
  4450. // Minor Page Faults chart
  4451. buffer_json_member_add_object(wb, "MinFlt");
  4452. {
  4453. buffer_json_member_add_string(wb, "name", "Minor Page Faults");
  4454. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4455. buffer_json_member_add_array(wb, "columns");
  4456. {
  4457. buffer_json_add_array_item_string(wb, "MinFlt");
  4458. buffer_json_add_array_item_string(wb, "CMinFlt");
  4459. }
  4460. buffer_json_array_close(wb);
  4461. }
  4462. buffer_json_object_close(wb);
  4463. // Major Page Faults chart
  4464. buffer_json_member_add_object(wb, "MajFlt");
  4465. {
  4466. buffer_json_member_add_string(wb, "name", "Major Page Faults");
  4467. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4468. buffer_json_member_add_array(wb, "columns");
  4469. {
  4470. buffer_json_add_array_item_string(wb, "MajFlt");
  4471. buffer_json_add_array_item_string(wb, "CMajFlt");
  4472. }
  4473. buffer_json_array_close(wb);
  4474. }
  4475. buffer_json_object_close(wb);
  4476. // Threads chart
  4477. buffer_json_member_add_object(wb, "Threads");
  4478. {
  4479. buffer_json_member_add_string(wb, "name", "Threads");
  4480. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4481. buffer_json_member_add_array(wb, "columns");
  4482. {
  4483. buffer_json_add_array_item_string(wb, "Threads");
  4484. }
  4485. buffer_json_array_close(wb);
  4486. }
  4487. buffer_json_object_close(wb);
  4488. // Processes chart
  4489. buffer_json_member_add_object(wb, "Processes");
  4490. {
  4491. buffer_json_member_add_string(wb, "name", "Processes");
  4492. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4493. buffer_json_member_add_array(wb, "columns");
  4494. {
  4495. buffer_json_add_array_item_string(wb, "Processes");
  4496. }
  4497. buffer_json_array_close(wb);
  4498. }
  4499. buffer_json_object_close(wb);
  4500. // FDs chart
  4501. buffer_json_member_add_object(wb, "FDs");
  4502. {
  4503. buffer_json_member_add_string(wb, "name", "File Descriptors");
  4504. buffer_json_member_add_string(wb, "type", "stacked-bar");
  4505. buffer_json_member_add_array(wb, "columns");
  4506. {
  4507. buffer_json_add_array_item_string(wb, "Files");
  4508. buffer_json_add_array_item_string(wb, "Pipes");
  4509. buffer_json_add_array_item_string(wb, "Sockets");
  4510. buffer_json_add_array_item_string(wb, "iNotiFDs");
  4511. buffer_json_add_array_item_string(wb, "EventFDs");
  4512. buffer_json_add_array_item_string(wb, "TimerFDs");
  4513. buffer_json_add_array_item_string(wb, "SigFDs");
  4514. buffer_json_add_array_item_string(wb, "EvPollFDs");
  4515. buffer_json_add_array_item_string(wb, "OtherFDs");
  4516. }
  4517. buffer_json_array_close(wb);
  4518. }
  4519. buffer_json_object_close(wb);
  4520. }
  4521. buffer_json_object_close(wb); // charts
  4522. buffer_json_member_add_array(wb, "default_charts");
  4523. {
  4524. buffer_json_add_array_item_array(wb);
  4525. buffer_json_add_array_item_string(wb, "CPU");
  4526. buffer_json_add_array_item_string(wb, "Category");
  4527. buffer_json_array_close(wb);
  4528. buffer_json_add_array_item_array(wb);
  4529. buffer_json_add_array_item_string(wb, "Memory");
  4530. buffer_json_add_array_item_string(wb, "Category");
  4531. buffer_json_array_close(wb);
  4532. }
  4533. buffer_json_array_close(wb);
  4534. buffer_json_member_add_object(wb, "group_by");
  4535. {
  4536. // group by PID
  4537. buffer_json_member_add_object(wb, "PID");
  4538. {
  4539. buffer_json_member_add_string(wb, "name", "Process Tree by PID");
  4540. buffer_json_member_add_array(wb, "columns");
  4541. {
  4542. buffer_json_add_array_item_string(wb, "PPID");
  4543. }
  4544. buffer_json_array_close(wb);
  4545. }
  4546. buffer_json_object_close(wb);
  4547. // group by Category
  4548. buffer_json_member_add_object(wb, "Category");
  4549. {
  4550. buffer_json_member_add_string(wb, "name", "Process Tree by Category");
  4551. buffer_json_member_add_array(wb, "columns");
  4552. {
  4553. buffer_json_add_array_item_string(wb, "Category");
  4554. buffer_json_add_array_item_string(wb, "PPID");
  4555. }
  4556. buffer_json_array_close(wb);
  4557. }
  4558. buffer_json_object_close(wb);
  4559. // group by User
  4560. buffer_json_member_add_object(wb, "User");
  4561. {
  4562. buffer_json_member_add_string(wb, "name", "Process Tree by User");
  4563. buffer_json_member_add_array(wb, "columns");
  4564. {
  4565. buffer_json_add_array_item_string(wb, "User");
  4566. buffer_json_add_array_item_string(wb, "PPID");
  4567. }
  4568. buffer_json_array_close(wb);
  4569. }
  4570. buffer_json_object_close(wb);
  4571. // group by Group
  4572. buffer_json_member_add_object(wb, "Group");
  4573. {
  4574. buffer_json_member_add_string(wb, "name", "Process Tree by Group");
  4575. buffer_json_member_add_array(wb, "columns");
  4576. {
  4577. buffer_json_add_array_item_string(wb, "Group");
  4578. buffer_json_add_array_item_string(wb, "PPID");
  4579. }
  4580. buffer_json_array_close(wb);
  4581. }
  4582. buffer_json_object_close(wb);
  4583. }
  4584. buffer_json_object_close(wb); // group_by
  4585. buffer_json_member_add_time_t(wb, "expires", expires);
  4586. buffer_json_finalize(wb);
  4587. fwrite(buffer_tostring(wb), buffer_strlen(wb), 1, stdout);
  4588. buffer_free(wb);
  4589. pluginsd_function_result_end_to_stdout();
  4590. }
  4591. static bool apps_plugin_exit = false;
  4592. static void *reader_main(void *arg __maybe_unused) {
  4593. char buffer[PLUGINSD_LINE_MAX + 1];
  4594. char *s = NULL;
  4595. while(!apps_plugin_exit && (s = fgets(buffer, PLUGINSD_LINE_MAX, stdin))) {
  4596. char *words[PLUGINSD_MAX_WORDS] = { NULL };
  4597. size_t num_words = quoted_strings_splitter_pluginsd(buffer, words, PLUGINSD_MAX_WORDS);
  4598. const char *keyword = get_word(words, num_words, 0);
  4599. if(keyword && strcmp(keyword, PLUGINSD_KEYWORD_FUNCTION) == 0) {
  4600. char *transaction = get_word(words, num_words, 1);
  4601. char *timeout_s = get_word(words, num_words, 2);
  4602. char *function = get_word(words, num_words, 3);
  4603. if(!transaction || !*transaction || !timeout_s || !*timeout_s || !function || !*function) {
  4604. netdata_log_error("Received incomplete %s (transaction = '%s', timeout = '%s', function = '%s'). Ignoring it.",
  4605. keyword,
  4606. transaction?transaction:"(unset)",
  4607. timeout_s?timeout_s:"(unset)",
  4608. function?function:"(unset)");
  4609. }
  4610. else {
  4611. int timeout = str2i(timeout_s);
  4612. if(timeout <= 0) timeout = PLUGINS_FUNCTIONS_TIMEOUT_DEFAULT;
  4613. // internal_error(true, "Received function '%s', transaction '%s', timeout %d", function, transaction, timeout);
  4614. netdata_mutex_lock(&mutex);
  4615. if(strncmp(function, "processes", strlen("processes")) == 0)
  4616. function_processes(transaction, function, buffer, PLUGINSD_LINE_MAX + 1, timeout);
  4617. else
  4618. pluginsd_function_json_error(transaction, HTTP_RESP_NOT_FOUND, "No function with this name found in apps.plugin.");
  4619. fflush(stdout);
  4620. netdata_mutex_unlock(&mutex);
  4621. // internal_error(true, "Done with function '%s', transaction '%s', timeout %d", function, transaction, timeout);
  4622. }
  4623. }
  4624. else
  4625. netdata_log_error("Received unknown command: %s", keyword?keyword:"(unset)");
  4626. }
  4627. if(!s || feof(stdin) || ferror(stdin)) {
  4628. apps_plugin_exit = true;
  4629. netdata_log_error("Received error on stdin.");
  4630. }
  4631. exit(1);
  4632. return NULL;
  4633. }
  4634. int main(int argc, char **argv) {
  4635. // debug_flags = D_PROCFILE;
  4636. stderror = stderr;
  4637. clocks_init();
  4638. pagesize = (size_t)sysconf(_SC_PAGESIZE);
  4639. // set the name for logging
  4640. program_name = "apps.plugin";
  4641. // disable syslog for apps.plugin
  4642. error_log_syslog = 0;
  4643. // set errors flood protection to 100 logs per hour
  4644. error_log_errors_per_period = 100;
  4645. error_log_throttle_period = 3600;
  4646. bool send_resource_usage = true;
  4647. {
  4648. const char *s = getenv("NETDATA_INTERNALS_MONITORING");
  4649. if(s && *s && strcmp(s, "NO") == 0)
  4650. send_resource_usage = false;
  4651. }
  4652. // since apps.plugin runs as root, prevent it from opening symbolic links
  4653. procfile_open_flags = O_RDONLY|O_NOFOLLOW;
  4654. netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
  4655. if(verify_netdata_host_prefix() == -1) exit(1);
  4656. user_config_dir = getenv("NETDATA_USER_CONFIG_DIR");
  4657. if(user_config_dir == NULL) {
  4658. // netdata_log_info("NETDATA_CONFIG_DIR is not passed from netdata");
  4659. user_config_dir = CONFIG_DIR;
  4660. }
  4661. // else netdata_log_info("Found NETDATA_USER_CONFIG_DIR='%s'", user_config_dir);
  4662. stock_config_dir = getenv("NETDATA_STOCK_CONFIG_DIR");
  4663. if(stock_config_dir == NULL) {
  4664. // netdata_log_info("NETDATA_CONFIG_DIR is not passed from netdata");
  4665. stock_config_dir = LIBCONFIG_DIR;
  4666. }
  4667. // else netdata_log_info("Found NETDATA_USER_CONFIG_DIR='%s'", user_config_dir);
  4668. #ifdef NETDATA_INTERNAL_CHECKS
  4669. if(debug_flags != 0) {
  4670. struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
  4671. if(setrlimit(RLIMIT_CORE, &rl) != 0)
  4672. netdata_log_info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
  4673. #ifdef HAVE_SYS_PRCTL_H
  4674. prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
  4675. #endif
  4676. }
  4677. #endif /* NETDATA_INTERNAL_CHECKS */
  4678. procfile_adaptive_initial_allocation = 1;
  4679. get_system_HZ();
  4680. #ifdef __FreeBSD__
  4681. time_factor = 1000000ULL / RATES_DETAIL; // FreeBSD uses usecs
  4682. #else
  4683. time_factor = system_hz; // Linux uses clock ticks
  4684. #endif
  4685. get_system_pid_max();
  4686. get_system_cpus_uncached();
  4687. parse_args(argc, argv);
  4688. if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
  4689. uid_t uid = getuid(), euid = geteuid();
  4690. #ifdef HAVE_CAPABILITY
  4691. netdata_log_error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
  4692. "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
  4693. "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
  4694. "To enable setuid to root run: sudo chown root:netdata %s; sudo chmod 4750 %s; "
  4695. , uid, euid, argv[0], argv[0], argv[0]
  4696. );
  4697. #else
  4698. netdata_log_error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
  4699. "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
  4700. "Your system does not support capabilities. "
  4701. "To enable setuid to root run: sudo chown root:netdata %s; sudo chmod 4750 %s; "
  4702. , uid, euid, argv[0], argv[0]
  4703. );
  4704. #endif
  4705. }
  4706. netdata_log_info("started on pid %d", getpid());
  4707. snprintfz(all_user_ids.filename, FILENAME_MAX, "%s/etc/passwd", netdata_configured_host_prefix);
  4708. debug_log("passwd file: '%s'", all_user_ids.filename);
  4709. snprintfz(all_group_ids.filename, FILENAME_MAX, "%s/etc/group", netdata_configured_host_prefix);
  4710. debug_log("group file: '%s'", all_group_ids.filename);
  4711. #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
  4712. all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max + 1);
  4713. #endif
  4714. all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max + 1);
  4715. netdata_thread_t reader_thread;
  4716. netdata_thread_create(&reader_thread, "APPS_READER", NETDATA_THREAD_OPTION_DONT_LOG, reader_main, NULL);
  4717. netdata_mutex_lock(&mutex);
  4718. APPS_PLUGIN_GLOBAL_FUNCTIONS();
  4719. usec_t step = update_every * USEC_PER_SEC;
  4720. global_iterations_counter = 1;
  4721. heartbeat_t hb;
  4722. heartbeat_init(&hb);
  4723. for(; !apps_plugin_exit ; global_iterations_counter++) {
  4724. netdata_mutex_unlock(&mutex);
  4725. #ifdef NETDATA_PROFILING
  4726. #warning "compiling for profiling"
  4727. static int profiling_count=0;
  4728. profiling_count++;
  4729. if(unlikely(profiling_count > 2000)) exit(0);
  4730. usec_t dt = update_every * USEC_PER_SEC;
  4731. #else
  4732. usec_t dt = heartbeat_next(&hb, step);
  4733. #endif
  4734. netdata_mutex_lock(&mutex);
  4735. struct pollfd pollfd = { .fd = fileno(stdout), .events = POLLERR };
  4736. if (unlikely(poll(&pollfd, 1, 0) < 0)) {
  4737. netdata_mutex_unlock(&mutex);
  4738. netdata_thread_cancel(reader_thread);
  4739. fatal("Cannot check if a pipe is available");
  4740. }
  4741. if (unlikely(pollfd.revents & POLLERR)) {
  4742. netdata_mutex_unlock(&mutex);
  4743. netdata_thread_cancel(reader_thread);
  4744. fatal("Received error on read pipe.");
  4745. }
  4746. if(global_iterations_counter % 10 == 0)
  4747. get_MemTotal();
  4748. if(!collect_data_for_all_processes()) {
  4749. netdata_log_error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
  4750. printf("DISABLE\n");
  4751. netdata_mutex_unlock(&mutex);
  4752. netdata_thread_cancel(reader_thread);
  4753. exit(1);
  4754. }
  4755. calculate_netdata_statistics();
  4756. normalize_utilization(apps_groups_root_target);
  4757. if(send_resource_usage)
  4758. send_resource_usage_to_netdata(dt);
  4759. #ifndef __FreeBSD__
  4760. send_proc_states_count(dt);
  4761. #endif
  4762. // this is smart enough to show only newly added apps, when needed
  4763. send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
  4764. if(likely(enable_users_charts))
  4765. send_charts_updates_to_netdata(users_root_target, "users", "Users");
  4766. if(likely(enable_groups_charts))
  4767. send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
  4768. send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
  4769. if(likely(enable_users_charts))
  4770. send_collected_data_to_netdata(users_root_target, "users", dt);
  4771. if(likely(enable_groups_charts))
  4772. send_collected_data_to_netdata(groups_root_target, "groups", dt);
  4773. fflush(stdout);
  4774. show_guest_time_old = show_guest_time;
  4775. debug_log("done Loop No %zu", global_iterations_counter);
  4776. }
  4777. netdata_mutex_unlock(&mutex);
  4778. }