-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecofreq.py
executable file
·3743 lines (3180 loc) · 109 KB
/
ecofreq.py
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
#!/usr/bin/env python3
import sys, json
import urllib.request
import requests
from requests.auth import HTTPBasicAuth
from subprocess import call,check_output,STDOUT,DEVNULL,CalledProcessError
from datetime import datetime
import time
import os
import configparser
import argparse
import random
import heapq
import string
import traceback
import asyncio
import json
import copy
from math import ceil
from inspect import isclass
from _collections import deque
try:
from aiomqtt import Client, MqttError
mqtt_found = True
except:
mqtt_found = False
HOMEDIR = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = "/var/log/ecofreq.log"
SHM_FILE = "/dev/shm/ecofreq"
OPTION_DISABLED = ["none", "off"]
JOULES_IN_KWH = 3.6e6
TS_FORMAT = "%Y-%m-%dT%H:%M:%S"
def read_value(fname, field=0, sep=' '):
with open(fname) as f:
s = f.readline().rstrip("\n")
if field == 0:
return s
else:
return s.split(sep)[field]
def read_int_value(fname):
return int(read_value(fname))
def write_value(fname, val):
if os.path.isfile(fname):
with open(fname, "w") as f:
f.write(str(val))
return True
else:
return False
def safe_round(val):
return round(val) if (isinstance(val, float)) else val
def getbool(x):
if isinstance(x, str):
return True if x.lower() in ['1', 'y', 'yes', 'true', 'on'] else False
else:
return x
class NAFormatter(string.Formatter):
def __init__(self, missing='NA'):
self.missing = missing
def format_field(self, value, spec):
if value == None:
value = self.missing
spec = spec.replace("f", "s")
return super(NAFormatter, self).format_field(value, spec)
class GeoHelper(object):
API_URL = "http://ipinfo.io"
@classmethod
def get_my_geoinfo(self):
req = urllib.request.Request(self.API_URL)
# req.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11")
try:
resp = urllib.request.urlopen(req).read()
js = json.loads(resp)
return js
except:
e = sys.exc_info()[0]
print ("Exception: ", e)
return None
@classmethod
def get_my_coords(self):
try:
js = self.get_my_geoinfo()
lat, lon = js['loc'].split(",")
except:
e = sys.exc_info()[0]
print ("Exception: ", e)
lat, lon = None, None
return lat, lon
class SuspendHelper(object):
SYS_PWR="/sys/power/"
SYS_PWR_STATE=SYS_PWR+"state"
SYS_PWR_MEMSLEEP=SYS_PWR+"mem_sleep"
S2MEM="mem"
S2DISK="disk"
S2IDLE="s2idle"
S2RAM="deep"
@classmethod
def available(cls):
return os.path.isdir(cls.SYS_PWR)
@classmethod
def supported_modes(cls):
supported_modes = []
if cls.available():
supported_modes = read_value(cls.SYS_PWR_STATE).split(" ")
if cls.S2MEM in supported_modes:
supported_modes += read_value(cls.SYS_PWR_MEMSLEEP).split(" ")
return supported_modes
@classmethod
def info(cls):
print("Suspend-to-RAM available: ", end ="")
def_s2ram = "[" + cls.S2RAM + "]"
if def_s2ram in cls.supported_modes():
print("YES")
else:
print("NO")
print("Suspend modes supported:", " ".join(cls.supported_modes()))
@classmethod
def suspend(cls, mode=S2RAM):
if mode == cls.S2RAM:
write_value(cls.SYS_PWR_MEMSLEEP, mode)
mode = cls.S2MEM
write_value(cls.SYS_PWR_STATE, mode)
class EcoFreqController(object):
def __init__(self, ef):
self.ef = ef
def run_cmd(self, cmd, args={}):
res = {}
try:
if hasattr(self, cmd):
getattr(self, cmd)(res, args)
res['status'] = 'OK'
else:
res['status'] = 'ERROR'
res['error'] = 'Unknown command: ' + cmd
except:
res['status'] = 'ERROR'
res['error'] = 'Exception: ' + sys.exc_info()
return res
def info(self, res, args):
res.update(self.ef.get_info())
m_stats = self.ef.monitor.get_stats()
if "LastState" in m_stats:
res['idle_state'] = m_stats["LastState"]
res['idle_load'] = m_stats["LastLoad"]
res['idle_duration'] = m_stats["IdleDuration"]
else:
res['idle_state'] = "NA"
res['avg_power'] = self.ef.monitor.get_last_avg_power()
res['total_energy_j'] = self.ef.monitor.get_total_energy()
res['total_co2'] = self.ef.total_co2
res['total_cost'] = self.ef.total_cost
res['last_co2kwh'] = self.ef.last_co2kwh
res['last_price'] = self.ef.last_price
def get_policy(self, res, args):
res['co2policy'] = self.ef.co2policy.get_config()
def set_policy(self, res, args):
new_cfg = {}
for domain in args["co2policy"].keys():
dpol = domain + "_policy"
if dpol in self.ef.config:
old_cfg = dict(self.ef.config[dpol])
else:
old_cfg = dict(self.ef.config["policy"])
# print(old_cfg)
new_cfg[domain] = copy.deepcopy(old_cfg)
new_cfg[domain].update(args["co2policy"][domain])
# all domains use the same metric for now
new_cfg["metric"] = args["co2policy"][domain]["metric"]
# print(new_cfg)
self.ef.co2policy.set_config(new_cfg)
if self.ef.last_co2_data:
self.ef.co2policy.set_co2(self.ef.last_co2_data)
self.ef.co2logger.print_cmd("set_policy")
def get_provider(self, res, args):
res['co2provider'] = self.ef.co2provider.get_config()
def set_provider(self, res, args):
old_cfg = self.ef.config
# print(args["co2provider"])
new_cfg = copy.deepcopy(old_cfg)
try:
new_cfg.read_dict(args["co2provider"])
self.ef.reset_co2provider(new_cfg)
except:
print(sys.exc_info())
class EcoServer(object):
IPC_FILE="/var/run/ecofreq.sock"
BUF_SIZE=2048
def __init__(self, iface, config=None):
import grp
self.iface = iface
self.fmod = 0o660
gname = "ecofreq"
if config and "server" in config:
gname = config["server"].get("filegroup", gname)
if "filemode" in config["server"]:
self.fmod = int(config["server"]["filemode"], 8)
try:
self.gid = grp.getgrnam(gname).gr_gid
except KeyError:
self.gid = -1
async def spin(self):
self.serv = await asyncio.start_unix_server(self.on_connect, path=self.IPC_FILE)
if self.gid >= 0:
os.chown(self.IPC_FILE, -1, self.gid)
os.chmod(self.IPC_FILE, self.fmod)
# print(f"Server init")
# async with self.serv:
await self.serv.serve_forever()
async def on_connect(self, reader, writer):
data = await reader.read(self.BUF_SIZE)
msg = data.decode()
# addr = writer.get_extra_info('peername')
# print(f"Received {msg!r}")
try:
req = json.loads(msg)
cmd = req['cmd']
args = req['args'] if 'args' in req else {}
res = self.iface.run_cmd(cmd, args)
response = json.dumps(res)
except:
response = "Invalid message"
writer.write(response.encode())
await writer.drain()
writer.close()
class EcoClient(object):
async def unix_send(self, message):
try:
reader, writer = await asyncio.open_unix_connection(EcoServer.IPC_FILE)
except FileNotFoundError:
raise ConnectionRefusedError
# print(f'Send: {message!r}')
writer.write(message.encode())
await writer.drain()
data = await reader.read(EcoServer.BUF_SIZE)
# print(f'Received: {data.decode()!r}')
writer.close()
return data.decode()
def send_cmd(self, cmd, args=None):
obj = dict(cmd=cmd, args=args)
msg = json.dumps(obj)
resp = asyncio.run(self.unix_send(msg))
try:
return json.loads(resp)
except:
return dict(status='ERROR', error='Exception')
def info(self):
return self.send_cmd('info')
def get_policy(self):
return self.send_cmd('get_policy')
def set_policy(self, policy):
return self.send_cmd('set_policy', policy)
def get_provider(self):
return self.send_cmd('get_provider')
def set_provider(self, provider):
return self.send_cmd('set_provider', provider)
class NvidiaGPUHelper(object):
CMD_NVSMI = "nvidia-smi"
@classmethod
def available(cls):
# return call(cls.CMD_NVSMI, shell=True, stdout=DEVNULL, stderr=DEVNULL) == 0
try:
out = cls.query_gpus(fields = "power.draw,power.management")
# print (out)
return "Enabled" in out[0][1]
except CalledProcessError:
return False
@classmethod
def query_gpus(cls, fields, fmt = "csv,noheader,nounits", qcmd="--query-gpu"):
cmdline = cls.CMD_NVSMI + " --format=" + fmt + " " + qcmd + "=" + fields
out = check_output(cmdline, shell=True, stderr=DEVNULL, universal_newlines=True)
result = []
for line in out.split("\n"):
if line:
result.append([x.strip() for x in line.split(",")])
return result
@classmethod
def get_power(cls):
pwr = [ float(x[0]) for x in cls.query_gpus(fields = "power.draw") ]
return sum(pwr)
@classmethod
def get_power_limit(cls):
pwr = [ float(x[0]) for x in cls.query_gpus(fields = "power.limit") ]
return sum(pwr)
@classmethod
def get_power_limit_all(cls):
return cls.query_gpus(fields = "power.min_limit,power.max_limit,power.limit")
@classmethod
def set_power_limit(cls, max_gpu_power):
cmdline = cls.CMD_NVSMI + " -pl " + str(max_gpu_power)
out = check_output(cmdline, shell=True, stderr=DEVNULL, universal_newlines=True)
@classmethod
def get_supported_freqs(cls):
return cls.query_gpus(fields="graphics", qcmd="--query-supported-clocks")
@classmethod
def get_hw_max_freq(cls):
return [float(x[0]) for x in cls.query_gpus(fields = "clocks.max.gr")]
@classmethod
def set_freq_limit(cls, max_gpu_freq):
cmdline = cls.CMD_NVSMI + " -lgc 0," + str(int(max_gpu_freq))
cmdline += " --mode=1"
out = check_output(cmdline, shell=True, stderr=DEVNULL, universal_newlines=True)
@classmethod
def reset_freq_limit(cls):
cmdline = cls.CMD_NVSMI + " -rgc"
out = check_output(cmdline, shell=True, stderr=DEVNULL, universal_newlines=True)
@classmethod
def info(cls):
if cls.available():
field_list = "name,power.min_limit,power.max_limit,power.limit"
cnt = 0
for gi in cls.query_gpus(fields = field_list, fmt="csv,noheader"):
print ("GPU" + str(cnt) + ": " + gi[0] + ", min_hw_limit = " + gi[1] + ", max_hw_limit = " + gi[2] + ", current_limit = " + gi[3])
cnt += 1
class CpuInfoHelper(object):
CMD_LSCPU = "lscpu"
CPU_TDP_FILE = os.path.join(HOMEDIR, "cpu_tdp.csv")
@classmethod
def available(cls):
return call(cls.CMD_LSCPU, shell=True, stderr=DEVNULL) == 0
@classmethod
def parse_lscpu(cls):
try:
out = check_output(cls.CMD_LSCPU, shell=True, stderr=DEVNULL, universal_newlines=True)
cpuinfo = {}
for line in out.split("\n"):
tok = line.split(":")
if len(tok) > 1:
cpuinfo[tok[0]] = tok[1].strip()
return cpuinfo
except CalledProcessError:
return None
@classmethod
def get_cores(cls):
cpuinfo = cls.parse_lscpu()
threads = int(cpuinfo["CPU(s)"])
cores = int(threads / int(cpuinfo["Thread(s) per core"]))
return cores
@classmethod
def get_sockets(cls):
cpuinfo = cls.parse_lscpu()
return int(cpuinfo["Socket(s)"])
@classmethod
def get_tdp_uw(cls):
cpuinfo = cls.parse_lscpu()
mymodel = cpuinfo["Model name"]
mymodel = mymodel.split(" with ")[0]
mycpu_toks = []
for w in mymodel.split(" "):
if w.lower().endswith("-core"):
break
if w.lower() in ["processor"]:
continue
mycpu_toks.append(w)
mycpu = " ".join(mycpu_toks)
with open(cls.CPU_TDP_FILE) as f:
for line in f:
model, tdp = line.rstrip('\n').split(",")
if model == mycpu:
return float(tdp.rstrip("W")) * 1e6
return None
@classmethod
def info(cls):
cpuinfo = cls.parse_lscpu()
if cpuinfo:
model = cpuinfo["Model name"]
sockets = int(cpuinfo["Socket(s)"])
threads = int(cpuinfo["CPU(s)"])
cores = int(threads / int(cpuinfo["Thread(s) per core"]))
print("CPU model: ", model)
print("CPU sockets/cores/threads:", sockets, "/", cores, "/", threads)
else:
print("CPU info not available")
class CpuFreqHelper(object):
SYSFS_CPU_PATH = "/sys/devices/system/cpu/cpu{0}/cpufreq/{1}"
KHZ, MHZ, GHZ = 1, 1e3, 1e6
@classmethod
def cpu_field_fname(cls, cpu, field):
return cls.SYSFS_CPU_PATH.format(cpu, field)
@classmethod
def available(cls):
return os.path.isfile(cls.cpu_field_fname(0, "scaling_driver"))
@classmethod
def info(cls):
if cls.available():
print ("DVFS settings: driver = " + cls.get_driver() + ", governor = " + cls.get_governor())
hw_fmin = round(cls.get_hw_min_freq(0, cls.MHZ))
hw_fmax = round(cls.get_hw_max_freq(0, cls.MHZ))
gov_fmin = round(cls.get_gov_min_freq(0, cls.MHZ))
gov_fmax = round(cls.get_gov_max_freq(0, cls.MHZ))
print ("DVFS HW limits: " + str(hw_fmin) + " - " + str(hw_fmax) + " MHz")
print ("DVFS policy: " + str(gov_fmin) + " - " + str(gov_fmax) + " MHz")
else:
print("DVFS driver not found.")
@classmethod
def get_string(cls, name, cpu=0):
try:
return read_value(cls.cpu_field_fname(cpu, name))
except:
return None
@classmethod
def get_int(cls, name, cpu=0):
s = cls.get_string(name, cpu)
return None if s is None else int(s)
@classmethod
def get_int_scaled(cls, name, cpu=0, unit=KHZ):
s = cls.get_string(name, cpu)
if s:
return int(s) / unit
else:
return None
@classmethod
def get_driver(cls):
if cls.available():
return cls.get_string("scaling_driver").strip()
else:
return None
@classmethod
def get_governor(cls):
return cls.get_string("scaling_governor").strip()
@classmethod
def get_hw_min_freq(cls, cpu=0, unit=KHZ):
return cls.get_int_scaled("cpuinfo_min_freq", cpu, unit)
@classmethod
def get_hw_max_freq(cls, cpu=0, unit=KHZ):
return cls.get_int_scaled("cpuinfo_max_freq", cpu, unit)
@classmethod
def get_hw_cur_freq(cls, cpu=0, unit=KHZ):
return cls.get_int_scaled("cpuinfo_cur_freq", cpu, unit)
@classmethod
def get_gov_min_freq(cls, cpu=0, unit=KHZ):
return cls.get_int_scaled("scaling_min_freq", cpu, unit)
@classmethod
def get_gov_max_freq(cls, cpu=0, unit=KHZ):
return cls.get_int_scaled("scaling_max_freq", cpu, unit)
@classmethod
def get_gov_cur_freq(cls, cpu=0, unit=KHZ):
return cls.get_int_scaled("scaling_cur_freq", cpu, unit)
@classmethod
def get_avg_gov_cur_freq(cls, unit=KHZ):
cpu = 0
fsum = 0
while True:
fcpu = cls.get_gov_cur_freq(cpu, unit)
if fcpu:
fsum += fcpu
cpu += 1
else:
break
return fsum / cpu
@classmethod
def set_cpu_field_value(cls, cpu, field, value):
return write_value(cls.cpu_field_fname(cpu, field), value)
@classmethod
def set_field_value(cls, field, value):
cpu = 0
while cls.set_cpu_field_value(cpu, field, value):
cpu += 1
@classmethod
def set_gov_max_freq(cls, freq):
cls.set_field_value("scaling_max_freq", freq)
class CpuPowerHelper(object):
@classmethod
def set_max_freq(cls, freq):
call("cpupower frequency-set -u " + str(freq) + " > /dev/null", shell=True)
class LinuxPowercapHelper(object):
INTEL_RAPL_PATH="/sys/class/powercap/intel-rapl:"
PKG_MAX=256
UWATT, MWATT, WATT = 1, 1e3, 1e6
@classmethod
def package_path(cls, pkg):
return cls.INTEL_RAPL_PATH + str(pkg)
@classmethod
def package_file(cls, pkg, fname):
return os.path.join(cls.package_path(pkg), fname)
@classmethod
def read_package_int(cls, pkg, fname):
return read_int_value(cls.package_file(pkg, fname))
@classmethod
def package_list(cls, domain="package-"):
l = []
pkg = 0
while pkg < cls.PKG_MAX:
fname = cls.package_file(pkg, "name")
if not os.path.isfile(fname):
break;
pkg_name = read_value(fname)
if pkg_name.startswith(domain):
l += [str(pkg)]
if domain in ["dram", "core", "uncore"]:
subpkg = 0
while subpkg < cls.PKG_MAX:
subpkg_code = str(pkg) + ":" + str(subpkg)
fname = cls.package_file(subpkg_code, "name")
if not os.path.isfile(fname):
break;
pkg_name = read_value(fname)
if pkg_name.startswith(domain):
l += [subpkg_code]
subpkg += 1
pkg += 1
return l
@classmethod
def available(cls, readonly=False):
if readonly:
return os.path.isfile(cls.package_file(0, "energy_uj"))
else:
return os.path.isfile(cls.package_file(0, "constraint_0_power_limit_uw"))
@classmethod
def enabled(cls, pkg=0):
return cls.read_package_int(pkg, "enabled") != 0
@classmethod
def info(cls):
if cls.available(True):
outfmt = "RAPL {0} domains: count = {1}, hw_limit = {2} W, current_limit = {3} W"
cpus = cls.package_list()
if len(cpus):
maxp = cls.get_package_hw_max_power(cpus[0], cls.WATT)
curp = cls.get_package_power_limit(cpus[0], cls.WATT)
print(outfmt.format("CPU ", len(cpus), maxp, curp))
dram = cls.package_list("dram")
if len(dram):
try:
maxp = cls.get_package_hw_max_power(dram[0], cls.WATT)
except OSError:
maxp = None
curp = cls.get_package_power_limit(dram[0], cls.WATT)
print(outfmt.format("DRAM", len(dram), maxp, curp))
psys = cls.package_list("psys")
if len(psys):
try:
maxp = cls.get_package_hw_max_power(psys[0], cls.WATT)
except OSError:
maxp = None
curp = cls.get_package_power_limit(psys[0], cls.WATT)
print(outfmt.format("PSYS", len(psys), maxp, curp))
else:
print("RAPL powercap not found.")
@classmethod
def get_package_hw_max_power(cls, pkg, unit=UWATT):
if cls.available():
return cls.read_package_int(pkg, "constraint_0_max_power_uw") / unit
else:
return None
@classmethod
def get_package_power_limit(cls, pkg, unit=UWATT):
if cls.available():
return cls.read_package_int(pkg, "constraint_0_power_limit_uw") / unit
else:
return None
@classmethod
def get_package_energy(cls, pkg):
return cls.read_package_int(pkg, "energy_uj")
@classmethod
def get_package_energy_range(cls, pkg):
return cls.read_package_int(pkg, "max_energy_range_uj")
@classmethod
def get_power_limit(cls, unit=UWATT):
power = 0
for pkg in cls.package_list():
power += cls.get_package_power_limit(pkg, unit)
return power
@classmethod
def set_package_power_limit(cls, pkg, power, unit=UWATT):
val = round(power * unit)
write_value(cls.package_file(pkg, "constraint_0_power_limit_uw"), val)
@classmethod
def reset_package_power_limit(cls, pkg):
# write_value(cls.package_file(pkg, "constraint_0_power_limit_uw"), round(cls.get_package_hw_max_power(pkg)))
cls.set_package_power_limit(pkg, cls.get_package_hw_max_power(pkg))
@classmethod
def set_power_limit(cls, power, unit=UWATT):
for pkg in cls.package_list():
cls.set_package_power_limit(pkg, power, unit)
class AMDEsmiHelper(object):
CMD_ESMI_TOOL="/opt/e-sms/e_smi/bin/e_smi_tool"
MAX_PLIMIT_LABEL="PowerLimitMax (Watts)"
CUR_PLIMIT_LABEL="PowerLimit (Watts)"
UWATT, MWATT, WATT = 1e-6, 1e-3, 1
@classmethod
def run_esmi(cls, params, parse_out=True):
cmdline = cls.CMD_ESMI_TOOL + " " + params
try:
out = check_output(cmdline, shell=True, stderr=DEVNULL, universal_newlines=True)
except CalledProcessError as e:
if e.returncode == 210:
out = e.output
else:
raise e
if parse_out:
result = {}
for line in out.split("\n"):
if line:
toks = line.split("|")
if len(toks) > 2:
field = toks[1].strip()
result[field] = toks[2:-1]
# print(result)
return result
@classmethod
def available(cls):
try:
out = cls.run_esmi("-v")
return True
except CalledProcessError:
return False
@classmethod
def enabled(cls, pkg=0):
try:
if cls.get_package_power_limit(pkg):
return True
else:
return False
except CalledProcessError:
return False
@classmethod
def get_field(cls, out, field, pkg=0):
if pkg >= 0:
return out[field][pkg]
else:
return out[field]
@classmethod
def get_package_hw_max_power(cls, pkg, unit=WATT):
if cls.available():
params = "--showsockpower"
out = cls.run_esmi(params)
limit_w = float(cls.get_field(out, cls.MAX_PLIMIT_LABEL, pkg))
return limit_w / unit
else:
return None
@classmethod
def get_package_power_limit(cls, pkg, unit=WATT):
if cls.available():
params = "--showsockpower"
out = cls.run_esmi(params)
limit_w = float(cls.get_field(out, cls.CUR_PLIMIT_LABEL, pkg))
return limit_w / unit
else:
return None
@classmethod
def get_power_limit(cls, unit=WATT):
if cls.available():
params = "--showsockpower"
out = cls.run_esmi(params)
pkg_limit_w = cls.get_field(out, cls.CUR_PLIMIT_LABEL, -1)
limit_w = sum([float(x) for x in pkg_limit_w])
return limit_w / unit
else:
return None
@classmethod
def set_package_power_limit(cls, pkg, power, unit=WATT):
# value must be in mW !
val = round(power * unit / cls.MWATT)
params = "--setpowerlimit {:d} {:d}".format(pkg, val)
cls.run_esmi(params, False)
@classmethod
def set_power_limit(cls, power, unit=WATT):
num_sockets = CpuInfoHelper.get_sockets()
for pkg in range(num_sockets):
cls.set_package_power_limit(pkg, power, unit)
@classmethod
def info(cls):
if cls.available():
outfmt = "ESMI CPU{0}: max_hw_limit = {1} W, current_limit = {2} W"
params = ""
out = cls.run_esmi(params)
num_sockets = int(cls.get_field(out, "NR_SOCKETS"))
for pkg in range(num_sockets):
maxp = float(cls.get_field(out, cls.MAX_PLIMIT_LABEL, pkg))
curp = float(cls.get_field(out, cls.CUR_PLIMIT_LABEL, pkg))
print(outfmt.format(pkg, maxp, curp))
else:
print("AMD E-SMI tool not found.")
# Code adapted from s-tui:
# https://github.com/amanusk/s-tui/commit/5c87727f5a2364697bfce84a0b688c1a6d2b3250
class AMDRaplMsrHelper(object):
MSR_CPU_PATH="/dev/cpu/{0}/msr"
TOPOL_CPU_PATH="/sys/devices/system/cpu/cpu{0}/topology/physical_package_id"
CPU_MAX = 4096
UNIT_MSR = 0xC0010299
CORE_MSR = 0xC001029A
PACKAGE_MSR = 0xC001029B
ENERGY_UNIT_MASK = 0x1F00
ENERGY_STATUS_MASK = 0xffffffff
UJOULE_IN_JOULE = 1e6
@staticmethod
def read_msr(filename, register):
with open(filename, "rb") as f:
f.seek(register)
res = int.from_bytes(f.read(8), sys.byteorder)
return res
@classmethod
def package_list(cls):
pkg_list = set()
for cpu in range(cls.CPU_MAX):
fname = cls.TOPOL_CPU_PATH.format(cpu)
if not os.path.isfile(fname):
break
pkg = read_int_value(fname)
pkg_list.add(pkg)
return list(pkg_list)
@classmethod
def pkg_to_cpu(cls, pkg):
for cpu in range(cls.CPU_MAX):
fname = cls.TOPOL_CPU_PATH.format(cpu)
if not os.path.isfile(fname):
break;
if read_int_value(fname) == cpu:
return cpu
return None
@classmethod
def cpu_msr_file(cls, cpu):
return cls.MSR_CPU_PATH.format(cpu)
@classmethod
def pkg_msr_file(cls, pkg):
cpu = cls.pkg_to_cpu(pkg)
return cls.cpu_msr_file(cpu)
@classmethod
def get_energy_factor(cls, filename):
unit_msr = cls.read_msr(filename, cls.UNIT_MSR)
energy_factor = 0.5 ** ((unit_msr & cls.ENERGY_UNIT_MASK) >> 8)
return energy_factor * cls.UJOULE_IN_JOULE
@classmethod
def get_energy_range(cls, filename):
return cls.ENERGY_STATUS_MASK * cls.get_energy_factor(filename)
@classmethod
def get_energy(cls, filename, register):
energy_factor = cls.get_energy_factor(filename)
package_msr = cls.read_msr(filename, register)
energy = package_msr * energy_factor
# print ("amd pkg_energy: ", energy)
return energy
@classmethod
def get_package_energy(cls, pkg):
filename = cls.pkg_msr_file(pkg)
return cls.get_energy(filename, cls.PACKAGE_MSR)
@classmethod
def get_core_energy(cls, cpu):
filename = cls.cpu_msr_file(cpu)
return cls.get_energy(filename, cls.CORE_MSR)
@classmethod
def get_package_energy_range(cls, pkg):
filename = cls.pkg_msr_file(pkg)
return cls.get_energy_range(filename)
@classmethod
def get_core_energy_range(cls, cpu):
filename = cls.cpu_msr_file(cpu)
return cls.get_energy_range(filename)
class LinuxCgroupHelper(object):
CGROUP_FS_PATH="/sys/fs/cgroup/"
@classmethod
def available(cls):
return os.path.exists(cls.CGROUP_FS_PATH)
@classmethod
def subsystems(cls, grp=""):
sub = []
if cls.available():
for sname in ["cpu", "freezer"]:
if cls.enabled(sname, grp):
sub.append(sname)
return sub
@classmethod
def info(cls):
print("Linux cgroup available: ", end ="")
if cls.available():
print("YES", end ="")
helper = None
if LinuxCgroupV1Helper.enabled():
helper = LinuxCgroupV1Helper
elif LinuxCgroupV2Helper.enabled():
helper = LinuxCgroupV2Helper
if helper:
print(" ({}) ({})".format(helper.VERSION, ",".join(helper.subsystems())))
else:
print("(disabled)")
else:
print("NO")
class LinuxCgroupV1Helper(LinuxCgroupHelper):
VERSION = "v1"
PROCS_FILE="cgroup.procs"
CFS_QUOTA_FILE="cpu.cfs_quota_us"
CFS_PERIOD_FILE="cpu.cfs_period_us"
FREEZER_STATE_FILE="freezer.state"
@classmethod
def subsys_path(cls, sub):
return os.path.join(cls.CGROUP_FS_PATH, sub)
@classmethod
def subsys_file(cls, sub, grp, fname):
return os.path.join(cls.subsys_path(sub), grp, fname)
@classmethod
def procs_file(cls, sub, grp):
return cls.subsys_file(sub, grp, cls.PROCS_FILE)
@classmethod
def cfs_quota_file(cls, grp):
return cls.subsys_file("cpu", grp, cls.CFS_QUOTA_FILE)
@classmethod
def cfs_period_file(cls, grp):
return cls.subsys_file("cpu", grp, cls.CFS_PERIOD_FILE)
@classmethod
def freezer_state_file(cls, grp):
return cls.subsys_file("freezer", grp, cls.FREEZER_STATE_FILE)
@classmethod
def read_cgroup_int(cls, sub, grp, fname):
return read_int_value(cls.subsys_file(sub, grp, fname))
@classmethod
def get_cpu_cfs_period_us(cls, grp):
return read_int_value(cls.cfs_period_file(grp))
@classmethod
def set_cpu_cfs_period_us(cls, grp, period_us):
return write_value(cls.cfs_period_file(grp), period_us)
@classmethod
def get_cpu_cfs_quota_us(cls, grp):
return read_int_value(cls.cfs_quota_file(grp))
@classmethod
def set_cpu_cfs_quota_us(cls, grp, quota_us):
write_value(cls.cfs_quota_file(grp), int(quota_us))
@classmethod
def set_cpu_quota(cls, grp, quota, period=None):
if period:
cls.set_cpu_cfs_period_us(grp, period)
else:
period = cls.get_cpu_cfs_period_us(grp)
quota_us = int(quota * period)
cls.set_cpu_cfs_quota_us(grp, quota_us)
@classmethod
def get_cpu_quota(cls, grp, ncores):
quota_us = cls.get_cpu_cfs_quota_us(grp)
period_us = cls.get_cpu_cfs_period_us(grp)
if quota_us == -1:
return ncores
else:
return float(quota_us) / period_us
@classmethod
def freeze(cls, grp):
write_value(cls.freezer_state_file(grp), "FROZEN")
@classmethod
def unfreeze(cls, grp):
write_value(cls.freezer_state_file(grp), "THAWED")
@classmethod
def add_proc_to_cgroup(cls, grp, pid):
write_value(cls.procs_file(grp), pid)
@classmethod
def enabled(cls, sub="cpu", grp=""):
return os.path.isfile(cls.procs_file(sub, grp))
class LinuxCgroupV2Helper(LinuxCgroupHelper):
VERSION = "v2"
PROCS_FILE="cgroup.procs"