set_cpu_affinity 28.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python

import sys
import os
import pwd
import re
import multiprocessing
import json
import signal
import weakref
from glob import glob
from subprocess import Popen, PIPE, DEVNULL
from collections import namedtuple
from functools import reduce, partial
from itertools import chain
16
from contextlib import contextmanager, ExitStack
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
from threading import Thread, Event
from queue import Queue

Debug = False

def GetProcDir(local_threads):
    dirs = ['/proc']
    if local_threads:
        dirs += [f'{os.getpid()}', 'task']
    return os.path.join(*dirs)

def GetTaskProcDir(task, is_thread):
    return os.path.join(GetProcDir(is_thread), f'{task}')

def context_enter(c):
    return c.__enter__()

def context_exit(c):
    c.__exit__(None, None, None)

@contextmanager
def parallel_context_manager(group):
    with multiprocessing.Pool() as pool:
        objs = pool.map(context_enter, group)
    try:
        yield objs
    finally:
        with multiprocessing.Pool() as pool:
            pool.map(context_exit, group)


class SystemCmd:

    SudoCacheMap = {}

    def __init__(self, cmd, desc='', try_sudo=True):
        self.m_cmd = []
        if try_sudo:
            self.checkSudo(cmd, desc)
            self.m_cmd = ['sudo', '-n']
        self.m_cmd += cmd

    def getCmd(self):
        return self.m_cmd

    def doPopen(self, **kws):
        args = dict(stdout=DEVNULL, stderr=DEVNULL)
        args.update(kws)
        return Popen(self.getCmd(), **args)

    def execute(self, **kws):
        po = self.doPopen(**kws)
        return po.wait()

    @classmethod
    def checkSudo(klass, cmd, desc=''):
        tcmd = tuple(cmd)
        if tcmd not in klass.SudoCacheMap:
            sudo = SystemCmd(['sudo', '-l'] + cmd, try_sudo=False)
            klass.SudoCacheMap[tcmd] = (sudo.execute() == 0)
        if klass.SudoCacheMap[tcmd]:
            return

        try:
            uid = os.getuid();
            pw = pwd.getpwuid(uid)
            user = pw[0]
        except KeyError:
            user = "Unknown"

        print(f'The command "{cmd}" is not allowed for user {user} '
              'in the sudoers database. Check sudoers(5) man page and '
              'restart this process')
        if desc:
            print(f'  {desc}')
        raise RuntimeError(f'Cannot execute sudo "{cmd}"! '
                           'See output for details')


class SMPSystem:

    NbCPUs = 0
    MaxNbCPUs = 0

    @classmethod
    def getNbCPUs(klass):
        if klass.NbCPUs == 0:
            with open('/proc/cpuinfo') as f:
                for l in f:
                    if l.startswith('processor'):
                        klass.NbCPUs += 1
        return klass.NbCPUs

    @classmethod
    def getMaxNbCPUs(klass):
        if klass.MaxNbCPUs == 0:
            cpu_glob = '/proc/sys/kernel/sched_domain/cpu*'
            klass.MaxNbCPUs = len(glob(cpu_glob)) or klass.getNbCPUs()
        return klass.NbCPUs

    @classmethod
    def getCPUSysfsDir(klass, cpu):
        return f'/sys/devices/system/cpu/cpu{cpu}'

121
122
123
124
125
126
127
128
129
130
131
132
133

class CPUFreqRawFileSetter:

    @classmethod
    def getBaseDir(klass, cpu):
        return os.path.join(SMPSystem.getCPUSysfsDir(cpu), 'cpufreq')

    @classmethod
    def getScalingGovernorFile(klass, cpu):
        return os.path.join(klass.getBaseDir(cpu), 'scaling_governor')

    @classmethod
    def getAvailableGovernorsFile(klass, cpu):
134
        return os.path.join(klass.getBaseDir(cpu), 'scaling_available_governors')
135

136
    @classmethod
137
    def getAvailableGovernors(klass, cpu):
138
        fname = klass.getAvailableGovernorsFile(cpu)
139
140
141
        cmd = SystemCmd(['cat', fname], try_sudo=False)
        cat = cmd.doPopen(stdout=PIPE, text=True)
        return cat.stdout.readline().strip().split()
142
143

    @classmethod
144
145
146
    def getCurrGovernor(klass, cpu_list):
        governor_list = []
        for cpu in cpu_list:
