apps_plugin.c 183 KB

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