apps_plugin.c 148 KB

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