147
            fname = klass.getScalingGovernorFile(cpu)
148
149
150
151
            cmd = SystemCmd(['cat', fname], try_sudo=False)
            cat = cmd.doPopen(stdout=PIPE, text=True)
            governor_list.append(cat.stdout.readline().strip())
        return governor_list
152
153

    @classmethod
154
    def setCurrGovernor(klass, cpu_list, governor):
155
156
        cpu_cmds = []
        for cpu in cpu_list:
157
            fname = klass.getScalingGovernorFile(cpu)
158
159
160
161
            cpu_cmds.append(f'echo {governor} > {fname}')
        bash_cmd = ' && '.join(cpu_cmds)
        cmd = SystemCmd(['bash', '-c', bash_cmd])
        if cmd.execute() != 0:
162
            raise RuntimeError(f'Cannot set CPUs {cpu_list} freq. governor '
163
164
                               f'to {governor}')

165
166
167
168
169
170
171
172
173
174
175
176
177

class CPUFreqUtilsSetter:

    Info = 'cpufreq-info'
    Set = 'cpufreq-set'

    @classmethod
    def getAvailableGovernors(klass, cpu):
        cmd = SystemCmd([klass.Info, '-c', str(cpu), '-g'], try_sudo=False)
        info = cmd.doPopen(stdout=PIPE, text=True)
        avail = info.stdout.readline().strip().split()
        return avail

178
    @classmethod
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
    def getGovernorInfo(klass, cpu):
        cmd = SystemCmd([klass.Info, '-c', str(cpu), '-p'], try_sudo=False)
        info = cmd.doPopen(stdout=PIPE, text=True)
        min_freq, max_freq, policy = info.stdout.readline().strip().split()
        return min_freq, max_freq, policy

    @classmethod
    def getCurrGovernor(klass, cpu_list):
        governors = []
        for cpu in cpu_list:
            min_freq, max_freq, policy = klass.getGovernorInfo(cpu)
            governors.append(policy)
        return governors

    @classmethod
    def setCurrGovernor(klass, cpu_list, governor):
        for cpu in cpu_list:
            min_freq, max_freq, policy = klass.getGovernorInfo(cpu)
            cmd = SystemCmd([klass.Set, '-c', str(cpu), '-g', governor,
                             '-d', min_freq, '-u', max_freq])
            if cmd.execute() != 0:
                raise RuntimeError(f'Cannot set CPU {cpu} freq. governor '
                                   f'to {governor}')


class CPUFreqMgr:

    PerformanceGovernors = ['performance']
    PowerSaveGovernors = ['ondemand', 'powersave']

209
    def __init__(self, target_governors=[None],
210
211
212
                 default_governors=PowerSaveGovernors, setter=None):
        self.m_setter = setter or self.getSetter()

213
        if not target_governors or not target_governors[0]:
214
            self.m_target_governor = None
215
216
217
218
219
220
221
222
223
224
            return
        elif not self.m_setter:
            raise RuntimeError('No available CPUFreq setter: install '
                               'cpufreq-utils or provide sudo privileges')

        available_targets = self.getAvailableGovernorsFrom(target_governors)
        if not available_targets:
            raise ValueError(f'None of the target governors '
                             f'{target_governors} is available')
        self.m_target_governor = available_targets[0]
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

        available_defaults = self.getAvailableGovernorsFrom(default_governors)
        if not available_defaults:
            raise ValueError(f'None of the default governors '
                             f'{default_governors} is available')
        self.m_default_governor = available_defaults[0]

    def getSetter(self):
        for klass in [CPUFreqUtilsSetter, CPUFreqRawFileSetter]:
            try:
                setter = klass()
                cpu_list=[0]
                governors = setter.getCurrGovernor(cpu_list)
                setter.setCurrGovernor(cpu_list, governors[0])
                return setter
            except:
                pass
        return None

    def getAvailableGovernorsFrom(self, governors):
245
246
        available_governors = self.m_setter.getAvailableGovernors(0)
        for cpu in range(1, SMPSystem.getNbCPUs()):
247
            available_for_this = self.m_setter.getAvailableGovernors(cpu)
248
249
250
251
            available_governors = [g for g in available_for_this
                                   if g in available_governors]
            if not available_governors:
                break
252
253
254
        return [g for g in governors if g in available_governors]

    def setAllGovernors(self, governor):
