apps_plugin.c 148 KB

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