apps_plugin.c 194 KB

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