255
        print(f'Setting all CPUs freq. governor to {governor} ...')
256
        self.m_setter.setCurrGovernor(range(SMPSystem.getNbCPUs()), governor)
257

258
259
260
    def __enter__(self):
        if self.m_target_governor:
            self.setAllGovernors(self.m_target_governor)
261

262
263
264
    def __exit__(self, *args):
        if self.m_target_governor:
            self.setAllGovernors(self.m_default_governor)
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


def CPU(*args):
    return CPUAffinity(reduce(lambda x,y: x | y, [1 << x for x in args]))

class CPUAffinity:

    def __init__(self, m=0):
        if type(m) == str:
            m = int(''.join(m.split(',')), 16)
        if m == self.allCPUs():
            m = 0
        self.m_mask = m

    def getMask(self):
        return self.m_mask if self.m_mask else self.allCPUs()

    def getZeroDefaultMask(self):
        return self.m_mask

    def __str__(self):
        return self.toString(self.getMask())

    def __repr__(self):
        return f'0x{self}'

    def __cmp__(self, o):
        return cmp(self.m_mask, o.m_mask)

    def __or__(self, o):
        return CPUAffinity(self.m_mask | o.m_mask)

    def __add__(self, o):
        return self | o

    def applyToTask(self, task):
        incl_threads = True
        status = os.path.join(GetTaskProcDir(task, not incl_threads), 'status')
        if not os.access(status, os.F_OK):
            return

        cmd = ['taskset']
        cmd += ['-a'] if incl_threads else []
        cmd += ['-p', str(self), f'{task}']
        taskset = SystemCmd(cmd)
        if Debug:
            print(f'Excecuting: {" ".join(taskset.getCmd())}')
        if taskset.execute() != 0:
            th = ' and threads' if incl_threads else ''
            raise RuntimeError(f'Error setting task {task}{th} CPU affinity')

    @classmethod
    def toString(klass, m, sep='', group_bits=32):
        group_mask = 2**group_bits - 1
        s = [f'{m >> b & group_mask:08x}'
             for b in range(0, klass.getNbSystemCPUs(), group_bits)]
        return sep.join(s[::-1])

    @staticmethod
    def fromJSON(json):
        if 'cpus' in json:
            return CPU(*json['cpus'])
        elif 'ranges' in json:
            return CPU(*list(chain(*[range(a, b) for a, b in json['ranges']])))
        raise ValueError(f'Invalid JSON CPUAffinity: {json}')

    @staticmethod
    def getNbSystemCPUs():
        return SMPSystem.getNbCPUs()

    @staticmethod
    def getMaxNbSystemCPUs():
        return SMPSystem.getMaxNbCPUs()

    @classmethod
    def allCPUs(klass):
        return 2**klass.getNbSystemCPUs() - 1


class IrqBalanceMgr:

    def __init__(self, stopped=True):
        self.m_state = not stopped

    def __enter__(self):
        self.setActive(self.m_state)

    def __exit__(self, *args):
        self.setActive(True)

    @classmethod
    def getActive(klass):
357
358
359
360
361
362
        cmd = SystemCmd(['service', 'irqbalance', 'status'])
        service = cmd.doPopen(stdout=PIPE, text=True)
        for l in service.stdout:
            if l.strip().startswith('Active'):
                return 'running' in l
        raise RuntimeError('Could not check irqbalance service')
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

    @classmethod
    def setActive(klass, active):
        if klass.getActive() == active:
            return
        action = 'start' if active else 'stop'
        print(f'irqbalance: executing {action} ...')
        service = SystemCmd(['service', 'irqbalance', action])
        if service.execute() != 0:
            raise RuntimeError(f'Could not {action} irqbalance service')


class NetDev:

    InfoTokenReStr = '([^ \t]+)[ \t]*'

    ProcIntSysfsName = '/proc/interrupts'
    ProcIntRe = None

    @classmethod
    def getProcIntRe(klass):
        nb_cpus = CPUAffinity.getNbSystemCPUs()
        if not klass.ProcIntRe:
            re_str = ('[ \t]*'
                      '(?P<irq>[0-9]+):[ \t]+'
	              '(?P<counts>(([0-9]+)[ \t]+){' f'{nb_cpus}' '})'
	              '(?P<info>(' f'{klass.InfoTokenReStr}' '){2,4})')
            klass.ProcIntRe = re.compile(re_str)
        return klass.ProcIntRe

