apps_plugin.c 145 KB

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