apps_plugin.c 148 KB

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