393
394
395
396
397
    ProcIntNameRe = re.compile('((?P<type>mlx[^_-]+)(_comp|-)'
                                      '(?P<mlx_queue>[0-9]+)@'
                                      '(pci:)?(?P<pci>[0-9A-Fa-f:.]+)|'
                                '(?P<name>[^-]+)-[TtRrXx]+-'
                                      '(?P<intel_queue>[0-9]+))')
398
399
400
401
402
403
404
405
406

    ProcIntCache = None

    EthtoolPacketsRe = re.compile('^[ \t]*'
                                  'rx(_queue_)?(?P<queue>[0-9]+)_packets:'
                                  '[ \t]+(?P<packets>[0-9]+)\n$');

    def __init__(self, name):
        self.m_name = name
407
408
        if not os.path.exists(self.getSysfsDir()):
            raise ValueError(f'Unknown NetDev {name}')
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

    def getSysfsDir(self):
        return f'/sys/class/net/{self.m_name}'

    def getDevLink(self):
        link = os.path.join(self.getSysfsDir(), 'device')
        return link if os.path.islink(link) else None

    def getDevPCIBusId(self):
        dev_link = self.getDevLink()
        if not dev_link:
            return None
        subsystem = os.path.join(dev_link, 'subsystem')
        if not os.path.islink(subsystem):
            return None
        elif os.path.basename(os.readlink(subsystem)) != 'pci':
            return None
        return os.path.basename(os.readlink(dev_link))

    @classmethod
    def getProcIntData(klass):
        if klass.ProcIntCache is not None:
            return klass.ProcIntCache

        proc_int_data = []
        proc_int_re = klass.getProcIntRe()
        with open(klass.ProcIntSysfsName) as f:
            for l in f:
                m = proc_int_re.match(l[:-1])
                if not m:
                    continue
                irq = int(m['irq'])
                queue = None
                name = re.findall(klass.InfoTokenReStr, m['info'])[-1]
                m = klass.ProcIntNameRe.match(name)
                if m:
                    queue_str = (m['mlx_queue'] if m['mlx_queue']
                                                else m['intel_queue'])
                    queue = int(queue_str)
                if Debug:
                    print(f'Found match: [{queue}] {irq}: {name}')
                proc_int_data.append(dict(irq=irq, name=name, queue=queue))
        klass.ProcIntCache = proc_int_data
        return klass.ProcIntCache

    def getIrqList(self):
        dev_link = self.getDevLink()
        if not dev_link:
            return []
        irq_glob = os.path.join(dev_link, 'msi_irqs', '*')
        dev_irqs = [int(os.path.basename(i)) for i in glob(irq_glob)]
        nb_retries = 5
        for retry in range(nb_retries):
            try:
                act_irqs = []
                for data in self.getProcIntData():
                    if data['irq'] in dev_irqs:
                        act_irqs.append((data['queue'], data['irq']))
                return act_irqs
            except Exception as e:
                print(f'Error reading {self.ProcIntSysfsName}: {e}. '
                      f'Retrying ...')
                pass
        raise RuntimeError(f'Error reading {self.ProcIntSysfsName} '
                           f'after {nb_retries} retries')

    def getActiveRxQueueList(self):
        cmd = SystemCmd(['ethtool', '-S', self.getName()])
477
        ethtool = cmd.doPopen(stdout=PIPE, text=True)
478
479
        queue_list = []
        for l in ethtool.stdout:
480
            m = self.EthtoolPacketsRe.match(l)
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
            if not m:
                continue
            if int(m['packets']) > 0:
                queue_list.append(int(m['queue']))
        if not queue_list:
            print(f'Warning: no queue found for {self.getName()}')
        return queue_list


