Debian Codegraph @

atopgpud

raw symbols SCIP
1 #!/usr/bin/python3 -Es
2
3 # ==============================================================
4 # Daemon that gathers statistical information from all
5 # NVIDIA GPUs in the current system. Since the GPU maintains the
6 # busy percentages only over the last second, this daemon gathers
7 # the statistics each second and maintains cumulative counters,
8 # globally and per process.
9 #
10 # Client processes can connect to this daemon via a UNIX domain
11 # socket with the abstract path name "atopgpud_nvidia" and send
12 # requests of two bytes, consisting of one byte
13 # request code followed by one byte API version number.
14 # The request code can be 'T' to obtain the GPU types or 'S' to
15 # obtain all statistical counters.
16 # The response of the daemon starts with a 4-byte integer. The
17 # first byte is the version of the response format and the
18 # subsequent three bytes indicate the length (big endian) of the
19 # response string that follows. See the formatters for the layout
20 # of the response string, later on in this source code.
21 #
22 # Dependencies: pip/pip3 install nvidia-ml-py
23 # --------------------------------------------------------------
24 # Author: Gerlof Langeveld
25 # Date: July 2018 - initial
26 # August 2025 - UNIX domain socket instead of IPv6 socket
27 # August 2025 - redesign of GPU busy percentage gathering
28 # August 2025 - no need to run with specific privileges
29 #
30 # Copyright (C) 2018,2025 Gerlof Langeveld
31 #
32 # This program is free software; you can redistribute it and/or modify it
33 # under the terms of the GNU General Public License as published by the
34 # Free Software Foundation; either version 2, or (at your option) any
35 # later version.
36 #
37 # This program is distributed in the hope that it will be useful, but
38 # WITHOUT ANY WARRANTY; without even the implied warranty of
39 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
40 # See the GNU General Public License for more details.
41 #
42 # You should have received a copy of the GNU General Public License
43 # along with this program; if not, write to the Free Software
44 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
45 # ==============================================================
46
47 import os
48 import sys
49 import time
50 import socket
51 import struct
52 import logging
53 import logging.handlers as loghand
54 import threading
55
56 SOCKPATH = b"\0atopgpud_nvidia"
57
58 COMPUTE = 1 # task support bit value
59 GRAPHIC = 2 # task support bit value
60
61 HIGHSTAMP = 1000
62
63 # =================================
64 # GPU related bookkeeping
65 # =================================
66 gpulist = [] # list with per-GPU bookkeeping
67 cliterm = {} # dict with one entry per client (client
68 # socket as key), that contains a dict with
69 # the terminated per-process bookkeepings
70 # that still have to be received by this client
71 # (pid of terminated process as key)
72
73 gpulock = None # mutex for access to gpulist/cliterm
74
75
76 # =================================
77 # per-GPU class
78 # =================================
79 class Stats(object): pass # generic statistics container
80
81 class GpuProp(object):
82 ###############################
83 # initialization method to setup
84 # properties
85 ###############################
86 def __init__(self, num):
87 gpuhandle = pynvml.nvmlDeviceGetHandleByIndex(num)
88 pciInfo = pynvml.nvmlDeviceGetPciInfo(gpuhandle)
89
90 self.gpuhandle = gpuhandle
91 self.stats = Stats()
92
93 self.stats.busid = pciInfo.busId
94 self.stats.devname = pynvml.nvmlDeviceGetName(gpuhandle)
95
96 # nvml backward compatibility
97 if type(self.stats.busid) == bytes:
98 self.stats.busid = self.stats.busid.decode('ascii', errors='replace')
99 if type(self.stats.devname) == bytes:
100 self.stats.devname = self.stats.devname.decode('ascii', errors='replace')
101
102 self.stats.devname = self.stats.devname.replace(' ', '_')
103
104 self.stats.tasksupport = 0 # process stats support
105
106 try:
107 procinfo = pynvml.nvmlDeviceGetComputeRunningProcesses(gpuhandle)
108 self.stats.tasksupport |= COMPUTE # compute proces support
109 except Exception:
110 pass # no compute process support
111
112 try:
113 procinfo = pynvml.nvmlDeviceGetGraphicsRunningProcesses(gpuhandle)
114 self.stats.tasksupport |= GRAPHIC # graphic process support
115 except Exception:
116 pass # no graphic process support
117
118 self.stats.gpupercnow = 0 # perc of time that GPU was busy
119 self.stats.mempercnow = 0 # perc of time that memory was rd/wr
120
121 self.stats.memtotalnow = 0 # in Kb
122 self.stats.memusednow = 0 # in Kb
123
124 self.stats.gpusamples = 0
125 self.stats.gpuperccum = 0 # perc of time that GPU was busy
126 self.stats.memperccum = 0 # perc of time that memory was rd/wr
127 self.stats.memusedcum = 0 # in KiB
128
129 self.stats.procstats = {} # stats of active processes (key = pid)
130
131 ###############################
132 # method to fetch counters and values
133 ###############################
134 def readstats(self):
135 global HIGHSTAMP
136
137 self.stats.gpusamples += 1
138
139 # -----------------------------
140 # get rates (utilization percentages)
141 # -----------------------------
142 try:
143 rates = pynvml.nvmlDeviceGetUtilizationRates(self.gpuhandle)
144
145 self.stats.gpupercnow = rates.gpu
146 self.stats.mempercnow = rates.memory
147 self.stats.gpuperccum += rates.gpu
148 self.stats.memperccum += rates.memory
149 except pynvml.NVMLError as err:
150 self.stats.gpupercnow = -1
151 self.stats.mempercnow = -1
152 self.stats.gpuperccum = -1
153 self.stats.memperccum = -1
154
155 # -----------------------------
156 # get memory occupation GPU-wide
157 # -----------------------------
158 try:
159 meminfo = pynvml.nvmlDeviceGetMemoryInfo(self.gpuhandle)
160
161 self.stats.memtotalnow = meminfo.total // 1024
162 self.stats.memusednow = meminfo.used // 1024
163 self.stats.memusedcum += meminfo.used // 1024 # in KiB
164 except pynvml.NVMLError as err:
165 pass
166
167 # -----------------------------
168 # get per-process statistics
169 # -----------------------------
170 try:
171 if self.stats.tasksupport & COMPUTE:
172 cprocinfo = pynvml.nvmlDeviceGetComputeRunningProcesses(self.gpuhandle)
173
174 for proc in cprocinfo:
175 proc.type = 'C'
176
177 if self.stats.tasksupport & GRAPHIC:
178 gprocinfo = pynvml.nvmlDeviceGetGraphicsRunningProcesses(self.gpuhandle)
179
180 for proc in gprocinfo:
181 proc.type = 'G'
182
183 procinfo = cprocinfo + gprocinfo
184
185 # -------------------------
186 # build list with pids from
187 # the previous interval
188 # -------------------------
189 actprocs = list(self.stats.procstats.keys())
190
191 # -------------------------
192 # handle proc stats of this
193 # interval
194 # -------------------------
195 for proc in procinfo:
196 pid = proc.pid
197
198 # ---------------------
199 # new process?
200 # create new stats
201 # ---------------------
202 if pid not in actprocs:
203 self.stats.procstats[pid] = Stats()
204
205 self.stats.procstats[pid].samples = 0
206 self.stats.procstats[pid].type = 'U' # unknown
207
208 self.stats.procstats[pid].memnow = 0 # in KiB
209 self.stats.procstats[pid].memcum = 0 # in KiB
210
211 self.stats.procstats[pid].gpubusy = -1
212 self.stats.procstats[pid].membusy = -1
213 self.stats.procstats[pid].gpubusycum = -1
214 self.stats.procstats[pid].membusycum = -1
215 else:
216 actprocs.remove(pid) # remove active pid from list
217
218 # ---------------------
219 # maintain proc stats
220 # ---------------------
221 self.stats.procstats[pid].samples += 1
222 self.stats.procstats[pid].type = proc.type
223
224 if proc.usedGpuMemory:
225 self.stats.procstats[pid].memnow = proc.usedGpuMemory // 1024
226 self.stats.procstats[pid].memcum += proc.usedGpuMemory // 1024
227
228 # -------------------------
229 # get average GPU utilization
230 # and memory utiliation for
231 # all active processes on GPU
232 # -------------------------
233 try:
234 procutils = pynvml.nvmlDeviceGetProcessUtilization(self.gpuhandle, HIGHSTAMP)
235
236 if procutils and len(procutils) > 0:
237 for proc in procutils:
238 if HIGHSTAMP < proc.timeStamp:
239 HIGHSTAMP = proc.timeStamp
240
241 if proc.pid in self.stats.procstats:
242 self.stats.procstats[proc.pid].gpubusy = proc.smUtil
243 self.stats.procstats[proc.pid].membusy = proc.memUtil
244
245 self.stats.procstats[proc.pid].gpubusycum += proc.smUtil
246 self.stats.procstats[proc.pid].membusycum += proc.memUtil
247 except Exception as e:
248 pass
249
250 # -------------------------
251 # determine which processes
252 # have terminated since
253 # previous sample
254 # -------------------------
255 for pid in actprocs:
256 for client in cliterm:
257 cliterm[client][pid] = self.stats.procstats[pid]
258
259 del self.stats.procstats[pid]
260
261 except pynvml.NVMLError as err:
262 pass
263
264
265 ###############################
266 # obtain current statistics
267 ###############################
268 def getstats(self):
269 return self.stats
270
271
272 # =================================
273 # Main function
274 # =================================
275 def main():
276 global gpulock
277 gpulock = threading.Lock() # mutex for access to gpulist/cliterm
278
279 # -----------------------------
280 # initialize GPU access,
281 # specifically to detect of it
282 # succeeds
283 # -----------------------------
284 try:
285 pynvml.nvmlInit()
286 except Exception:
287 logging.error("Shared lib 'libnvidia-ml' probably not installed!")
288 sys.exit()
289
290 # -----------------------------
291 # open UNIX domain stream socket
292 # -----------------------------
293 try:
294 mysock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
295 except Exception as sockex:
296 logging.error("Socket creation fails")
297 sys.exit(1)
298
299 # -----------------------------
300 # bind to abstract pathname and
301 # make socket passive
302 # -----------------------------
303 try:
304 mysock.bind(SOCKPATH)
305 mysock.listen(32)
306 except Exception as sockex:
307 logging.error("Socket binding to path %s fails", SOCKPATH)
308 sys.exit(1)
309
310 # -----------------------------
311 # initialize GPU access for the
312 # child process
313 # -----------------------------
314 try:
315 pynvml.nvmlInit()
316 except Exception:
317 pass
318
319 # -----------------------------
320 # determine number of GPUs in
321 # this system
322 # -----------------------------
323 gpunum = pynvml.nvmlDeviceGetCount()
324 logging.info("Number of GPUs: %d", gpunum)
325
326 if gpunum == 0:
327 logging.info("Terminated (no GPUs available)")
328 sys.exit()
329
330 # -----------------------------
331 # initialize per-GPU bookkeeping
332 # -----------------------------
333 for i in range(gpunum):
334 gpulist.append( GpuProp(i) )
335
336 # -----------------------------
337 # kick off new thread to fetch
338 # statistics periodically
339 # -----------------------------
340 t = threading.Thread(target=gpuscanner, args=(1,))
341 t.daemon = True
342 t.start()
343
344 logging.info("Initialization succeeded")
345
346 # -----------------------------
347 # main thread:
348 # await connect of client
349 # -----------------------------
350 while True:
351 newsock, peeraddr = mysock.accept()
352
353 # -------------------------
354 # create new thread to
355 # serve this client
356 # -------------------------
357 t = threading.Thread(target=serveclient, args=(newsock, peeraddr))
358 t.daemon = True
359 t.start()
360
361
362 # ===========================================
363 # Thread start function:
364 # Serve new client that has just connected.
365 # -------------------------------------------
366 # Protocol between client and server:
367 #
368 # - client transmits request
369 # consisting of two bytes
370 #
371 # byte 0: type of request
372 # 'S' get statistical counters
373 # 'T' get type of each GPU
374 #
375 # byte 1: integer version number
376 # response layout might change
377 # so the client asks for a
378 # specific response version
379 #
380 # - server transmits response
381 # consisting of a four bytes integer
382 # in big endian byte order
383 #
384 # byte 0: version number, preferably
385 # as requested by the client
386 #
387 # byte 1-3: length of the response string
388 # that follows
389 #
390 # followed by the response string that is
391 # version specific (see gpuformatters)
392 # ===========================================
393 def serveclient(sock, peer):
394 # -----------------------------
395 # create per client bookkeeping
396 # for terminated processes
397 # -----------------------------
398 with gpulock:
399 cliterm[sock] = {}
400
401 # -----------------------------
402 # main loop
403 # -----------------------------
404 while True:
405 # -------------------------
406 # wait for request
407 # -------------------------
408 try:
409 rcvbuf = sock.recv(20)
410 except Exception as sockex:
411 logging.error("Receive error: %s", sockex)
412 sock.close()
413 break
414
415 # -------------------------
416 # connection closed by peer?
417 # -------------------------
418 if not rcvbuf:
419 sock.close()
420 break
421
422 logging.debug("Received: %s", rcvbuf)
423
424 # -------------------------
425 # request has wrong length?
426 # -------------------------
427 if len(rcvbuf) != 2:
428 logging.error('Wrong request length: %d', len(rcvbuf))
429 sock.close()
430 break
431
432 # -------------------------
433 # valid request:
434 # get statistical counters?
435 # -------------------------
436 command = chr(rcvbuf[0])
437 version = rcvbuf[1]
438
439 if command == 'S':
440 if version == 0 or version >= len(gpuformatters):
441 version = len(gpuformatters)-1
442
443 xmitbuf = gpuformatters[version](sock).encode('ascii',
444 errors='replace')
445
446 # -------------------------
447 # valid request:
448 # get GPU types?
449 # -------------------------
450 elif command == 'T':
451 if version == 0 or version >= len(gpudevnames):
452 version = len(gpudevnames)-1
453
454 xmitbuf = gpudevnames[version]().encode('ascii', errors='replace')
455
456 # -------------------------
457 # invalid request!
458 # -------------------------
459 else:
460 logging.error('Wrong request from client: %s', command)
461 sock.close()
462 break
463
464 # -------------------------
465 # transmit GPU statistics
466 # as bytes
467 # -------------------------
468 prelude = struct.pack(">I", (version << 24) + len(xmitbuf))
469
470 try:
471 sock.send(prelude)
472 sock.send(xmitbuf)
473
474 logging.debug("Send: %s", prelude + xmitbuf)
475 except Exception as sockex:
476 logging.error("Send error: %s", sockex)
477 sock.close()
478 break
479
480 # -----------------------------
481 # delete per client bookkeeping
482 # of terminated processes
483 # -----------------------------
484 with gpulock:
485 del cliterm[sock]
486
487 # -----------------------------
488 # END OF CLIENT THREAD
489 # -----------------------------
490
491
492 # =================================
493 # Generate sequence of device names
494 # =================================
495 def gpudevname_v1():
496 # -----------------------------
497 # main loop:
498 # - get device name of every GPU
499 # - convert into one string
500 # with format:
501 # numgpus@busid devname tasksupport@busid devname tasksupport@...
502 # -----------------------------
503 strbuf = str( len(gpulist) )
504
505 with gpulock:
506 for i, gpu in enumerate(gpulist):
507 s = gpu.getstats()
508 strbuf += "@{:s} {:s} {:d}".format(s.busid, s.devname, s.tasksupport)
509
510 return strbuf
511
512 gpudevnames = [None, gpudevname_v1, gpudevname_v1]
513
514
515 # =================================
516 # Convert statistics of all GPUs
517 # into parseable string
518 # =================================
519 def gpuformatter_v1(clisock):
520 # -----------------------------
521 # main loop:
522 # - get statistics for every GPU
523 # - convert stats to one string
524 # with format:
525 # numgpus@gpu0 stats#pid stats#pid stats@gpu1 stats#pid stats@....
526 # -----------------------------
527 strbuf = ""
528
529 with gpulock:
530 for i, gpu in enumerate(gpulist):
531 s = gpu.getstats()
532
533 # ---------------------
534 # generic GPU stats
535 # ---------------------
536 strbuf += "@{:d} {:d} {:d} {:d} {:d} {:d} {:d} {:d}".format(
537 s.gpupercnow, s.mempercnow,
538 s.memtotalnow, s.memusednow, s.gpusamples,
539 s.gpuperccum, s.memperccum, s.memusedcum);
540
541 # ---------------------
542 # active processes for
543 # this GPU
544 # ---------------------
545 for pid, stat in s.procstats.items():
546 strbuf += "#A {:d} {:d} {:d} {:d} {:d} {:d} {:d}".format(pid,
547 stat.gpubusy, stat.membusy, 0,
548 stat.memnow, stat.memcum, stat.samples)
549
550 # ---------------------
551 # terminated processes
552 # for this GPU
553 # ---------------------
554 for pid, stat in cliterm[clisock].items():
555 strbuf += "#E {:d} {:d} {:d} {:d} {:d} {:d} {:d}".format(pid,
556 stat.gpubusy, stat.membusy, 0,
557 stat.memnow, stat.memcum, stat.samples)
558
559 cliterm[clisock].clear()
560
561
562 return strbuf
563
564
565 def gpuformatter_v2(clisock):
566 # -----------------------------
567 # main loop:
568 # - get statistics for every GPU
569 # - convert stats to one string
570 # with format:
571 # numgpus@gpu0 stats#pid stats#pid stats@gpu1 stats#pid stats@....
572 # -----------------------------
573 strbuf = ""
574
575 with gpulock:
576 for i, gpu in enumerate(gpulist):
577 s = gpu.getstats()
578
579 # ---------------------
580 # generic GPU stats
581 # ---------------------
582 strbuf += "@{:d} {:d} {:d} {:d} {:d} {:d} {:d} {:d}".format(
583 s.gpupercnow, s.mempercnow,
584 s.memtotalnow, s.memusednow, s.gpusamples,
585 s.gpuperccum, s.memperccum, s.memusedcum);
586
587 # ---------------------
588 # active processes for
589 # this GPU
590 # ---------------------
591 for pid, stat in s.procstats.items():
592 strbuf += "#A {:d} {:s} {:d} {:d} {:d} {:d} {:d}".format(pid,
593 stat.type,
594 stat.gpubusycum, stat.membusycum,
595 stat.memnow, stat.memcum, stat.samples)
596
597 # ---------------------
598 # terminated processes
599 # for this GPU
600 # ---------------------
601 for pid, stat in cliterm[clisock].items():
602 strbuf += "#E {:d} {:s} {:d} {:d} {:d} {:d} {:d}".format(pid,
603 stat.type,
604 stat.gpubusycum, stat.membusycum,
605 stat.memnow, stat.memcum, stat.samples)
606
607 cliterm[clisock].clear()
608
609 return strbuf
610
611 gpuformatters = [None, gpuformatter_v1, gpuformatter_v2]
612
613
614 # =================================
615 # Thread start function:
616 # Scan all GPUs with a particular
617 # interval to obtain their stats
618 # =================================
619 def gpuscanner(scaninterval):
620 realtimenext = time.time() + scaninterval
621
622 # -----------------------------
623 # main loop
624 # -----------------------------
625 while True:
626 # -----------------------------
627 # gather the metrics per GPU
628 # -----------------------------
629 with gpulock:
630 for gpu in gpulist:
631 gpu.readstats()
632
633 # -----------------------------
634 # handle wait time:
635 # wait before taking next sample
636 # unless gathering the metric took
637 # more than the required interval itself
638 # -----------------------------
639 sleeptime = realtimenext - time.time()
640
641 if sleeptime > 0:
642 time.sleep(sleeptime)
643
644 realtimenext += scaninterval
645
646
647 # ==========================================================================
648
649 # -----------------------------
650 # initialize logging
651 # -----------------------------
652 if '-v' in sys.argv:
653 loglevel = logging.DEBUG
654 else:
655 loglevel = logging.INFO
656
657 fm = logging.Formatter('atopgpud %(levelname)s: %(message)s')
658
659 fh = loghand.SysLogHandler('/dev/log',
660 facility=loghand.SysLogHandler.LOG_DAEMON)
661 fh.setFormatter(fm)
662 fh.setLevel(loglevel)
663
664 lg = logging.getLogger() # root logger
665 lg.addHandler(fh)
666 lg.setLevel(loglevel)
667
668 if '-f' not in sys.argv:
669 # -----------------------------
670 # release parent process
671 # (daemonize)
672 # -----------------------------
673 try:
674 if os.fork():
675 sys.exit(0) # parent process exits; child continues...
676 except Exception:
677 logging.error("Failed to fork child")
678
679 # -----------------------------
680 # load module pynvml
681 # -----------------------------
682 try:
683 import pynvml
684 except Exception:
685 logging.error("Python module 'pynvml' not installed!")
686 sys.exit(1)
687
688
689 try:
690 # -----------------------------
691 # call main function
692 # -----------------------------
693 main()
694
695 finally:
696 # -----------------------------
697 # shutdown GPU access
698 # -----------------------------
699 try:
700 pynvml.nvmlShutdown()
701 except Exception:
702 pass