apps_plugin.c 208 KB

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