class NetDevRxQueueMgr:

    Affinity = namedtuple('NetDevRxQueueMgr_Affinity', ['irq', 'processing'])
    DefaultAffinity = Affinity(CPUAffinity(), CPUAffinity())

    AffinitySetterName = 'netdev_set_queue_cpu_affinity'

    TaskIrq, TaskProcessing = range(2)

    def __init__(self, name, queue_affinity_map,
                 default_affinity=DefaultAffinity):
        self.m_dev = NetDev(name)
        self.m_queue_affinity_map = queue_affinity_map
        self.m_default_affinity = default_affinity
        self.m_irq_list = None

    def getName(self):
        return self.m_dev.m_name

    def getSetQueueTaskList(self):
        return [(self.getQueueName(queue),
                 self.getQueueAffinityTaskList(queue, affinity))
                for queue, affinity in self.m_queue_affinity_map.items()]

    def getRestoreQueueTaskList(self):
        good_affinity = self.m_default_affinity
        return [(self.getQueueName(queue),
                 self.getQueueAffinityTaskList(queue, good_affinity))
                for queue, affinity in self.m_queue_affinity_map.items()
                if affinity != good_affinity]

    def getQueueName(self, queue):
        queue_str = f'queue #{queue}' if queue >= 0 else 'queues'
        return f'NetDev {self.getName()} Rx {queue_str}'

    def __enter__(self):
        for queue_name, tl in self.getSetQueueTaskList():
            print(f'Setting {queue_name} affinity [{len(tl)} tasks] ...')
            [self.applyWithSetter(*t) for t in tl]

    def __exit__(self, *args):
        for queue_name, tl in self.getRestoreQueueTaskList():
            print(f'Restoring {queue_name} affinity [{len(tl)} tasks] ...')
            [self.applyWithSetter(*t) for t in tl]

    def getIrqList(self):
        if self.m_irq_list is None:
            self.m_irq_list = self.m_dev.getIrqList()
        return self.m_irq_list

    def getQueueAffinityTaskList(self, queue, affinity):
        tl = self.getTaskList(self.TaskIrq, queue, affinity.irq)
        tl += self.getTaskList(self.TaskProcessing, queue, affinity.processing)
        return tl

    def getTaskList(self, task, queue, affinity):
        if task == self.TaskIrq:
            f = self.getIrqFileSystemData
        else:
            f = self.getProcessingFileSystemData
        return [(self.getName(), task, e, affinity) for p, e in zip(*f(queue))]

    def getIrqFileSystemData(self, queue):
        irq_list = self.getIrqList()
        if queue == -1:
            act_irqs = [i for q, i in irq_list]
        elif queue == -2:
            act_queue_list = self.m_dev.getActiveRxQueueList()
            act_irqs = [i for q, i in irq_list if q in acq_queue_list]
        else:
            act_irqs = [i for q, i in irq_list if q == queue]
        full_path = [f'/proc/irq/{i}/smp_affinity' for i in act_irqs]
        entry_name = [f'{i}' for i in act_irqs]
        return full_path, entry_name

    def getProcessingFileSystemData(self, queue):
        sysfs_dir = self.m_dev.getSysfsDir()
        full_path = glob(f'{sysfs_dir}/queues/rx-*/rps_cpus')
        entry_name = [p.split('/')[6] for p in full_path]
        if queue == -2:
            filter_list = self.m_dev.getActiveRxQueueList()
        elif queue == -1:
            filter_list = []
        else:
            filter_list = [queue]
        if filter_list:
            full_path = [p for p, e in zip(full_path, entry_name)
                         if int(e[3:]) in filter_list]
            entry_name = [p.split('/')[6] for p in full_path]
        if not full_path:
            print(f'Warning: no Rx queue ({queue}) for {self.getName()}')
        return full_path, entry_name

    @classmethod
    def applyWithSetter(klass, dev_name, task, irq_queue, affinity):
        task_opt = '-i' if task == klass.TaskIrq else '-r'
        mask = affinity.getZeroDefaultMask()
        if task == klass.TaskIrq and mask == 0:
            return
        args = [task_opt, dev_name, irq_queue, CPUAffinity.toString(mask, ',')]
        setter = SystemCmd([klass.AffinitySetterName] + args)
        if Debug:
            print(f'Executing: {" ".join(setter.getCmd())} ...')
593
        sys.stdout.flush()
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
        if setter.execute() != 0:
            raise RuntimeError(f'Error executing {" ".join(setter.getCmd())}')

NetDevRxQueueMgr_Affinity = NetDevRxQueueMgr.Affinity

def parallel_netdev_queue_boundary(net_devs, action):
    desc = 'Setting' if action == 'set' else 'Restoring'
    method = f'get{action.capitalize()}QueueTaskList'
    with multiprocessing.Pool() as pool:
        all_tasks = []
        for d in net_devs:
            f = getattr(d, method)
            for queue_name, tl in f():
                print(f'{desc} {queue_name} affinity [{len(tl)} tasks] ...')
                all_tasks += tl
        pool.starmap(NetDevRxQueueMgr.applyWithSetter, all_tasks)

