-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprocs.nim
2390 lines (2245 loc) · 120 KB
/
procs.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Linux /proc data/display/query interfaces - both cmdline & library
#XXX Could port to BSD using libkvm/kvm_getprocs/_getargv/_getenvv/kinfo_proc;
# This program goes to some effort to save time by collecting only needed data.
import std/[os, posix, strutils, sets, tables, terminal, algorithm, nre,
critbits, parseutils, monotimes, macros, exitprocs, strformat],
cligen/[posixUt,mfile,mslice,sysUt,textUt,humanUt,strUt,abbrev,macUt,puSig]
export signum # from puSig; For backward compatibility
when not declared(stdout): import std/syncio
const ess: seq[string] = @[]
#------------ SAVE-LOAD SYS: Avoid FS calls;Can Be Stale BUT SOMETIMES WANT THAT
let PFS = getEnv("PFS","/proc") # Alt Root; Repro runs @other times/machines
let PFA = getEnv("PFA", "") # Nm of cpio -Hbin Proc File Archive to make
if PFS.len > 0 and PFA == PFS: Value !! "Cannot set PFS & PFA to same value"
type Rec* {.packed.} = object # Saved data header; cpio -oHbin compatible
magic, dev, ino, mode, uid, gid, nlink, rdev: uint16 # magic=0o070707
mtime : array[2, uint16]
nmLen : uint16
datLen: array[2, uint16] #26B Hdr; Support readFile stat readlink
proc cpioLoad(path: string): (Table[MSlice, MSlice], seq[string]) =
let mf = mopen(path) # Lifetime of program on purpose
if mf.mem.isNil: return # mmap on directories fails
result[0] = initTable[MSlice, MSlice](mf.len div 90) # 90 is <sz> guess
let trailBuf = "TRAILER!!!"; let trailer = trailBuf.toMSlice
var nm, dat: MSlice
var off = 0
while off + Rec.sizeof < mf.len:
let h = cast[ptr Rec](mf.mem +! off)
off += Rec.sizeof
if h.magic != 0o070707: IO !! &"off:{off}: magic!=0o070707: 0o{h.magic:06o}"
nm = MSlice(mem: mf.mem +! off, len: h.nmLen.int - 1) # Rec includes \0
if nm == trailer: break
if nm.len > 0 and nm[0] in {'1'..'9'} and (let sl = nm.find('/'); sl != -1):
let tld = $nm[0..<sl]
if result[1].len > 0: (if result[1][^1] != tld: result[1].add $nm[0..<sl])
else: result[1].add tld
off += h.nmLen.int + int(h.nmLen mod 2 != 0)
let dLen = (h.datLen[0].int shl 16) or h.datLen[1].int
dat = MSlice(mem: mf.mem +! off, len: dLen)
off += dLen + int(dLen mod 2 != 0)
if (h.mode.cint and S_IFMT)==S_IFLNK and dat.len>0 and dat[dat.len-1]=='\0':
dat.len -= 1
result[0][nm] = dat
var tab: Table[MSlice, MSlice]
var apids: seq[string] # Archive pids
if chdir(PFS.cstring) != 0:
(tab, apids) = cpioLoad(PFS)
if tab.len == 0: IO !! "Cannot cd into " & PFS & " & it seems not to be cpio"
discard chdir("/proc/") # For fall back querying
var rec = Rec(magic: 0o070707)
var pad0: array[512, char]
var outp: File
if PFA.len > 0: outp = open(PFA, fmWrite)
proc writeRecHdr(path: cstring; pLen, datLen: int) =
let path = if path.isNil: nil else: cast[pointer](path)
let pLen = if path.isNil: 0 else: pLen
rec.nmLen = uint16(pLen + 1) # Include NUL terminator
rec.datLen[0] = uint16(datLen shr 16)
rec.datLen[1] = uint16(datLen and 0xFFFF)
discard outp.writeBuffer(rec.addr, rec.sizeof)
discard outp.writeBuffer(path , pLen + 1)
if pLen mod 2 == 0: discard outp.writeBuffer(pad0.addr, 1)
proc readFile(path: string, buf: var string, st: ptr Stat=nil, perRead=4096) =
if tab.len > 0:
try:
let s = tab[path.toMSlice]
buf.setLen s.len
copyMem buf.cstring, s.mem, s.len
except: buf.setLen 0
else: posixUt.readFile path, buf, nil, perRead
if PFA.len > 0:
rec.mode = 0o100444; rec.nlink = 1 # Regular file r--r--r--; Inherit rest..
writeRecHdr path.cstring, path.len, buf.len #.. from probable last stat.
discard outp.writeBuffer(buf.cstring, buf.len)
if buf.len mod 2 == 1: discard outp.writeBuffer(pad0.addr, 1)
proc cstrlen(s: pointer): int {.importc: "strlen", header:"string.h".}
proc stat(a1: cstring, a2: var Stat): cint =
if tab.len > 0:
try:
let key = MSlice(mem: a1, len: a1.cstrlen)
let s = tab[key]
let kLen = if key.len mod 2 == 0: key.len + 2 else: key.len + 1
let r = cast[ptr Rec](cast[uint](s.mem) - uint(Rec.sizeof + kLen))
a2.st_uid = r.uid.Uid; a2.st_gid = r.gid.Gid
except: discard
else: discard posix.stat(a1, a2)
if PFA.len > 0:
rec.dev = uint16(a2.st_dev) # Dev should neither change nor matter..
rec.ino = uint16(a2.st_ino) #..so can fold into above for 4B inode.
rec.mode = uint16(a2.st_mode)
rec.uid = uint16(a2.st_uid)
rec.gid = uint16(a2.st_gid)
rec.nlink = uint16(a2.st_nlink) # Generally 1|number of sub-dirs
rec.rdev = uint16(a2.st_rdev) # Dev Specials are very rare
rec.mtime[0] = uint16(a2.st_mtime.int shr 16)
rec.mtime[1] = uint16(a2.st_mtime.int and 0xFFFF)
writeRecHdr a1, a1.len, 0
proc readlink(path: string, err=stderr): string =
if tab.len > 0:
try:
let s = tab[path.toMSlice]
result.setLen s.len
copyMem result.cstring, s.mem, s.len
except: discard
else: result = posixUt.readlink(path, err)
if PFA.len > 0 and result.len > 0: #Mark as SymLn;MUST BE KNOWN to be SymLn
rec.mode = 0o120777; rec.nlink = 1 # Inherit rest from probable last stat.
writeRecHdr path.cstring, path.len, result.len + 1
discard outp.writeBuffer(result.cstring, result.len + 1)
if result.len mod 2 == 0: discard outp.writeBuffer(pad0.addr, 1)
proc writeTrailer() =
if PFA.len == 0 or outp.isNil: return
rec.nlink = 1 # At least GNU cpio does this
writeRecHdr cstring("TRAILER!!!"), 10, 0
let sz = outp.getFilePos # Traditionally, cpio pads to 512B block size
if sz mod 512!=0:discard outp.writeBuffer(pad0.addr,(sz div 512 + 1)*512 - sz)
addExitProc writeTrailer
type #------------ TYPES FOR PER-PROCESS DATA
Ce = CatchableError
Proc* = object ##Abstract proc data (including a kind vector)
kind*: seq[uint8] ##kind nums for independent format dimensions
st*: Stat
pidPath*: seq[Pid]
state*: char
spid*, cmd*, usr*, grp*: string
pid*, pid0*, ppid0*, pgrp*, sess*, pgid*, nThr*: Pid
flags*, minflt*, cminflt*, majflt*, cmajflt*: culong
t0*, ageD*, utime*, stime*, cutime*, cstime*: culong
prio*, nice*: clong
vsize*, rss*, rss_rlim*, rtprio*, sched*, blkioTks*, gtime*, cgtime*,
data0*, data1*, brk0*, arg0*, arg1*, env0*, env1*: culong
startcode*, endcode*, startstk*, kstk_esp*, kstk_eip*, wchan0*: uint64
tty*: Dev
exit_sig*, processor*, exitCode*: cint
size*, res*, share*, txt*, lib*, dat*, dty*: culong
environ*, usrs*, grps*: seq[string]
cmdLine*, argv0*, root*, cwd*, exe*: string
name*, umask*, stateS*: string
tgid*, ngid*, pid1*, ppid*, tracerPid*, nStgid*, nSpid*, nSpgid*, nSsid*:Pid
uids*: array[4, Uid] #id_real, id_eff, id_set, id_fs
gids*: array[4, Gid] #id_real, id_eff, id_set, id_fs
groups*: seq[Gid]
vmPeak*,vmSize*,vmLck*,vmPin*,vmHWM*,vmRSS*, rssAnon*,rssFile*,rssShmem*,
vmData*, vmStk*, vmExe*, vmLib*, vmPTE*, vmSwap*, hugeTLB*: uint64
fDSize*, coreDumping*, tHP_enabled*, threads*, noNewPrivs*, seccomp*: uint16
sigQ*, sigPnd*, shdPnd*, sigBlk*, sigIgn*, sigCgt*: string
capInh*, capPrm*, capEff*, capBnd*, capAmb*: string
spec_Store_Bypass*: string
cpusAllowed*, memsAllowed*: uint16
cpusAllowedList*, memsAllowedList*: string
volunCtxtSwitch*, nonVolunCtxtSwitch*: uint64
wchan*: string
rch*, wch*, syscr*, syscw*, rbl*, wbl*, wcancel*: uint64
nIpc*, nMnt*, nNet*, nPid*, nUser*, nUts*, nCgroup*, nPid4Kids*: Ino
fd0*, fd1*, fd2*, fd3*, fd4*, fd5*, fd6*: string #/proc/PID/fd/*
oom_score*, oom_adj*, oom_score_adj*: cint
pss*, pss_dirty*, pss_anon*, pss_file*, shrClean*, shrDirty*, #smaps_rollup
pvtClean*, pvtDirty*, refd*, anon*, lazyFree*, thpAnon*, thpShm*,
thpFile*, thpShr*, thpPvt*, pss_swap*, pss_lock*: uint64
pSched*, pWait*, pNOnCPU*: int64 #XXX /proc/PID/(personality|limits|..)
ProcField* = enum #stat
pf_pid0=0, pf_cmd, pf_state, pf_ppid0, pf_pgrp, pf_sess, pf_tty, pf_pgid,
pf_flags, pf_minflt, pf_cminflt, pf_majflt, pf_cmajflt, pf_utime, pf_stime,
pf_cutime, pf_cstime, pf_prio, pf_nice, pf_nThr, pf_alrm, pf_t0, pf_vsize,
pf_rss, pf_rss_rlim, pf_startcode, pf_endcode, pf_startstk, pf_kstk_esp,
pf_kstk_eip,
pf_sigPnd, pf_sigBlk, pf_sigIgn, pf_sigCgt, #DO NOT USE THESE or pf_alrm
pf_wchan0, pf_defunct1, pf_defunct2, #DO NOT USE THESE
pf_exit_sig, pf_processor, pf_rtprio, pf_sched, pf_blkioTks, pf_gtime,
pf_cgtime, pf_data0, pf_data1, pf_brk0, pf_arg0, pf_arg1, pf_env0, pf_env1,
pf_exitCode,
pffs_uid, pffs_gid, #fstat
pffs_usr, pffs_grp, pfs_usrs, pfs_grps, #/etc/pw
pfsm_size,pfsm_res, pfsm_share,pfsm_txt,pfsm_lib,pfsm_dat,pfsm_dty, #statm
pfcl_cmdline, pfen_environ, pfr_root, pfc_cwd, pfe_exe, #various
pfs_name, pfs_umask, pfs_stateS, pfs_tgid, pfs_ngid, #status
pfs_pid1, pfs_pPid, pfs_tracerPid, pfs_uids, pfs_gids,
pfs_fDSize, pfs_groups, pfs_nStgid, pfs_nSpid, pfs_nSpgid, pfs_nSsid,
pfs_vmPeak, pfs_vmSize, pfs_vmLck, pfs_vmPin, pfs_vmHWM, pfs_vmRSS,
pfs_rssAnon, pfs_rssFile, pfs_rssShmem,
pfs_vmData, pfs_vmStk, pfs_vmExe, pfs_vmLib, pfs_vmPTE, pfs_vmSwap,
pfs_hugeTLB, pfs_coreDumping, pfs_tHP_enabled, pfs_threads,
pfs_sigQ, pfs_sigPnd, pfs_shdPnd, pfs_sigBlk, pfs_sigIgn, pfs_sigCgt,
pfs_capInh, pfs_capPrm, pfs_capEff, pfs_capBnd, pfs_capAmb,
pfs_noNewPrivs, pfs_seccomp, pfs_specStoreBypass,
pfs_cpusAllowed, pfs_cpusAllowedList,
pfs_memsAllowed, pfs_memsAllowedList,
pfs_volunCtxtSwitch, pfs_nonVolunCtxtSwitch,
pfw_wchan, #wchan
pfi_rch, pfi_wch, pfi_syscr, pfi_syscw, pfi_rbl, pfi_wbl, pfi_wcancel, #io
pfn_ipc, pfn_mnt, pfn_net, pfn_pid, pfn_user, pfn_uts, #NmSpcs
pfn_cgroup, pfn_pid4Kids,
pfd_0, pfd_1, pfd_2, pfd_3, pfd_4, pfd_5, pfd_6, #/proc/PID/fd/*
pfo_score, pfo_adj, pfo_score_adj, #oom scoring
pfsr_pss, pfsr_pss_dirty, pfsr_pss_anon, pfsr_pss_file, pfsr_shrClean,
pfsr_shrDirty, pfsr_pvtClean, pfsr_pvtDirty, pfsr_refd, pfsr_anon,
pfsr_lazyFree, pfsr_thpAnon, pfsr_thpShm, pfsr_thpFile, pfsr_thpShr,
pfsr_thpPvt, pfsr_pss_swap, pfsr_pss_lock,
pfss_sched, pfss_wait, pfss_NOnCPU # User+Sys Tm;Tm waiting2run;NumOnThisCPU
ProcFields* = set[ProcField]
ProcSrc=enum psDStat="dstat",psStat="stat",psStatm="statm",psStatus="status",
psWChan="wchan", psIO="io", psSMapsR="smaps_rollup", psSchedSt="schedstat",
psRoot="root", psCwd="cwd", psExe="exe", psFDs="fds"
ProcSrcs* = set[ProcSrc]
NmSpc* = enum nsIpc = "ipc" , nsMnt = "mnt", nsNet = "net", nsPid = "pid",
nsUser = "user", nsUts = "uts", nsCgroup = "cgroup",
nsPid4Kids = "pid4kids"
#------------ TYPE FOR procs.find ACTIONS
PfAct* = enum acEcho="echo", acPath="path", acAid ="aid" , acCount="count",
acKill="kill", acNice="nice", acWait1="wait", acWaitA="Wait"
#------------ TYPES FOR SYSTEM-WIDE DATA
MemInfo* = tuple[MemTotal, MemFree, MemAvailable, Buffers, Cached,
SwapCached, Active, Inactive, ActiveAnon, InactiveAnon, ActiveFile,
InactiveFile, Unevictable, Mlocked, SwapTotal, SwapFree, Dirty, Writeback,
AnonPages, Mapped, Shmem, KReclaimable, Slab, SReclaimable, SUnreclaim,
KernelStack, PageTables, NFS_Unstable, Bounce, WritebackTmp, CommitLimit,
Committed_AS, VmallocTotal, VmallocUsed, VmallocChunk, Percpu,
AnonHugePages, ShmemHugePages, ShmemPmdMapped, CmaTotal, CmaFree,
HugePagesTotal, HugePagesFree, HugePagesRsvd, HugePagesSurp,
Hugepagesize, Hugetlb, DirectMap4k, DirectMap2M, DirectMap1G: uint]
CPUInfo* = tuple[user, nice, system, idle, iowait, irq,
softirq, steal, guest, guest_nice: int]
SoftIRQs* = tuple[all, hi, timer, net_tx, net_rx, blk,
irq_poll, tasklet, sched, hrtimer, rcu: int]
SysStat* = tuple[cpu: seq[CPUInfo], ##Index 0=combined
interrupts, contextSwitches, bootTime,
procs, procsRunnable, procsBlocked: int,
softIRQ: SoftIRQs]
NetStat* = tuple[bytes, packets, errors, drops, fifo, frame,
compressed, multicast: int]
NetDevStat* = tuple[name: string; rcvd, sent: NetStat]
NetDevStats* = seq[NetDevStat]
DiskIOStat* = tuple[nIO, nMerge, nSector, msecs: int]
DiskStat* = tuple[major, minor: int, name: string,
reads, writes, cancels: DiskIOStat,
inFlight, ioTicks, timeInQ: int]
DiskStats* = seq[DiskStat]
LoadAvg* = tuple[m1, m5, m15: string; runnable, total: int; mostRecent: Pid]
Sys* = tuple[m: MemInfo; s: SysStat; l: LoadAvg; d: DiskStats; n: NetDevStats]
SysSrc = enum ssMemInfo, ssStat, ssLoadAvg, ssDiskStat, ssNetDev
SysSrcs* = set[SysSrc]
proc toPfn(ns: NmSpc): ProcField =
case ns
of nsIpc: pfn_ipc
of nsMnt: pfn_mnt
of nsNet: pfn_net
of nsPid: pfn_pid
of nsUser: pfn_user
of nsUts: pfn_uts
of nsCgroup: pfn_cgroup
of nsPid4Kids: pfn_pid4Kids
const needsStat = { pf_cmd, pf_state, pf_ppid0, pf_pgrp, pf_sess,
pf_tty, pf_pgid, pf_flags, pf_minflt, pf_cminflt, pf_majflt, pf_cmajflt,
pf_utime, pf_stime, pf_cutime, pf_cstime, pf_prio, pf_nice, pf_nThr,
pf_t0, pf_vsize, pf_rss, pf_rss_rlim, pf_startcode, pf_endcode, pf_startstk,
pf_kstk_esp, pf_kstk_eip, pf_wchan0, pf_exit_sig, pf_processor, pf_rtprio,
pf_sched }
const needsFstat = { pffs_uid, pffs_gid, pffs_usr, pffs_grp }
const needsStatm = { pfsm_size, pfsm_res, pfsm_share, pfsm_txt, pfsm_lib,
pfsm_dat, pfsm_dty }
const needsStatus = { pfs_name, pfs_umask, pfs_stateS, pfs_tgid, pfs_ngid,
pfs_pid1, pfs_pPid, pfs_tracerPid, pfs_uids, pfs_gids, pfs_fDSize, pfs_groups,
pfs_nStgid, pfs_nSpid, pfs_nSpgid, pfs_nSsid, pfs_vmPeak, pfs_vmSize,
pfs_vmLck, pfs_vmPin, pfs_vmHWM, pfs_vmRSS, pfs_rssAnon, pfs_rssFile,
pfs_rssShmem, pfs_vmData, pfs_vmStk, pfs_vmExe, pfs_vmLib, pfs_vmPTE,
pfs_vmSwap, pfs_hugeTLB, pfs_coreDumping, pfs_tHP_enabled, pfs_threads,
pfs_sigQ, pfs_sigPnd, pfs_shdPnd, pfs_sigBlk, pfs_sigIgn, pfs_sigCgt,
pfs_capInh, pfs_capPrm, pfs_capEff, pfs_capBnd, pfs_capAmb, pfs_noNewPrivs,
pfs_seccomp, pfs_specStoreBypass, pfs_cpusAllowed,
pfs_cpusAllowedList, pfs_memsAllowed, pfs_memsAllowedList,
pfs_volunCtxtSwitch, pfs_nonVolunCtxtSwitch }
const needsSchedSt = { pfss_sched, pfss_wait, pfss_NOnCPU }
var usrs*: Table[Uid, string] #user tables
var uids*: Table[string, Uid]
var grps*: Table[Gid, string] #group tables
var gids*: Table[string, Gid]
proc invert*[T, U](x: Table[T, U]): Table[U, T] =
for k, v in x.pairs: result[v] = k
#------------ SYNTHETIC FIELDS
proc ancestorId(pidPath: seq[Pid], ppid=0.Pid): Pid =
if pidPath.len > 1: pidPath[1] elif pidPath.len > 0: pidPath[0] else: ppid
proc command(p: Proc): string = (if p.cmdLine.len > 0: p.cmdLine else: p.cmd)
proc cmdClean(cmd: string): string = # map non-printing ASCII -> ' '
result.setLen cmd.len
for i, c in cmd: result[i] = (if ord(c) < 32: ' ' else: c)
while result[^1] == ' ': result.setLen result.len - 1 # strip trailing white
#------------ PROCESS SPECIFIC /proc/PID/file PARSING
const needsIO = { pfi_rch, pfi_wch, pfi_syscr, pfi_syscw,
pfi_rbl, pfi_wbl, pfi_wcancel }
const needsSMapsR = { pfsr_pss, pfsr_pss_dirty, pfsr_pss_anon, pfsr_pss_file,
pfsr_shrClean, pfsr_shrDirty, pfsr_pvtClean, pfsr_pvtDirty, pfsr_refd,
pfsr_anon, pfsr_lazyFree, pfsr_thpAnon, pfsr_thpShm, pfsr_thpFile,
pfsr_thpShr, pfsr_thpPvt, pfsr_pss_swap, pfsr_pss_lock }
proc any[T](s: set[T], es: varargs[T]): bool =
for e in es: (if e in s: return true)
proc all[T](s: set[T], es: varargs[T]): bool =
for e in es: (if e notin s: return)
true
proc needs*(fill: var ProcFields): ProcSrcs =
## Compute the ``ProcDatas`` argument for ``read(var Proc)`` based on
## all the requested fields in ``fill``.
if pffs_usr in fill: fill.incl pffs_uid #If string usr/grp requested then
if pffs_grp in fill: fill.incl pffs_gid #..add the numeric id to fill.
if pfs_usrs in fill: fill.incl pfs_uids
if pfs_grps in fill: fill.incl pfs_gids
if (needsFstat * fill).card > 0: result.incl psDStat
if (needsStat * fill).card > 0: result.incl psStat
if (needsStatm * fill).card > 0: result.incl psStatm
if (needsStatus * fill).card > 0: result.incl psStatus
if (needsIO * fill).card > 0: result.incl psIO
if (needsSchedSt * fill).card > 0: result.incl psSchedSt
if (needsSMapsR * fill).card > 0: result.incl psSMapsR
if pffs_usr in fill or pfs_usrs in fill and usrs.len == 0: usrs = users()
if pffs_grp in fill or pfs_grps in fill and grps.len == 0: grps = groups()
proc nonDecimal(s: string): bool =
for c in s:
if c < '0' or c > '9': return true
iterator allPids*(): string =
## Yield all pids as strings on a running Linux system via /proc entries
if apids.len > 0:
for pid in apids: yield pid
else:
for pcKind, pid in walkDir(".", relative=true):
if pcKind != pcDir or pid.nonDecimal: continue
yield pid
proc pidsIt*(pids: seq[string]): auto =
## Yield pids as strings from provided ``seq`` if non-empty or ``/proc``.
result = iterator(): string =
if pids.len > 0:
for pid in pids: yield pid
else:
for pid in allPids(): yield pid
template forPid*(pids: seq[string], body) {.dirty.} =
var did: HashSet[string]
if pids.len > 0:
for pid in pids:
if pid notin did: (did.incl pid; body)
else: (for pid in allPids(): body)
proc toPid(s: string|MSlice): Pid {.inline.} = parseInt(s).Pid
proc toDev(s: string|MSlice): Dev {.inline.} = parseInt(s).Dev
proc toCul(s: string|MSlice, unit=1): culong = parseInt(s).culong*unit.culong
proc toCui(s: string|MSlice): cuint {.inline.} = parseInt(s).cuint
proc toU16(s: string|MSlice): uint16{.inline.} = parseInt(s).uint16
proc toU64(s: string|MSlice, unit=1): uint64 = parseInt(s).uint64*unit.uint64
proc toCin(s: string|MSlice): cint {.inline.} = parseInt(s).cint
proc toInt(s: string|MSlice): int {.inline.} = parseInt(s)
proc toMem(s: string|MSlice): uint64{.inline.} = parseInt(s).uint64
var buf = newStringOfCap(4096) #shared IO buffer for all readFile
proc readStat*(p: var Proc; pr: string, fill: ProcFields): bool =
## Populate ``Proc p`` pf_ fields requested in ``fill`` via /proc/PID/stat.
## Returns false upon missing/corrupt file (eg. stale ``pid`` | not Linux).
result = true
(pr & "stat").readFile buf
let cmd0 = buf.find('(') + 1 #Bracket command. Works even if cmd has
let cmd1 = buf.rfind(')') #..parens or whitespace chars in it.
if cmd0 < 3 or cmd1 == -1 or p.spid.len < cmd0 - 2 or # 2=" " + error offset
cmpMem(p.spid[0].addr, buf[0].addr, p.spid.len) != 0: return false
let nC = cmd1 - cmd0
if pf_pid0 in fill: p.pid0 = MSlice(mem: buf[0].addr, len: cmd0 - 2).toPid
if pf_cmd in fill: p.cmd.setLen nC; copyMem p.cmd.cstring, buf[cmd0].addr, nC
var i = 1
if buf[^1] == '\n': buf.setLen buf.len - 1
for s in MSlice(mem: buf[cmd1 + 2].addr, len: buf.len - (cmd1 + 2)).mSlices:
i.inc; case i
of pf_state .int:p.state =if pf_state in fill: s[0] else:'\0'
of pf_ppid0 .int:p.ppid0 =if pf_ppid0 in fill: toPid(s) else:0
of pf_pgrp .int:p.pgrp =if pf_pgrp in fill: toPid(s) else:0
of pf_sess .int:p.sess =if pf_sess in fill: toPid(s) else:0
of pf_tty .int:p.tty =if pf_tty in fill: toDev(s) else:0
of pf_pgid .int:p.pgid =if pf_pgid in fill: toPid(s) else:0
of pf_flags .int:p.flags =if pf_flags in fill: toCul(s) else:0
of pf_minflt .int:p.minflt =if pf_minflt in fill: toCul(s) else:0
of pf_cminflt .int:p.cminflt =if pf_cminflt in fill: toCul(s) else:0
of pf_majflt .int:p.majflt =if pf_majflt in fill: toCul(s) else:0
of pf_cmajflt .int:p.cmajflt =if pf_cmajflt in fill: toCul(s) else:0
of pf_utime .int:p.utime =if pf_utime in fill: toCul(s) else:0
of pf_stime .int:p.stime =if pf_stime in fill: toCul(s) else:0
of pf_cutime .int:p.cutime =if pf_cutime in fill: toCul(s) else:0
of pf_cstime .int:p.cstime =if pf_cstime in fill: toCul(s) else:0
of pf_prio .int:p.prio =if pf_prio in fill: toInt(s) else:0
of pf_nice .int:p.nice =if pf_nice in fill: toInt(s) else:0
of pf_nThr .int:p.nThr =if pf_nThr in fill: toPid(s) else:0
of pf_alrm .int: discard #discontinued
of pf_t0 .int:p.t0 =if pf_t0 in fill: toCul(s) else:0
of pf_vsize .int:p.vsize =if pf_vsize in fill: toCul(s) else:0
of pf_rss .int:p.rss =if pf_rss in fill: toCul(s,4096)else:0
of pf_rss_rlim .int:p.rss_rlim =if pf_rss_rlim in fill: toCul(s) else:0
of pf_startcode.int:p.startcode=if pf_startcode in fill: toU64(s) else:0
of pf_endcode .int:p.endcode =if pf_endcode in fill: toU64(s) else:0
of pf_startstk .int:p.startstk =if pf_startstk in fill: toU64(s) else:0
of pf_kstk_esp .int:p.kstk_esp =if pf_kstk_esp in fill: toU64(s) else:0
of pf_kstk_eip .int:p.kstk_eip =if pf_kstk_eip in fill: toU64(s) else:0
of pf_sigPnd .int: discard #discontinued
of pf_sigBlk .int: discard #discontinued
of pf_sigIgn .int: discard #discontinued
of pf_sigCgt .int: discard #discontinued
of pf_wchan0 .int:p.wchan0 =if pf_wchan0 in fill: toU64(s) else:0
of pf_defunct1 .int: discard #discontinued
of pf_defunct2 .int: discard #discontinued
of pf_exit_sig .int:p.exit_sig =if pf_exit_sig in fill: toCin(s) else:0
of pf_processor.int:p.processor=if pf_processor in fill: toCin(s) else:0
of pf_rtprio .int:p.rtprio =if pf_rtprio in fill: toCul(s) else:0
of pf_sched .int:p.sched =if pf_sched in fill: toCul(s) else:0
of pf_blkioTks .int:p.blkioTks =if pf_blkioTks in fill: toCul(s) else:0
of pf_gtime .int:p.gtime =if pf_gtime in fill: toCul(s) else:0
of pf_cgtime .int:p.cgtime =if pf_cgtime in fill: toCul(s) else:0
of pf_data0 .int:p.data0 =if pf_data0 in fill: toCul(s) else:0
of pf_data1 .int:p.data1 =if pf_data1 in fill: toCul(s) else:0
of pf_brk0 .int:p.brk0 =if pf_brk0 in fill: toCul(s) else:0
of pf_arg0 .int:p.arg0 =if pf_arg0 in fill: toCul(s) else:0
of pf_arg1 .int:p.arg1 =if pf_arg1 in fill: toCul(s) else:0
of pf_env0 .int:p.env0 =if pf_env0 in fill: toCul(s) else:0
of pf_env1 .int:p.env1 =if pf_env1 in fill: toCul(s) else:0
of pf_exitCode .int:p.exitCode =if pf_exitCode in fill: toCin(s) else:0
else: discard
proc readStatm*(p: var Proc; pr: string, fill: ProcFields): bool =
## Populate ``Proc p`` pfsm_ fields requested in ``fill`` via /proc/PID/statm.
## Returns false upon missing/corrupt file (eg. stale ``pid`` | not Linux).
result = true
(pr & "statm").readFile buf
let c = buf.split
if c.len != 7:
return false
if pfsm_size in fill: p.size = toCul(c[0])
if pfsm_res in fill: p.res = toCul(c[1])
if pfsm_share in fill: p.share = toCul(c[2])
if pfsm_txt in fill: p.txt = toCul(c[3])
if pfsm_lib in fill: p.lib = toCul(c[4])
if pfsm_dat in fill: p.dat = toCul(c[5])
if pfsm_dty in fill: p.dty = toCul(c[6])
proc readStatus*(p: var Proc; pr: string, fill: ProcFields): bool=
## Populate ``Proc p`` pfs_ fields requested in ``fill`` via /proc/PID/status.
## Returns false upon missing/corrupt file (eg. stale ``pid`` | not Linux).
proc `<`(f: ProcField, fs: ProcFields): bool {.inline} = f in fs
result = true
(pr & "status").readFile buf
var c = newSeqOfCap[string](32)
for line in buf.split('\n'):
if line.len == 0 or line.splitr(c, seps=wspace) < 2: continue
let n = c[0]
if pfs_name < fill and n=="Name:": p.name = c[1]
elif pfs_umask < fill and n=="Umask:": p.umask = c[1]
elif pfs_stateS < fill and n=="State:": p.stateS = c[1]
elif pfs_tgid < fill and n=="Tgid:": p.tgid = toPid(c[1])
elif pfs_ngid < fill and n=="Ngid:": p.ngid = toPid(c[1])
elif pfs_pid1 < fill and n=="Pid:": p.pid1 = toPid(c[1])
elif pfs_pPid < fill and n=="PPid:": p.ppid = toPid(c[1])
elif pfs_tracerPid < fill and n=="TracerPid:": p.tracerPid = toPid(c[1])
elif pfs_uids < fill and n=="Uid:":
if c.len != 5: return false
for i in 0..3: p.uids[i] = toCui(c[i+1]).Uid
elif pfs_gids < fill and n=="Gid:":
if c.len != 5: return false
for i in 0..3: p.gids[i] = toCui(c[i+1]).Gid
elif pfs_fDSize < fill and n=="FDSize:": p.fDSize = toU16(c[1])
elif pfs_groups < fill and n=="Groups:":
p.groups.setLen(c.len - 1)
for i, g in c[1..^1]: p.groups[i] = toCui(g).Gid
elif pfs_nStgid < fill and n=="NStgid:": p.nStgid = toPid(c[1])
elif pfs_nSpid < fill and n=="NSpid:": p.nSpid = toPid(c[1])
elif pfs_nSpgid < fill and n=="NSpgid:": p.nSpgid = toPid(c[1])
elif pfs_nSsid < fill and n=="NSsid:": p.nSsid = toPid(c[1])
elif pfs_vmPeak < fill and n=="VmPeak:": p.vmPeak = toMem(c[1])
elif pfs_vmSize < fill and n=="VmSize:": p.vmSize = toMem(c[1])
elif pfs_vmLck < fill and n=="VmLck:": p.vmLck = toMem(c[1])
elif pfs_vmPin < fill and n=="VmPin:": p.vmPin = toMem(c[1])
elif pfs_vmHWM < fill and n=="VmHWM:": p.vmHWM = toMem(c[1])
elif pfs_vmRSS < fill and n=="VmRSS:": p.vmRSS = toMem(c[1])
elif pfs_rssAnon < fill and n=="RssAnon:": p.rssAnon = toMem(c[1])
elif pfs_rssFile < fill and n=="RssFile:": p.rssFile = toMem(c[1])
elif pfs_rssShmem < fill and n=="RssShmem:": p.rssShmem = toMem(c[1])
elif pfs_vmData < fill and n=="VmData:": p.vmData = toMem(c[1])
elif pfs_vmStk < fill and n=="VmStk:": p.vmStk = toMem(c[1])
elif pfs_vmExe < fill and n=="VmExe:": p.vmExe = toMem(c[1])
elif pfs_vmLib < fill and n=="VmLib:": p.vmLib = toMem(c[1])
elif pfs_vmPTE < fill and n=="VmPTE:": p.vmPTE = toMem(c[1])
elif pfs_vmSwap < fill and n=="VmSwap:": p.vmSwap = toMem(c[1])
elif pfs_hugeTLB < fill and n=="HugetlbPages:":p.hugeTLB = toMem(c[1])
elif pfs_coreDumping<fill and n=="CoreDumping:": p.coreDumping= toU16(c[1])
elif pfs_tHP_enabled<fill and n=="THP_enabled:": p.tHP_enabled= toU16(c[1])
elif pfs_threads < fill and n=="Threads:": p.threads = toU16(c[1])
elif pfs_sigQ < fill and n=="SigQ:": p.sigQ = c[1]
elif pfs_sigPnd < fill and n=="SigPnd:": p.sigPnd = c[1]
elif pfs_shdPnd < fill and n=="ShdPnd:": p.shdPnd = c[1]
elif pfs_sigBlk < fill and n=="SigBlk:": p.sigBlk = c[1]
elif pfs_sigIgn < fill and n=="SigIgn:": p.sigIgn = c[1]
elif pfs_sigCgt < fill and n=="SigCgt:": p.sigCgt = c[1]
elif pfs_capInh < fill and n=="CapInh:": p.capInh = c[1]
elif pfs_capPrm < fill and n=="CapPrm:": p.capPrm = c[1]
elif pfs_capEff < fill and n=="CapEff:": p.capEff = c[1]
elif pfs_capBnd < fill and n=="CapBnd:": p.capBnd = c[1]
elif pfs_capAmb < fill and n=="CapAmb:": p.capAmb = c[1]
elif pfs_noNewPrivs < fill and n=="NoNewPrivs:": p.noNewPrivs = toU16(c[1])
elif pfs_seccomp < fill and n=="Seccomp:": p.seccomp = toU16(c[1])
elif pfs_specStoreBypass < fill and n=="Speculation_Store_Bypass:":
p.spec_Store_Bypass = c[1]
elif pfs_cpusAllowed<fill and n=="Cpus_allowed:":p.cpusAllowed=toU16(c[1])
elif pfs_cpusAllowedList < fill and n=="Cpus_allowed_list:":
p.cpusAllowedList = c[1]
elif pfs_memsAllowed<fill and n=="Mems_allowed:":p.memsAllowed=toU16(c[1])
elif pfs_memsAllowedList < fill and n=="Mems_allowed_list:":
p.memsAllowedList = c[1]
elif pfs_volunCtxtSwitch < fill and n=="voluntary_ctxt_switches:":
p.volunCtxtSwitch = toU64(c[1])
elif pfs_volunCtxtSwitch < fill and n=="nonvoluntary_ctxt_switches:":
p.nonVolunCtxtSwitch = toU64(c[1])
proc readIO*(p: var Proc; pr: string, fill: ProcFields): bool =
## Populate ``Proc p`` pfi_ fields requested in ``fill`` via /proc/PID/io.
## Returns false upon missing/corrupt file (eg. stale ``pid`` | not Linux).
result = true
(pr & "io").readFile buf
if buf.len == 0:
if pfi_rch in fill: p.rch = 0
if pfi_wch in fill: p.wch = 0
if pfi_syscr in fill: p.syscr = 0
if pfi_syscw in fill: p.syscw = 0
if pfi_rbl in fill: p.rbl = 0
if pfi_wbl in fill: p.wbl = 0
if pfi_wcancel in fill: p.wcancel = 0
return
var cols = newSeqOfCap[string](2)
for line in buf.split('\n'):
if line.len == 0: break
if line.splitr(cols, sep=' ') != 2: return false
let nm = cols[0]
if pfi_rch in fill and nm == "rchar:" : p.rch = toU64(cols[1])
if pfi_wch in fill and nm == "wchar:" : p.wch = toU64(cols[1])
if pfi_syscr in fill and nm == "syscr:" : p.syscr = toU64(cols[1])
if pfi_syscw in fill and nm == "syscw:" : p.syscw = toU64(cols[1])
if pfi_rbl in fill and nm == "read_bytes:" : p.rbl = toU64(cols[1])
if pfi_wbl in fill and nm == "write_bytes:": p.wbl = toU64(cols[1])
if pfi_wcancel in fill and nm == "cancelled_write_bytes:":
p.wcancel = toU64(cols[1])
proc readSchedStat*(p:var Proc; pr:string, fill:ProcFields, schedSt=false):bool=
## Fill `Proc p` pfss_ fields requested in `fill` via /proc/PID/schedstat. If
## (stale `pid`, not Linux, CONFIG_SCHEDSTATS=n, etc.) return false.
result = true
buf.setLen 0
if schedSt: (pr & "schedstat").readFile buf
if buf.len == 0:
if fill.all(pfss_sched, pf_utime, pf_stime):
p.pSched = int64(p.utime + p.stime)*10_000_000i64
if pfss_wait in fill: p.pWait = 0
if pfss_NOnCPU in fill: p.pNOnCPU = 0
return
var cols = newSeqOfCap[string](3)
for line in buf.split('\n'):
if line.len == 0: break
if line.splitr(cols, sep=' ') != 3: return false
if pfss_sched in fill: p.pSched = cols[0].toInt
if pfss_wait in fill: p.pWait = cols[1].toInt
if pfss_NOnCPU in fill: p.pNOnCPU = cols[2].toInt
proc readSMapsR*(p: var Proc; pr: string, fill: ProcFields): bool =
## Use /proc/PID/smaps_rollup to populate ``fill``-requested ``Proc p`` pfsr_
## fields. Returns false on missing/corrupt file (eg. stale ``pid``).
result = true
(pr & "smaps_rollup").readFile buf
if buf.len == 0: # %M is rare enough to not optimize setting to zero?
p.pss = 0; p.pss_dirty = 0; p.pss_anon = 0; p.pss_file = 0; p.shrClean = 0
p.shrDirty = 0; p.pvtClean = 0; p.pvtDirty = 0; p.refd = 0; p.anon = 0
p.lazyFree = 0; p.thpAnon = 0; p.thpShm = 0; p.thpFile = 0; p.thpShr = 0
p.thpPvt = 0; p.pss_swap = 0; p.pss_lock = 0
return # Likely a permissions problem
var cols = newSeqOfCap[string](2)
for line in buf.split('\n'):
if line.len == 0 or line.splitr(cols, seps=wspace) < 2: continue
let nm = cols[0]
template doF(eTag, sTag, f, e) = (if eTag in fill and nm == sTag: p.f = e)
doF pfsr_pss , "Pss:" , pss , cols[1].toU64*1024
doF pfsr_pss_dirty, "Pss_Dirty:" , pss_dirty, cols[1].toU64*1024
doF pfsr_pss_anon , "Pss_Anon:" , pss_anon , cols[1].toU64*1024
doF pfsr_pss_file , "Pss_File:" , pss_file , cols[1].toU64*1024
doF pfsr_shrClean , "Shared_Clean:" , shrClean , cols[1].toU64*1024
doF pfsr_shrDirty , "Shared_Dirty:" , shrDirty , cols[1].toU64*1024
doF pfsr_pvtClean , "Private_Clean:" , pvtClean , cols[1].toU64*1024
doF pfsr_pvtDirty , "Private_Dirty:" , pvtDirty , cols[1].toU64*1024
doF pfsr_refd , "Referenced:" , refd , cols[1].toU64*1024
doF pfsr_anon , "Anonymous:" , anon , cols[1].toU64*1024
doF pfsr_lazyFree , "LazyFree:" , lazyFree , cols[1].toU64*1024
doF pfsr_thpAnon , "AnonHugePages:" , thpAnon , cols[1].toU64*1024
doF pfsr_thpShm , "ShmemPmdMapped:" , thpShm , cols[1].toU64*1024
doF pfsr_thpFile , "FilePmdMapped:" , thpFile , cols[1].toU64*1024
doF pfsr_thpShr , "Shared_Hugetlb:" , thpShr , cols[1].toU64*1024
doF pfsr_thpPvt , "Private_Hugetlb:", thpPvt , cols[1].toU64*1024
doF pfsr_pss_swap , "SwapPss:" , pss_swap , cols[1].toU64*1024
doF pfsr_pss_lock , "Locked:" , pss_lock , cols[1].toU64*1024
let devNull* = open("/dev/null", fmWrite)
proc read*(p: var Proc; pid: string, fill: ProcFields, sneed: ProcSrcs,
schedSt=false): bool =
## Omnibus entry point. Fill ``Proc p`` with fields requested in ``fill`` via
## all required ``/proc`` files. Returns false upon missing/corrupt file (eg.
## stale ``pid`` | not Linux).
result = true # Ok unless early exit says elsewise
let pr = pid & "/"
if psDStat in sneed: # Must happen before p.st gets used @end
if stat(pr.cstring, p.st) == -1: return false
p.spid = pid; p.pid = toPid(pid) # Set pid fields themselves
p.pidPath.setLen 0
if psStat in sneed and not p.readStat(pr, fill): return false
if pfcl_cmdline in fill:
(pr & "cmdline").readFile buf
if buf.len > 0: # "exe" is best, but $0 / argv[0] is..
p.argv0 = buf.split('\0')[0] #..usually cmd in Bourne/Korn family.
p.cmdLine = buf.cmdClean
if pfen_environ in fill: (pr&"environ").readFile buf; p.environ=buf.split '\0'
if pfr_root in fill: p.root = readlink(pr & "root", devNull)
if pfc_cwd in fill: p.cwd = readlink(pr & "cwd" , devNull)
if pfe_exe in fill: p.exe = readlink(pr & "exe" , devNull)
if psStatm in sneed and not p.readStatm( pr, fill): return false
if psStatus in sneed and not p.readStatus(pr, fill): return false
if pfw_wchan in fill: (pr & "wchan").readFile buf; p.wchan = buf
if psIO in sneed and not p.readIO(pr, fill): return false
if psSchedSt in sneed: discard p.readSchedStat(pr, fill, schedSt)
if psSMapsR in sneed and not p.readSMapsR(pr, fill): return false
#Maybe faster to readlink, remove tag:[] in tag:[inode], decimal->binary.
if pfn_ipc in fill: p.nIpc =st_inode(pr&"ns/ipc", devNull)
if pfn_mnt in fill: p.nMnt =st_inode(pr&"ns/mnt", devNull)
if pfn_net in fill: p.nNet =st_inode(pr&"ns/net", devNull)
if pfn_pid in fill: p.nPid =st_inode(pr&"ns/pid", devNull)
if pfn_user in fill: p.nUser =st_inode(pr&"ns/user", devNull)
if pfn_uts in fill: p.nUts =st_inode(pr&"ns/uts", devNull)
if pfn_cgroup in fill: p.nCgroup =st_inode(pr&"ns/cgroup", devNull)
if pfn_pid4Kids in fill:p.nPid4Kids=st_inode(pr&"ns/pid_for_children",devNull)
if pfd_0 in fill: p.fd0 = readlink(pr & "fd/0", devNull)
if pfd_1 in fill: p.fd1 = readlink(pr & "fd/1", devNull)
if pfd_2 in fill: p.fd2 = readlink(pr & "fd/2", devNull)
if pfd_3 in fill: p.fd3 = readlink(pr & "fd/3", devNull)
if pfd_4 in fill: p.fd4 = readlink(pr & "fd/4", devNull)
if pfd_5 in fill: p.fd5 = readlink(pr & "fd/5", devNull)
if pfd_6 in fill: p.fd6 = readlink(pr & "fd/6", devNull)
template doInt(x, y, z: untyped) {.dirty.} =
if x in fill: (pr & y).readFile buf; z = buf.strip.parseInt.cint
doInt(pfo_adj , "oom_adj" , p.oom_adj )
doInt(pfo_score_adj, "oom_score_adj", p.oom_score_adj)
if pffs_usr in fill: p.usr = usrs.getOrDefault(p.st.st_uid, $p.st.st_uid)
if pffs_grp in fill: p.grp = grps.getOrDefault(p.st.st_gid, $p.st.st_gid)
if pfs_usrs in fill:
for ui in p.uids: p.usrs.add usrs.getOrDefault(ui, $ui)
if pfs_grps in fill:
for gi in p.gids: p.grps.add grps.getOrDefault(gi, $gi)
macro save(p: Proc, fs: varargs[untyped]) =
result = newStmtList()
for f in fs: result.add(quote do: (let `f` = p.`f`))
macro rest(p: Proc, fs: varargs[untyped]) =
result = newStmtList()
for f in fs: result.add(quote do: (p.`f` = `f`; p.`f`.setLen 0))
proc clear(p: var Proc, fill: ProcFields, sneed: ProcSrcs) =
# Re-init all that above `read` populates to allow obj/mem re-use. To not leak
# (& also re-use) seqs & strings we must save, zeroMem, then restore them.
#XXX Can save memory write traffic by replicating tests both before & after.
save p, kind, pidPath, environ, usrs, grps # seq[Pid],seq[string],then strings
save p, spid,cmd,usr,grp, cmdLine,argv0, root, cwd, exe, name,umask,stateS,
sigQ,sigPnd,shdPnd,sigBlk,sigIgn,sigCgt,
capInh,capPrm,capEff,capBnd,capAmb, spec_Store_Bypass,
cpusAllowedList,memsAllowedList, wchan, fd0,fd1,fd2,fd3,fd4,fd5,fd6
zeroMem p.addr, p.sizeof
rest p, kind, pidPath, environ, usrs, grps # seq[Pid],seq[string],then strings
rest p, spid,cmd,usr,grp, cmdLine,argv0, root, cwd, exe, name,umask,stateS,
sigQ,sigPnd,shdPnd,sigBlk,sigIgn,sigCgt,
capInh,capPrm,capEff,capBnd,capAmb, spec_Store_Bypass,
cpusAllowedList,memsAllowedList, wchan, fd0,fd1,fd2,fd3,fd4,fd5,fd6
proc merge*(p: var Proc; q: Proc, fill: ProcFields, overwriteSetValued=false) =
## Merge ``fill`` fields for ``q`` on to those for ``p``. Summing makes sense
## for fields like ``utime``, min|max for eg ``t0``, or bool-aggregated for eg
## ``foo``. When there is no natural aggregation the merged value is really
## set-valued (eg, ``tty``). In such cases, by default, the first Proc wins
## the field unless ``overwriteSetValued`` is ``true``.
if p.pidPath.len > q.pidPath.len: p.pidPath = q.pidPath #XXX Shortest? Common?
p.ppid0 = if p.pidPath.len > 0: p.pidPath[^1] else: 0
if pf_minflt in fill: p.minflt += q.minflt
if pf_cminflt in fill: p.cminflt += q.cminflt
if pf_majflt in fill: p.majflt += q.majflt
if pf_cmajflt in fill: p.cmajflt += q.cmajflt
if pf_utime in fill: p.utime += q.utime
if pf_stime in fill: p.stime += q.stime
if pf_cutime in fill: p.cutime += q.cutime
if pf_cstime in fill: p.cstime += q.cstime
if pfss_sched in fill: p.pSched += q.pSched
if pfss_wait in fill: p.pWait += q.pWait
if pf_utime in fill: p.t0 = min(p.t0, q.t0)
if pf_exitCode in fill: p.exitCode += q.exitCode
if pf_nThr in fill: p.nThr += q.nThr
if pffs_uid in fill: p.st.st_uid=min(p.st.st_uid, q.st.st_uid)
if pffs_gid in fill: p.st.st_gid=min(p.st.st_gid, q.st.st_gid)
if pfsm_dty in fill: p.dty += q.dty
if pfs_threads in fill: p.threads += q.threads
if pfs_vmPeak in fill: p.vmPeak = max(p.vmPeak, q.vmPeak)
if pfs_vmHWM in fill: p.vmHWM = max(p.vmHWM , q.vmHWM )
if pfs_vmLck in fill: p.vmLck += q.vmLck
if pfs_vmPin in fill: p.vmPin += q.vmPin
if pfs_volunCtxtSwitch in fill: p.volunCtxtSwitch += q.volunCtxtSwitch
if pfs_nonVolunCtxtSwitch in fill:p.nonVolunCtxtSwitch += q.nonVolunCtxtSwitch
if pfi_rch in fill: p.rch += q.rch
if pfi_wch in fill: p.wch += q.wch
if pfi_syscr in fill: p.syscr += q.syscr
if pfi_syscw in fill: p.syscw += q.syscw
if pfi_rbl in fill: p.rbl += q.rbl
if pfi_wbl in fill: p.wbl += q.wbl
if pfi_wcancel in fill: p.wcancel += q.wcancel
if overwriteSetValued: #XXX trickier fields: mem,capabilities,signals,sched,..
if pf_tty in fill: p.tty = q.tty
if pf_cmd in fill: p.cmd = q.cmd
if pfcl_cmdline in fill: p.cmdLine = q.cmdLine
if pfw_wchan in fill: p.wchan = q.wchan
if pf_processor in fill: p.processor = q.processor
if pffs_usr in fill: p.usr = q.usr
if pffs_grp in fill: p.grp = q.grp
if pfs_name in fill: p.name = q.name
proc minusEq*(p: var Proc, q: Proc, fill: ProcFields) =
## For temporal differences, set ``p.field -= q`` for all fields in ``fill``
## for fields where summing makes sense in ``merge``.
template doInt(e, f: untyped) {.dirty.} =
if e in fill: p.f -= q.f
doInt(pf_rss , rss )
doInt(pfsr_pss , pss )
doInt(pf_minflt , minflt )
doInt(pf_cminflt , cminflt )
doInt(pf_majflt , majflt )
doInt(pf_cmajflt , cmajflt )
doInt(pf_utime , utime )
doInt(pf_stime , stime )
doInt(pf_cutime , cutime )
doInt(pf_cstime , cstime )
doInt(pfss_sched , pSched )
doInt(pfss_wait , pWait )
doInt(pf_exitCode , exitCode )
doInt(pf_nThr , nThr )
doInt(pfsm_size , size )
doInt(pfsm_res , res )
doInt(pfsm_share , share )
doInt(pfsm_txt , txt )
doInt(pfsm_lib , lib )
doInt(pfsm_dat , dat )
doInt(pfsm_dty , dty )
doInt(pfs_threads , threads )
doInt(pfs_vmPeak , vmPeak )
doInt(pfs_vmSize , vmSize )
doInt(pfs_vmLck , vmLck )
doInt(pfs_vmPin , vmPin )
doInt(pfs_vmHWM , vmHWM )
doInt(pfs_vmRSS , vmRSS )
doInt(pfs_rssAnon , rssAnon )
doInt(pfs_rssFile , rssFile )
doInt(pfs_rssShmem , rssShmem )
doInt(pfs_volunCtxtSwitch , volunCtxtSwitch )
doInt(pfs_nonVolunCtxtSwitch, nonVolunCtxtSwitch)
doInt(pfi_rch , rch )
doInt(pfi_wch , wch )
doInt(pfi_syscr , syscr )
doInt(pfi_syscw , syscw )
doInt(pfi_rbl , rbl )
doInt(pfi_wbl , wbl )
doInt(pfi_wcancel , wcancel )
#------------ NON-PROCESS SPECIFIC /proc PARSING
proc procPidMax*(): int = ## Parse & return len("/proc/sys/kernel/pid_max").
"sys/kernel/pid_max".readFile buf; buf.strip.len
proc procUptime*(): culong =
## System uptime in jiffies (there are 100 jiffies per second)
"uptime".readFile buf
let decimal = buf.find('.')
if decimal == -1: return
buf[decimal..decimal+1] = buf[decimal+1..decimal+2]
buf[decimal+2] = ' '
var x: int
discard parseInt(buf, x)
x.culong
proc procMemInfo*(): MemInfo =
## /proc/meminfo fields (in bytes or pages if specified).
"meminfo".readFile buf
proc toU(s: string, unit=1): uint {.inline.} = toU64(s, unit).uint
var nm = ""
for line in buf.split('\n'):
var i = 0
for col in line.splitWhitespace:
if i == 0: nm = col
else:
if nm=="MemTotal:" : result.MemTotal = toU(col, 1024)
elif nm=="MemFree:" : result.MemFree = toU(col, 1024)
elif nm=="MemAvailable:" : result.MemAvailable = toU(col, 1024)
elif nm=="Buffers:" : result.Buffers = toU(col, 1024)
elif nm=="Cached:" : result.Cached = toU(col, 1024)
elif nm=="SwapCached:" : result.SwapCached = toU(col, 1024)
elif nm=="Active:" : result.Active = toU(col, 1024)
elif nm=="Inactive:" : result.Inactive = toU(col, 1024)
elif nm=="Active(anon):" : result.ActiveAnon = toU(col, 1024)
elif nm=="Inactive(anon):" : result.InactiveAnon = toU(col, 1024)
elif nm=="Active(file):" : result.ActiveFile = toU(col, 1024)
elif nm=="Inactive(file):" : result.InactiveFile = toU(col, 1024)
elif nm=="Unevictable:" : result.Unevictable = toU(col, 1024)
elif nm=="Mlocked:" : result.Mlocked = toU(col, 1024)
elif nm=="SwapTotal:" : result.SwapTotal = toU(col, 1024)
elif nm=="SwapFree:" : result.SwapFree = toU(col, 1024)
elif nm=="Dirty:" : result.Dirty = toU(col, 1024)
elif nm=="Writeback:" : result.Writeback = toU(col, 1024)
elif nm=="AnonPages:" : result.AnonPages = toU(col, 1024)
elif nm=="Mapped:" : result.Mapped = toU(col, 1024)
elif nm=="Shmem:" : result.Shmem = toU(col, 1024)
elif nm=="KReclaimable:" : result.KReclaimable = toU(col, 1024)
elif nm=="Slab:" : result.Slab = toU(col, 1024)
elif nm=="SReclaimable:" : result.SReclaimable = toU(col, 1024)
elif nm=="SUnreclaim:" : result.SUnreclaim = toU(col, 1024)
elif nm=="KernelStack:" : result.KernelStack = toU(col, 1024)
elif nm=="PageTables:" : result.PageTables = toU(col, 1024)
elif nm=="NFS_Unstable:" : result.NFS_Unstable = toU(col, 1024)
elif nm=="Bounce:" : result.Bounce = toU(col, 1024)
elif nm=="WritebackTmp:" : result.WritebackTmp = toU(col, 1024)
elif nm=="CommitLimit:" : result.CommitLimit = toU(col, 1024)
elif nm=="Committed_AS:" : result.Committed_AS = toU(col, 1024)
elif nm=="VmallocTotal:" : result.VmallocTotal = toU(col, 1024)
elif nm=="VmallocUsed:" : result.VmallocUsed = toU(col, 1024)
elif nm=="VmallocChunk:" : result.VmallocChunk = toU(col, 1024)
elif nm=="Percpu:" : result.Percpu = toU(col, 1024)
elif nm=="AnonHugePages:" : result.AnonHugePages = toU(col, 1024)
elif nm=="ShmemHugePages:" : result.ShmemHugePages = toU(col, 1024)
elif nm=="ShmemPmdMapped:" : result.ShmemPmdMapped = toU(col, 1024)
elif nm=="CmaTotal:" : result.CmaTotal = toU(col, 1024)
elif nm=="CmaFree:" : result.CmaFree = toU(col, 1024)
elif nm=="HugePages_Total:": result.HugePagesTotal = toU(col)
elif nm=="HugePages_Free:" : result.HugePagesFree = toU(col)
elif nm=="HugePages_Rsvd:" : result.HugePagesRsvd = toU(col)
elif nm=="HugePages_Surp:" : result.HugePagesSurp = toU(col)
elif nm=="Hugepagesize:" : result.Hugepagesize = toU(col, 1024)
elif nm=="Hugetlb:" : result.Hugetlb = toU(col, 1024)
elif nm=="DirectMap4k:" : result.DirectMap4k = toU(col, 1024)
elif nm=="DirectMap2M:" : result.DirectMap2M = toU(col, 1024)
elif nm=="DirectMap1G:" : result.DirectMap1G = toU(col, 1024)
break
i.inc
proc parseCPUInfo*(rest: string): CPUInfo =
let col = rest.splitWhitespace
result.user = parseInt(col[0])
result.nice = parseInt(col[1])
result.system = parseInt(col[2])
result.idle = parseInt(col[3])
result.iowait = parseInt(col[4])
result.irq = parseInt(col[5])
result.softirq = parseInt(col[6])
result.steal = parseInt(col[7])
result.guest = parseInt(col[8])
result.guest_nice = parseInt(col[9])
proc parseSoftIRQs*(rest: string): SoftIRQs =
let col = rest.splitWhitespace #"softirq" == [0]
result.all = parseInt(col[0])
result.hi = parseInt(col[1])
result.timer = parseInt(col[2])
result.net_tx = parseInt(col[3])
result.net_rx = parseInt(col[4])
result.blk = parseInt(col[5])
result.irq_poll = parseInt(col[6])
result.tasklet = parseInt(col[7])
result.sched = parseInt(col[8])
result.hrtimer = parseInt(col[9])
result.rcu = parseInt(col[10])
proc procSysStat*(): SysStat =
"stat".readFile buf
for line in buf.split('\n'):
let cols = line.splitWhitespace(maxSplit=1)
if cols.len != 2: continue
let nm = cols[0]
let rest = cols[1]
if nm.startsWith("cpu"): result.cpu.add rest.parseCPUInfo
elif nm == "intr": result.interrupts =
parseInt(rest.splitWhitespace(maxSplit=1)[0])
elif nm == "ctxt": result.contextSwitches = parseInt(rest)
elif nm == "btime": result.bootTime = parseInt(rest)
elif nm == "processes": result.procs = parseInt(rest)
elif nm == "procs_running": result.procsRunnable = parseInt(rest)
elif nm == "procs_blocked": result.procsBlocked = parseInt(rest)
elif nm == "softirq": result.softIRQ = rest.parseSoftIRQs()
proc parseNetStat*(cols: seq[string]): NetStat =
result.bytes = parseInt(cols[0])
result.packets = parseInt(cols[1])
result.errors = parseInt(cols[2])
result.drops = parseInt(cols[3])
result.fifo = parseInt(cols[4])
result.frame = parseInt(cols[5])
result.compressed = parseInt(cols[6])
result.multicast = parseInt(cols[7])
proc procNetDevStats*(): seq[NetDevStat] =
var i = 0
var row: NetDevStat
"net/dev".readFile buf
for line in buf.split('\n'):
if line.len < 1: continue
i.inc
if i < 3: continue
let cols = line.splitWhitespace
if cols.len < 17:
stderr.write "unexpected format in " & "net/dev\n"
return
row.name = cols[0]
if row.name.len > 0 and row.name[^1] == ':':
row.name.setLen row.name.len - 1
row.rcvd = parseNetStat(cols[1..8])
row.sent = parseNetStat(cols[9..16])
result.add row.move
proc parseIOStat*(cols: seq[string]): DiskIOStat =
result.nIO = parseInt(cols[0])
result.nMerge = parseInt(cols[1])
result.nSector = parseInt(cols[2])
result.msecs = parseInt(cols[3])
proc procDiskStats*(): seq[DiskStat] =
var row: DiskStat
"diskstats".readFile buf
for line in buf.split('\n'):
if line.len < 1: continue
let cols = line.splitWhitespace
if cols.len < 18:
stderr.write "unexpected format in diskstats\n"
return
row.major = parseInt(cols[0])
row.minor = parseInt(cols[1])
row.name = cols[2]
row.reads = cols[3..6].parseIOStat()
row.writes = cols[7..10].parseIOStat()
row.inFlight = parseInt(cols[11])
row.ioTicks = parseInt(cols[12])
row.timeInQ = parseInt(cols[13])
row.cancels = cols[14..17].parseIOStat()
result.add row.move
proc procLoadAvg*(): LoadAvg =
let cols = readFile("loadavg").splitWhitespace()
if cols.len != 5: return
result.m1 = cols[0]
result.m5 = cols[1]
result.m15 = cols[2]
result.mostRecent = parseInt(cols[4]).Pid
let runTotal = cols[3].split('/')
if runTotal.len != 2: return
result.runnable = parseInt(runTotal[0])
result.total = parseInt(runTotal[1])
#------------ RELATED PROCESS MGMT APIs
proc usrToUid*(usr: string): Uid =
## Convert string|numeric user designations to Uids via usrs
if usr.len == 0: return 999.Uid
if usr[0].isDigit: return toInt(usr).Uid
if usrs.len == 0: usrs = users()