-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgqueue
More file actions
executable file
·381 lines (296 loc) · 13.6 KB
/
gqueue
File metadata and controls
executable file
·381 lines (296 loc) · 13.6 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# by slemaire <[email protected]>
# this code follows the methodology given in https://doi.org/10.1002/advs.202100707
import os
import subprocess
import re
import argparse
from datetime import timedelta, datetime
import sys
import glob
import socket
import json
MEMORY_CONSUMPTION = 0.3725 # in W/GB
DEFAULT_PUE = 1.57 # (Power Usage Efficiency, worldwide average in 2021 from Uptime Institute)
def get_co2(time, ncores, TDP_per_core, RAM_per_core, cluster_PUE, cluster_carbon_intensity):
"""
Get the CO2e in g implementing equation (4) from https://doi.org/10.1002/advs.202100707
Parameters:
-----------
time: float
computation duration in seconds
ncores: int
number of cores used in the computation
TDP_per_core: float
TDP of the compute node CPU divided by its number of cores, in W/core
RAM_per_core: float
RAM available on a compute node divided by its number of cores, in GB/core
cluster_PUE: float
ratio between the total power drawn of the cluster facility and the power used by computing equipment
cluster_carbon_intensity: float
carbon footpring of producing a quantity of energy, in gCO2e/kWh
Return:
-------
float
carbon footprint of the computation in gCO2e
"""
t = time/60/60 #time in hours
nc = ncores # number of cores
Pc = TDP_per_core # power draw of a computing core
uc = 1
nm = nc*RAM_per_core # in GB
Pm = MEMORY_CONSUMPTION #in W/GB
PUE = cluster_PUE
E = t*(nc*Pc*uc + nm*Pm)*PUE*0.001
return E*cluster_carbon_intensity
def human_readable(size, decimal_places=1):
for unit in ['gCO2e','kgCO2e','TCO2e']:
if size < 1000.0:
break
size /= 1000.0
return f"{size:.{decimal_places}f} {unit}"
def progress_bar(ratio, size=10):
nb_bar = int(ratio*size+0.5)
return nb_bar*"█" + (size-nb_bar)*"─"
def duration2sec(duration):
"""
Converts slurm duration string format in number of seconds. Accepted input formats are:
d-HH:MM:SS, HH:MM:SS and MM:SS
"""
d = 0
h = 0
parse = re.match("([0-9]*)-([0-9]{2}):([0-9]{2}):([0-9]{2})", duration)
if parse:
d = parse.group(1)
h = parse.group(2)
m = parse.group(3)
s = parse.group(4)
else:
parse = re.match("^([0-9]+):([0-9]{2}):([0-9]{2})$", duration)
if parse:
h = parse.group(1)
m = parse.group(2)
s = parse.group(3)
else:
parse = re.match("^([0-9]+):([0-9]{2})$", duration)
m = parse.group(1)
s = parse.group(2)
return int(d)*3600*24 + int(h)*3600 + int(m)*60 + int(s)
class Cluster():
"""
Encomparses all the information given in a cluster json file
"""
def __init__(self, cluster_filename):
with open(cluster_filename, "r") as cluster_file:
self.cluster_info = json.load(cluster_file)
self.filename = cluster_filename
if "PUE" in self.cluster_info:
self.PUE = self.cluster_info["PUE"]
else:
self.PUE = DEFAULT_PUE
self.country = self.cluster_info["country"]
self.default_partition = self.cluster_info["default_partition"]
self.hostnames = self.cluster_info["hostnames"]
self.carbon_intensity = float(self.cluster_info["carbon_intensity"])
def set_carbon_intensity(self, carbon_intensity):
self.carbon_intensity = carbon_intensity
self.country = "custom"
def load_partitions(self):
"""
Loads partition data from cluster_info data. Separate function used for performance reasons
"""
self.partition_dict = {}
self.partition_names = []
for partition in self.cluster_info["partitions"]:
for partition_name in partition["partition_names"]:
self.partition_dict[partition_name] = partition
self.partition_names.append(partition_name)
def get_CPUh_footprint(self, partition_name=None):
"""
Returns the carbon footprint of a partition hardware in gCO2e/(CPU.h)
"""
if not partition_name: partition_name = self.default_partition
return get_co2(time=60*60,
ncores=1,
TDP_per_core=self.partition_dict[partition_name]["TDP_per_core"],
RAM_per_core=self.partition_dict[partition_name]["RAM_per_core"],
cluster_PUE=self.PUE,
cluster_carbon_intensity=self.carbon_intensity)
class Job():
def __init__(self, squeue_line, cluster):
squeue_line = squeue_line.split(" ")
self.jobID = squeue_line[0]
self.status = squeue_line[1]
self.is_running = (squeue_line[1] == "RUNNING")
self.ncores = int(squeue_line[2])
self.nnode = int(squeue_line[3])
self.job_name = squeue_line[4]
self.total_duration = duration2sec(squeue_line[5])
self.elapsed_time = duration2sec(squeue_line[6])
self.partition_name = squeue_line[7]
self.reason = squeue_line[8]
self.start_time = squeue_line[9]
self.directory = squeue_line[-1].split("/")[-1]
self.cluster = cluster
if self.partition_name in self.cluster.partition_dict:
self.partition = self.cluster.partition_dict[self.partition_name]
else:
self.partition = self.cluster.partition_dict[self.cluster.default_partition]
def get_url(self):
"""
Generates a sharable url from a running job,
Still work in progress as location information isn't known by the script (CI info can't be inputed in the url)
"""
url = "https://green-algorithms.org//?runTime_hour={hours}&runTime_min={minutes}&locationContinent=Europe&locationCountry=Netherlands&locationRegion=NL&PUEradio=Yes&PUE={PUE}&coreType=CPU&numberCPUs={ncores}&CPUmodel=other&tdpCPU={TDP}&memory={total_RAM}&platformType=localServer".format(
hours=int(self.elapsed_time/60/60),
minutes=int(self.elapsed_time/60 - int(self.elapsed_time/60/60)*60),
PUE=self.cluster.PUE,
ncores=self.ncores,
TDP=self.partition["TDP_per_core"],
total_RAM=self.partition["RAM_per_core"]*self.ncores)
return url
def get_co2(self, time):
return get_co2(time,
ncores=self.ncores,
TDP_per_core=self.partition["TDP_per_core"],
RAM_per_core=self.partition["RAM_per_core"],
cluster_PUE=self.cluster.PUE,
cluster_carbon_intensity=self.cluster.carbon_intensity)
#############################################
# Display functions
#############################################
def display_history(cluster, user_name, days_list=[1, 7, 30, 30*3]):
"""
Displays past carbon footprint for a particular user.
This is an approximation as the partition is assumed to be the default cluster one.
"""
# Display history information
print("Carbon footprint over the last:")
for ndays in days_list:
today_minus_ndays = (datetime.now() - timedelta(days=ndays)).strftime("%Y-%m-%dT%H:%M:%S")
sreport_raw = subprocess.check_output(["sreport", "-P", "-t", "Second", "user", "Top", "TopCount=30000", "Users={}".format(user_name), "Start={}".format(today_minus_ndays)]).splitlines()
cpu_s = 0
for line in sreport_raw[5:]:
cpu_s += int(line.decode(sys.stdout.encoding).split("|")[4])
co2 = get_co2(cpu_s,
ncores=1,
TDP_per_core=cluster.partition_dict[cluster.default_partition]["TDP_per_core"],
RAM_per_core=cluster.partition_dict[cluster.default_partition]["RAM_per_core"],
cluster_PUE=cluster.PUE,
cluster_carbon_intensity=cluster.carbon_intensity)
if not ndays == 1:
plural="s"
else:
plural=""
print("{} day{}:".format(ndays, plural), human_readable(co2))
def print_table(output, row_color=None):
header = True
widths = [max(map(len, col)) for col in zip(*output)]
for i,row in enumerate(output):
output_string = " ".join((val.ljust(width) for val, width in zip(row, widths)))
if header:
header = False
print(output_string)
print("─"*len(output_string))
else:
if row_color and row_color[i-1]:
print('\033[2m', end="")
print(output_string, end="")
print('\033[0m')
def display_joblist(cluster, user_name):
"""
Displays the job list currently in the queue and their respective footprint
"""
# Load information about jobs in queue/running
squeue_raw = subprocess.check_output(["squeue", "-S", "-T,u,i", "-h", "-u", user_name, "-o", "%A %T %C %D %j %l %M %P %R %S %Z"]).splitlines()
job_list = [ Job(line.decode(sys.stdout.encoding), cluster) for line in squeue_raw ]
# Display job information
column_names = ["Directory", "Job name", "Job-ID", "Partition", "Cores", "Status", "CO2", "Total CO2"]
output = [column_names, ]
for job in job_list:
output_line = []
output_line.append(job.directory)
output_line.append(job.job_name)
output_line.append(str(job.jobID))
output_line.append(job.partition_name)
output_line.append(str(job.ncores))
if job.is_running:
output_line.append(progress_bar(job.elapsed_time/job.total_duration))
output_line.append(human_readable(job.get_co2(job.elapsed_time)))
else:
output_line.append(job.status)
output_line.append("-")
output_line.append(human_readable(job.get_co2(job.total_duration)))
output.append(output_line)
is_not_running_list = [ not job.is_running for job in job_list ]
print_table(output, is_not_running_list)
def display_cluster_info(cluster):
print("Config filename: {}".format(cluster.filename))
print("Carbon intensity: {} gCO2e/kWh ({})".format(cluster.carbon_intensity, cluster.country))
detail = ""
if cluster.PUE == DEFAULT_PUE:
detail = " (world average)"
print("Power Usage Efficiency: {}".format(cluster.PUE), detail)
print()
column_names = ["Partition", "TDP per core", "RAM per core", "Footprint per CPU.h"]
output = [column_names, ]
for partition_name in cluster.partition_names:
output_line = []
if partition_name == cluster.default_partition:
output_line.append(partition_name+"*")
else:
output_line.append(partition_name)
output_line.append("{} W".format(cluster.partition_dict[partition_name]["TDP_per_core"]))
output_line.append("{} GB".format(cluster.partition_dict[partition_name]["RAM_per_core"]))
output_line.append("{:.2f} gCO2e/(CPU.h)".format(cluster.get_CPUh_footprint(partition_name)))
output.append(output_line)
print_table(output)
if __name__ == "__main__":
# Argument parsing
parser = argparse.ArgumentParser(description='CLI tool to compute CO2 emissions of HPC computations following green-algorithms.org methodology on slurm systems.')
parser.add_argument('-p', '--partition', action='store_true', default=False,
help='Displays partitions information')
parser.add_argument('-j', '--job', action='store_true', default=False,
help='Displays footprint of jobs in queue')
parser.add_argument('-r', '--history', action='store_true', default=False,
help='Displays footprint of past jobs over the last 1, 7, 30 and 90 days')
parser.add_argument('-c', '--cluster', type=str, default=None,
help='Cluster .json file to use, if omited autodetection is used')
parser.add_argument('-u', '--user', type=str, default=None,
help='User to show analysis about, if omited the current user is used')
parser.add_argument('--carbon-intensity', type=float, default=None,
help='Overwrites carbon internsity information from cluster data, specify value in gCO2/kWh')
parser.add_argument('-a', '--all', action='store_true', default=False,
help='Displays everything, equivalent to -p -j -r')
args = parser.parse_args()
if not args.user is None:
user_name = args.user
else:
user_name = os.getlogin()
# Load cluster information
cluster = None
if not args.cluster is None and os.path.isfile(args.cluster):
cluster = Cluster(args.cluster)
cluster.load_partitions()
else:
hostname = socket.gethostname()
for cluster_filename in glob.glob(os.path.dirname(__file__) + "/cluster_data/*.json"):
cluster = Cluster(cluster_filename)
if hostname in cluster.hostnames:
cluster.load_partitions()
break
# Exit if missing cluster configuration: TODO throw a proper error
if not cluster:
sys.exit("Missing input file in {}/cluster_data for hostname {}".format(os.path.dirname(__file__), hostname))
if not args.carbon_intensity is None:
cluster.set_carbon_intensity(args.carbon_intensity)
# Displays data
if args.partition or args.all:
display_cluster_info(cluster)
print()
if args.job or (not args.partition and not args.job and not args.history) or args.all:
display_joblist(cluster, user_name)
print()
if args.history or (not args.partition and not args.job and not args.history) or args.all:
display_history(cluster, user_name)