@contextmanager
def net_dev_groups_cpu_affinity(net_dev_groups_affinity):
    stop_irq_balance = bool(net_dev_groups_affinity)
    with IrqBalanceMgr(stop_irq_balance):
        net_devs = [NetDevRxQueueMgr(d, affinity_map)
                    for net_devs, affinity_map in net_dev_groups_affinity
                    for d in net_devs]
        parallel_netdev_queue_boundary(net_devs, 'set')
        try:
            yield
        finally:
            parallel_netdev_queue_boundary(net_devs, 'restore')


class ProcessMgr:

    DefaultAffinity = CPUAffinity()

    VmRe = re.compile('VmSize:?$')
    CpusRe = re.compile('Cpus_allowed:?$')

    def __init__(self, other_affinity, default_affinity=DefaultAffinity):
        self.m_other_affinity = other_affinity
        self.m_default_affinity = default_affinity

    def __enter__(self):
        print(f'Setting CPU affinity of other processes ...')
        self.setOtherAffinity(self.m_other_affinity)

    def __exit__(self, *args):
        if self.m_other_affinity == self.m_default_affinity:
            return
        print(f'Restoring default CPU affinity to other processes ...')
        self.setOtherAffinity(self.m_default_affinity)

    @classmethod
    def setOtherAffinity(klass, affinity):
        this_pid = os.getpid()
        task_status_fname_list = glob('/proc/[0-9]*/status')
        with multiprocessing.Pool() as pool:
            f = partial(klass.checkOtherPIDAndSet, this_pid=this_pid,
                        affinity=affinity)
            pool.map(f, task_status_fname_list)

    @classmethod
    def checkOtherPIDAndSet(klass, n, this_pid, affinity):
        pid = int(n.split('/')[2])
        if pid == this_pid:
            return
        try:
            has_vm = False
            has_bad_affinity = False
            with open(n) as f:
                for l in f:
                    tokens = l.split()
                    if klass.VmRe.match(tokens[0]):
                        has_vm = True
                        continue
                    m = klass.CpusRe.match(tokens[0])
                    if m:
                        proc_affinity = CPUAffinity(tokens[1])
                        has_bad_affinity = (proc_affinity != affinity)
            if has_vm and has_bad_affinity:
                affinity.applyToTask(pid)
        except FileNotFoundError:
            pass

class CPUAffinityDataJSONParser:

    def __init__(self, json_str):
        config = json.loads(json_str)
        self.m_json = None
        listener = []
684
        cpufreq_governor = None
685
686
687
688
689
690
691
692
693
694
        lima = ProcessMgr.DefaultAffinity
        other = ProcessMgr.DefaultAffinity
        net_dev = []
        if 'recvs' in config:
            listener = self.listenerAffinityFromRecvsJSON(config['recvs'])
            lima = self.limaAffinityFromRecvsJSON(config['recvs'])
        if 'cpu_affinity' in config:
            self.m_json = config['cpu_affinity']
            if 'recv' in self.m_json:
                listener = self.listenerAffinityFromJSON(self.m_json['recv'])
695
            cpufreq_governor = self.m_json.get('cpufreq_governor', None)
696
697
698
699
700
701
702
            if 'lima' in self.m_json:
                lima = self.limaAffinityFromJSON(self.m_json['lima'])
            if 'other' in self.m_json:
                other = self.otherAffinityFromJSON(self.m_json['other'])
            if 'net_dev' in self.m_json:
                net_dev = [self.netDevGroupAffinityFromJSON(json)
                           for json in self.m_json['net_dev']]
