apps_plugin.c 187 KB

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