703
704
705
        self.m_global_data = dict(listener=listener,
                                  cpufreq_governor=cpufreq_governor, lima=lima,
                                  other=other, net_dev=net_dev)
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

    @classmethod
    def listenerAffinityFromRecvsJSON(klass, recvs):
        if len(recvs) == 0 or 'cpu_affinity' not in recvs[0] or \
           'recv' not in recvs[0]['cpu_affinity']:
            return []
        merge_listeners = lambda x, y: [[c + d for c, d in zip(a, b)]
                                        for a, b in zip(x, y)]
        return reduce(merge_listeners,
                      [[[CPUAffinity.fromJSON(l) for l in r['listeners']]
                        for r in x['cpu_affinity']['recv']]
                       for x in recvs])

    @classmethod
    def limaAffinityFromRecvsJSON(klass, recvs):
        if len(recvs) == 0 or 'cpu_affinity' not in recvs[0] or \
           'lima' not in recvs[0]['cpu_affinity']:
            return CPUAffinity()
        return reduce(lambda x, y: x + y,
                      [CPUAffinity.fromJSON(x['cpu_affinity']['lima'])
                       for x in recvs])

    @classmethod
    def recvAffinityFromJSON(klass, json):
        return [[CPUAffinity.fromJSON(l) for l in recv['listeners']]
                for recv in json]

    @classmethod
    def limaAffinityFromJSON(klass, json):
        return CPUAffinity.fromJSON(json)

    @classmethod
    def otherAffinityFromJSON(klass, json):
        return CPUAffinity.fromJSON(json)

    @classmethod
    def netDevGroupAffinityFromJSON(klass, json):
        def queue_affinity(json):
            def affinity(j):
                irq, proc = [CPUAffinity.fromJSON(a)
                             for a in (j['irq'], j['proc'])]
                return NetDevRxQueueMgr.Affinity(irq, proc)
            def queues(j):
                if 'queue' in j:
                    return [j]
                elif 'queues' in j:
                    return [dict(queue=q, affinity=j['affinity'])
                            for q in j['queues']]
                return []
            return dict([(q['queue'], affinity(q['affinity']))
                         for j in json for q in queues(j)])
        return (json['devs'], queue_affinity(json['affinity']))

    def getGlobalData(self):
        return self.m_global_data

    @classmethod
    def fromFile(klass, fname):
        with open(fname) as f:
            return klass(f.read())

def CPUGlobalDataToStringLines(cpu_affinity_data):
    lines = []
    if cpu_affinity_data['listener']:
        lines += ["Listeners:"]
    for i, r in enumerate(cpu_affinity_data['listener']):
        l_str = ',\n      '.join([repr(l) for l in r])
        lines += [f" {i:2d}: [{l_str}]"]

    lines += [f"Lima:   {cpu_affinity_data['lima']}"]
    lines += [f"Other:  {cpu_affinity_data['other']}"]
    if cpu_affinity_data['net_dev']:
        lines += ["NetDev:"]
    for devs, affinity in cpu_affinity_data['net_dev']:
        lines += [f"++Devs: {','.join(devs)}"]
        lines += chain(*[(f" *Queue: {q}",
                          f"  Irq:  {a.irq}", f"  Proc: {a.processing}")
                         for q, a in affinity.items()])
    return lines


787
788
789
790
791
792
793
794
795
child = None

def sig_term_handler(intno, stack_frame):
    print('set_cpu_affinity: sending SIGTERM to sub-process ...')
    sys.stdout.flush()
    if child is not None:
        child.terminate()


796
797
798
def main(argv):

    signal.signal(signal.SIGINT, signal.SIG_IGN)
799
    signal.signal(signal.SIGTERM, sig_term_handler)
800
801
802
803
804
805
806
807
808
809

    print(f'NbSystemCPUs={CPUAffinity.getNbSystemCPUs()},',
          f'MaxNbSystemCPUs={CPUAffinity.getMaxNbSystemCPUs()}')
    print(f'CPUs:   {CPUAffinity()}')

    json_parser = CPUAffinityDataJSONParser.fromFile(argv[1])
    cpu_affinity_data = json_parser.getGlobalData()
    for l in CPUGlobalDataToStringLines(cpu_affinity_data):
        print(l)

810
811
    os.environ['SET_CPU_AFFINITY_PID'] = str(os.getpid())

812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
    with ExitStack() as stack:
        cpufreq_governors = [cpu_affinity_data['cpufreq_governor']]
        stack.enter_context(CPUFreqMgr(cpufreq_governors))

        net_dev_affinity = cpu_affinity_data['net_dev']
        stack.enter_context(net_dev_groups_cpu_affinity(net_dev_affinity))

        stack.enter_context(ProcessMgr(cpu_affinity_data['other']))

        def child_func(*argv):
            affinity = cpu_affinity_data['lima']
            affinity.applyToTask(os.getpid())
            print(f'Executing: {" ".join(argv)} ...')
            os.execlp(argv[0], *argv)

        global child
        child = multiprocessing.Process(target=child_func, args=argv[2:])
        child.start()
        child.join()
831
832
833
834


if __name__ == '__main__':
    main(sys.argv)