footprints.py 53 KB
Newer Older
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
#!/usr/bin/env python

from __future__ import print_function

import argparse
import os
import subprocess
import sys
import hostlist

#import mysql.connector as mariadb
import pymysql as mariadb

import ast
import operator # max function
import json
import time

from datetime import datetime
from datetime import timedelta
from influxdb import InfluxDBClient

debug_file = sys.stderr
debug_flag = False

def print_info(*args, **kwargs):
  global debug_file
  print(*args, file=debug_file, **kwargs)

def print_debug(*args, **kwargs):
  global debug_flag
  if debug_flag:
    print("DEBUG:", *args, file=sys.stderr, **kwargs)
  

### conversion of large values
unitthresholds = (
        (10**16, 'P'),
        (10**13, 'T'),
        (10**10, 'G'),
        (10**7, 'M'),
        (10**4, 'K'),
        (1, '')
    )

# conversion factor for unit prefixes: binary, decimal
unit2fac = {
  "P": (1<<50L, 10**15),
  "T": (1<<40L, 10**12),
  "G": (1<<30L, 10**9),
  "M": (1<<20L, 10**6),
  "K": (1<<10L, 10**3),
  "": (1, 1)
}

def getUnitAndFactor(unit, value):
  metric_divide = 1
  for (factor, quantifier) in unitthresholds:
    if value >= factor:
      if unit.startswith('Xi'):
        metric_divide = unit2fac[quantifier][0]
      else:
        metric_divide = unit2fac[quantifier][1]

      unit = unit.replace('X', quantifier, 1)
      break
      
  if unit.startswith('iB'):
    unit = unit.replace('iB', 'bytes', 1)
  
  return ( unit, metric_divide )

### Taurus partition - available CPU cores per node
partition_cpu_num = {
   "haswell":24,
   "west":12,
   "sandy":16,
   "broadwell":28,
   "gpu1":16,
   "gpu2":24,
   "smp1":32,
   "smp2":64,
   "knl":64,
   "hpdlf":12,
   "ml":174
}

partition_gpu_num = {
  "gpu1":2,
  "gpu2":4,
  "ml":6
}

# non-contiguous timeline data
# per socket data
# per cpu data
# per node data

#measurements_metrics = {
  #'likwid_cpu': ('flops_any', 'cpi'), # shared hosts clause
  #'likwid_socket' : ('mem_bw', 'rapl_power'), # socket hostname clause
  #'cpu' : ('used',), # shared hosts clause
  #'memory' : ('used',),
  #'infiniband' : ('bw',),
  #'lustre_scratch2' : ('read_bw', 'write_bw', 'read_requests', 'write_requests', 'open', 'close', 'fsync', 'seek'), # no 'create' in measurement
  #'lustre_highiops' : ('read_bw', 'write_bw', 'read_requests', 'write_requests', 'open', 'close', 'fsync', 'seek'), # no 'create' in measurement
  #'nvml' : ('gpu_used','mem_used','power','temp')
#}

ipc_avail = False # Do we have IPC or CPI values?
mflops = False # Are flops_any in MFLOPS?

# base performance metrics
perf_foot_metrics = {
  'likwid_cpu': (('ipc','mean'),('flops_any','mean')),
  'likwid_socket' : (('mem_bw','mean'), ('rapl_power','mean')),
  'cpu' : (('used','mean'),), # shared hosts clause
  'memory' : (('used','max'),),
  'infiniband' : (('bw','mean'),),
  'lustre_scratch2' : (('read_bw','mean'), ('write_bw','mean')), 
  'lustre_highiops' : (('read_bw','mean'), ('write_bw','mean')),
  'nvml' : (('gpu_used','mean'), ('mem_used','max'),('power','mean'))
}

# maximum per job values for selected metrics
perf_max_per_job = {
  'likwid_cpu': ('flops_any',), 
  'cpu' : ('used',), 
  'infiniband' : ('bw',),
  'lustre_scratch2' : ('read_bw', 'write_bw', 'read_requests', 'write_requests', 'open', 'close', 'fsync', 'seek'), 
  'lustre_highiops' : ('read_bw', 'write_bw', 'read_requests', 'write_requests', 'open', 'close', 'fsync', 'seek'), 
  'nvml' : ('gpu_used',)
}

# Generate more comprehensive footprint based on per node select statements
# performance metrics and their aggregate
# structure: measurement : ((metric1,aggregate1[,aggregate2,...]),[(metric1,aggregate1[,aggregate2,...]),...]
perf_per_node = {
  'likwid_cpu': (('flops_any','mean','max'), ('ipc','mean','max')), 
  'likwid_socket' : (('mem_bw','mean','max'), ('rapl_power','mean','max')),
  'cpu' : (('used','mean','max'),), 
  'memory' : (('used','max'),),
  'infiniband' : (('bw','mean'),),
  'lustre_scratch2' : (('read_bw','mean'), ('write_bw','mean'), ('read_requests','mean'), ('write_requests','mean'), ('open','mean'), ('close','mean'), ('fsync','mean'), ('seek','mean')), 
  'lustre_highiops' : (('read_bw','mean'), ('write_bw','mean'), ('read_requests','mean'), ('write_requests','mean'), ('open','mean'), ('close','mean'), ('fsync','mean'), ('seek','mean')), 
  'nvml' : (('gpu_used','mean','max'), ('mem_used','max'),('power','mean','max'),('temp','mean','max'))
}

metric_name_mapping = {
  ('likwid_cpu','flops_any'):'flops',
  ('likwid_cpu','cpi'):'cpi',
  ('likwid_cpu','ipc'):'ipc',
  ('likwid_socket','mem_bw'):'mem_bw',
  #('likwid_socket','rapl_power','mean'):'cpu_power_avg',
  ('cpu','used'):'cpu_used',
  ('memory','used'):'memory', #host_mem_max
  ('infiniband','bw'):'ib_bw',
  ('lustre_scratch2','read_bw'):'lustre_scratch2_read_bw',
  ('lustre_scratch2','write_bw'):'lustre_scratch2_write_bw',
  ('lustre_highiops','read_bw'):'lustre_highiops_read_bw',
  ('lustre_highiops','write_bw'):'lustre_highiops_write_bw'
  #('nvml','gpu_used'):'gpu_used',
  #('nvml','mem_used':'gpu_mem_used',
  #('nvml','power':'gpu_power',
}

map_influx2maria = {
  ('likwid_cpu','flops_any'):('flops_any', 'per_core','footprint_base'),
  ('likwid_cpu','cpi'):('ipc','per_core','footprint_base'),
  ('likwid_cpu','ipc'):('ipc','per_core','footprint_base'),
  ('likwid_socket','mem_bw'):('mem_bw','per_socket','footprint_base'),
  ('likwid_socket','rapl_power'):('cpu_power','per_socket','footprint_base'),
  ('cpu','used'):('cpu_used', 'per_core','footprint_base'),
  ('memory','used'):('host_mem_used','per_node','footprint_base'), 
  ('infiniband','bw'):('ib_bw','per_node','footprint_base'),
  ('lustre_scratch2','read_bw'):('lustre_scratch2_read_bytes','per_node','footprint_fileio'),
  ('lustre_scratch2','write_bw'):('lustre_scratch2_write_bytes','per_node','footprint_fileio'),
  ('lustre_highiops','read_bw'):('lustre_highiops_read_bytes','per_node','footprint_fileio'),
  ('lustre_highiops','write_bw'):('lustre_highiops_write_bytes','per_node','footprint_fileio'),
  ('nvml','gpu_used'):('used','per_gpu','footprint_gpu'),
  ('nvml','mem_used'):('mem_used','per_gpu','footprint_gpu'),
  ('nvml','power'):('power','per_gpu','footprint_gpu')
}
    
def get_table_and_field_name(measurement, metric, aggregate):
  maria_name_tuple = map_influx2maria[(measurement,metric)]
  table_name = maria_name_tuple[2]
  field_name = maria_name_tuple[0]
  
  # exception for the file IO table (no "mean_per_node" as column suffix)
  if table_name != 'footprint_fileio':
    field_name += '_' + aggregate + '_' + maria_name_tuple[1]
  
  #table_name = "footprint_base"
  #field_name = ""
  #if measurement == 'likwid_socket':
    #field_name += '_per_socket'
  #elif 'nvml' == measurement:
    #field_name += '_per_gpu'
    #table_name = "footprint_gpu"
  #elif 'cpu' in measurement:
    #field_name += '_per_cpu'
  #else:
    #field_name += '_per_node'
    
  #if 'highiops' in measurement:
    #table_name = "footprint_lustre_highiops"
  #elif 'scratch2' in measurement:
    #table_name = "footprint_lustre_scratch2"

  return (table_name,field_name)


def get_metric_key(measurement, metric):
  if measurement == 'cpu':
    return "cpu_used"
  elif measurement == 'memory':
    return "main_mem_used"
  elif measurement.startswith("lustre_"):
    return measurement + "_" + metric
  elif measurement == 'infiniband':
    return "ib_" + metric
  elif measurement == 'nvml' and metric != 'gpu_used':
    return "gpu_" + metric
  else:
    return metric

PER_NODE, PER_SOCKET, PER_CORE = 0, 1, 2
num_nodes, num_sockets, num_cores = -1, -1, -1
metric_desc_tab = {
  'mem_bw':("Memory bandwidth","XiB/s", PER_SOCKET),
  'flops_any':("Normalized FLOPS","XFLOPs", PER_CORE),
  'cpi':("Cycles / instr.","CPI", PER_CORE),
  'ipc':("Instr./Cycle","IPC", PER_CORE),
  'write_bw':("Lustre write bandwidth","XiB/s", PER_NODE),
  'read_bw':("Lustre read bandwidth","XiB/s", PER_NODE),
  'main_mem_used':("Main memory used","XiB", PER_NODE),
  'ib_bw':("IB bandwidth","XiB/s", PER_NODE),
  'cpu_used':("CPU used/active","", PER_CORE),
  'rapl_power':("CPU power","W", PER_SOCKET),
  'gpu_used':("GPU used/active","", PER_NODE),
  'gpu_mem_used':("GPU memory used","XiB", PER_NODE),
  'gpu_power':("GPU power","W", PER_NODE),
  'gpu_temp':("GPU temperature","C", PER_NODE),
  'lustre_highiops_open':("highiops open","1/s", PER_NODE),
  'lustre_highiops_close':("highiops close","1/s", PER_NODE),
  'lustre_highiops_seek':("highiops seek","1/s", PER_NODE),
  'lustre_highiops_read_bw':("highiops read bw","XiB/s", PER_NODE),
  'lustre_highiops_write_bw':("highiops write bw","XiB/s", PER_NODE),
  'lustre_highiops_read_requests':("highiops read req","1/s", PER_NODE),
  'lustre_highiops_write_requests':("highiops write req","1/s", PER_NODE),
  'lustre_scratch2_open':("scratch2 open","1/s", PER_NODE),
  'lustre_scratch2_close':("scratch2 close","1/s", PER_NODE),
  'lustre_scratch2_seek':("scratch2 seek","1/s", PER_NODE),
  'lustre_scratch2_read_bw':("scratch2 read bw","XiB/s", PER_NODE),
  'lustre_scratch2_write_bw':("scratch2 write bw","XiB/s", PER_NODE),
  'lustre_scratch2_read_requests':("scratch2 read req","1/s", PER_NODE),
  'lustre_scratch2_write_requests':("scratch2 write req","1/s", PER_NODE),
}

metric_output_order = ['cpu_used', 'main_mem_used', 'ipc', 'flops_any', 'mem_bw', 'rapl_power', 'gpu_used', 'gpu_mem_used',
  'gpu_power', 'gpu_temp', 'ib_bw',
  'lustre_highiops_read_bw','lustre_highiops_write_bw','lustre_highiops_open','lustre_highiops_close','lustre_highiops_seek','lustre_highiops_read_requests','lustre_highiops_write_requests',
  'lustre_scratch2_read_bw','lustre_scratch2_write_bw','lustre_scratch2_open','lustre_scratch2_close','lustre_scratch2_seek','lustre_scratch2_read_requests','lustre_scratch2_write_requests']


def connect_to_mariadb():  
  #connection data for MariaDB 
  HOST = os.environ["MARIADB_HOST"]
  PORT = os.environ["MARIADB_PORT"]
  USER = os.environ["MARIADB_USER"]
  PASSWORD = os.environ["MARIADB_PASSWORD"]
  DATABASE = os.environ["MARIADB_DATABASE"]

  return mariadb.connect( host=HOST, port=int(PORT),
                          user=USER, passwd=PASSWORD,
                          db=DATABASE, connect_timeout=10)
  
   
influxdb_connection = None
influxdb_connection_st = None
influxdb_connection_lt = None
def connect_to_influxdb(isShortTerm=False):
  if isShortTerm:
    # connection data for InfluxDB 
    host = os.environ["INFLUXDB_HOST"]
    port = os.environ["INFLUXDB_PORT"]
    user = os.environ["INFLUXDB_USER"]
    password = os.environ["INFLUXDB_PASSWORD"]
    database = os.environ["INFLUXDB_DATABASE"]
  else:
    host = os.environ["INFLUXDB_LT_HOST"]
    port = os.environ["INFLUXDB_LT_PORT"]
    user = os.environ["INFLUXDB_LT_USER"]
    password = os.environ["INFLUXDB_LT_PASSWORD"]
    database = os.environ["INFLUXDB_LT_DATABASE"]
  
  # connect to database
  return InfluxDBClient(host, port, user, password, database)
  
def setInfluxConnection(job_start):
  global influxdb_connection
  
  # if job started within the last two weeks
  if job_start > (time.time() - 1209600):
    global influxdb_connection_st
    if influxdb_connection_st == None:
      influxdb_connection_st = connect_to_influxdb(True)
    influxdb_connection = influxdb_connection_st
  else:
    global influxdb_connection_lt
    if influxdb_connection_lt == None:
      influxdb_connection_lt = connect_to_influxdb(False)
    influxdb_connection = influxdb_connection_lt

"""
brief divide the value depending on the metric type
"""
def nat_divide(value, metric_key):
  metric_divide = 1
  if metric_key in metric_desc_tab:
    if metric_desc_tab[metric_key][2] == PER_CORE:
      metric_divide = num_cores
    elif metric_desc_tab[metric_key][2] == PER_NODE:
      metric_divide = num_nodes
    elif metric_desc_tab[metric_key][2] == PER_SOCKET:
      metric_divide = num_sockets
  
  return value/float(metric_divide)


def convert_cpulist_to_cpulistdict(cpulist):
  # taurusi5579[21-23],taurusi5592[0-3,10-16,22-23] -->
  # {'taurusi5579':'[21-23]','taurusi5592':'[0-3,10-16,22-23]'}
  cpulist_1 = cpulist.replace("[","':'[")
  cpulist_2 = cpulist_1.replace("],","]','")
  cpulist = str("{'") + cpulist_2 + str("'}")
  cpulist_dict = ast.literal_eval(cpulist)
  return cpulist_dict


def get_cores_num(partition):
  if "haswell" in partition:
    cpu_num = partition_cpu_num["haswell"]
  elif "west" in partition:
    cpu_num = partition_cpu_num["west"]
  elif "sandy" in partition:
    cpu_num = partition_cpu_num["sandy"]
  elif "broadwell" in partition:
    cpu_num = partition_cpu_num["broadwell"]
  elif "gpu1" in partition:
    cpu_num = partition_cpu_num["gpu1"]
  elif "gpu2" in partition:
    cpu_num = partition_cpu_num["gpu2"]
  elif "smp1" in partition:
    cpu_num = partition_cpu_num["smp1"]
  elif "smp2" in partition:
    cpu_num = partition_cpu_num["smp2"]
  elif "knl" in partition:
    cpu_num = partition_cpu_num["knl"]
  elif partition in partition_cpu_num:
    cpu_num = partition_cpu_num[partition]
  else:
    cpu_num = 24 #default
  return cpu_num

def get_socket_cpu(cpu, partition):
   #print partition

   # get number of cpus from partition dictionary
   cpu_num = get_cores_num(partition)

   # get cpu index of second socket (first socket has cpu index 0)
   socket_cpu_index = int(cpu_num/2)

   #print cpu
   #print socket_cpu_index

   if cpu < socket_cpu_index:
      return 0
   else:
      return socket_cpu_index

# returns "where" clause with socket cpus for all hosts and total number of sockets
def get_socket_hostnames_clause(cpulist_dict, partition):
  global num_sockets
  num_sockets = 0
  counter = 1
  hostnames_clause = "("
  num_nodes = len(cpulist_dict)
  for node in cpulist_dict:
    # get cpus
    cpus = hostlist.expand_hostlist(cpulist_dict[node])

    if len(cpus) == 0:
        break
    
    # get first and last cpu from list
    first_cpu = cpus[0]
    last_cpu = cpus[len(cpus)-1]
    socket_cpu_1 = get_socket_cpu(int(first_cpu), partition)
    socket_cpu_2 = get_socket_cpu(int(last_cpu), partition)

    if socket_cpu_1 == socket_cpu_2:
      cpu_clause = "(cpu='" + str(socket_cpu_1) + "')"
      num_sockets += 1
    else:
      cpu_clause = "(cpu='" + str(socket_cpu_1) + "' or cpu='" + str(socket_cpu_2) + "')"
      num_sockets += 2

    #print cpu_clause

    if counter < num_nodes:
        hostnames_clause += "(hostname='" + str(node) + "') and " + str(cpu_clause) + ") or ("
    else:
        hostnames_clause += "(hostname='" + str(node) + "') and " + str(cpu_clause) + ")"
    counter = counter + 1
   
  #print hostnames_clause

  return hostnames_clause
 
 
def get_cpu_clause(cpulist):
  cpu_idx_last = len(cpulist)-1
  cpu_idx = 0
  cpu_clause = "("
  for cpu in cpulist:
    if cpu_idx < cpu_idx_last:
      cpu_clause += "cpu='" + str(cpu) + "' or "
    else:
      cpu_clause += "cpu='" + str(cpu) + "')"
    cpu_idx += 1
      
  return cpu_clause

def get_cpu_hostnames_clause(cpulist_dict):
  num_nodes = len(cpulist_dict)
  counter = 1
  hostnames_clause = "("
  for node in cpulist_dict:
    try:
      cpus = hostlist.expand_hostlist(cpulist_dict[node])
    except:
      print_info("Could not expand CPU list for node ", str(node), "(" + str(cpulist_dict[node]) + ")")
      break

    cpu_clause = get_cpu_clause(cpus)

    if counter < num_nodes:
      hostnames_clause += "(hostname='" + str(node) + "') and " + cpu_clause + ") or ("
    else:
      hostnames_clause += "(hostname='" + str(node) + "') and " + cpu_clause + ")"
    counter = counter + 1
    
  #print hostnames_clause

  return hostnames_clause

def get_pur_hostnames_clause(nodelist):
  num_nodes = len(nodelist)
  counter = 1
  hostnames_clause = "("
  for node in nodelist:
    if counter < num_nodes:
      hostnames_clause += "hostname='" + str(node) + "' or "
    else:
      hostnames_clause += "hostname='" + str(node) + "')"
    counter = counter + 1

  return hostnames_clause

def get_hostnames_clauses(nodelist, cpulist_dict, partition, exclusive):
  # host names for measurements without CPU tags
  pure_hostnames_clause = get_pur_hostnames_clause(nodelist)

  # check if host names clause needs CPUs and sockets for non exclusive jobs
  if exclusive == 0: 
    # check input data:
    if len(nodelist) != len(cpulist_dict):
      print_info("len(nodelist) != len(cpulist_dict)")
    
    cpu_hostnames_clause = get_cpu_hostnames_clause(cpulist_dict)
    if not cpu_hostnames_clause:
      print_info("Could not generate shared hostname clause")
      return None
    socket_hostnames_clause = get_socket_hostnames_clause(cpulist_dict, partition)
  else:
    cpu_hostnames_clause = pure_hostnames_clause
    socket_hostnames_clause = cpu_hostnames_clause
    num_sockets = num_nodes * 2
    
  return (pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause)


def get_results_from_influxdb(query_str):
  global influxdb_connection
  
  #get all points
  try:
    query_result = influxdb_connection.query(query_str).get_points()
  except:
    print_info("Influx query failed! ", query_str)
    return None
  
  points = list(query_result)
  
  #print query_str, ":", points
  
  if len(points) > 0:
    return points[0]
  else:
    #if not ("scratch2" in query_str or "highiops" in query_str):
    #  print "No points on", query_str
    return None
  
def get_mean_ipc_from_cpi(where_clause):
  query_str = "select median(ipc) as medianipc, mean(ipc) as meanipc from (select 1/cpi as ipc from likwid_cpu where " + where_clause + ")"
  print_debug("get_mean_ipc_from_cpi: %s" % (query_str,))
  
  result_value = -1
  
  result = get_results_from_influxdb(query_str)
  if result and "meanipc" in result:
    result_value = float(result['meanipc'])
    if result_value > 50 and "medianipc" in result:
      result_value = float(result['medianipc'])
      print_info("Mean IPC = %f -> use median IPC = %f" % (float(result['meanipc']), result_value))
    
    if result_value > 50:
      print_info("Do not store IPC of %f" % (result_value,))
      return -1
      
  return result_value

# gather the native average and max values on a per node basis
def get_per_node_footprint(nodelist, cpulist_dict, exclusive, partition, time_clause):
  global ipc_avail
  global perf_per_node
  footprint = {} #used as call by reference
  
  if exclusive:
    nodes = nodelist
  else:
    nodes = cpulist_dict
    if len(nodelist) != len(cpulist_dict):
      print_info("len(nodelist) != len(cpulist_dict)")
      print_info("Node list:", nodelist)
      print_info("CPU list:", cpulist_dict)

  # get metrics for each node individually
  # detect outlier nodes based on the average values per node
  min_avg_values = {} # min average per node
  max_avg_values = {} # max average per node
  avg_for_job = {} # average including all node's data
  max_native_values = {} # max values for the metric's smallest unit (core/socket/node)
  min_native_values = {} # min values for the metric's smallest unit (core/socket/node)
  
  # get metrics for all nodes separately
  for node in nodes:
    # set hostname clause 
    hostname_clause = "hostname='" + str(node) + "'"
    
    # add CPUs to where clause for shared jobs
    if exclusive == 0:
      cpus = hostlist.expand_hostlist(cpulist_dict[node])
      cpu_clause = " and " + get_cpu_clause(cpus)
        
      where_clause_cpu = hostname_clause + cpu_clause + time_clause
      
      socket_cpu_1 = get_socket_cpu(int(cpus[0]), partition)
      socket_cpu_2 = get_socket_cpu(int(cpus[len(cpus)-1]), partition)

      if socket_cpu_1 == socket_cpu_2:
        cpu_clause = " and (cpu='" + str(socket_cpu_1) + "')"
      else:
        cpu_clause = " and (cpu='" + str(socket_cpu_1) + "' or cpu='" + str(socket_cpu_2) + "')"

      where_clause_socket = hostname_clause + cpu_clause + time_clause
    else:
      where_clause_cpu = hostname_clause + time_clause
      where_clause_socket = where_clause_cpu
    
    # iterate over all measurements
    for measurement in perf_per_node:
      ### generate select statement
      
      ### skip nvml for non-gpu partitions:
      if measurement == "nvml" and partition not in partition_gpu_num:
        continue
      
      # select where clause
      if 'socket' in measurement:
        where_clause = where_clause_socket
      elif 'cpu' in measurement:
        where_clause = where_clause_cpu
      else:
        where_clause = hostname_clause + time_clause
      
      metrics = perf_per_node[measurement]
      metric_idx = 0
      metric_idx_last = len(metrics) - 1
      query_str = "select "
      for metric_tuple in metrics:
        metric = metric_tuple[0]
        
        aggregate_idx = 1
        aggregate_idx_last = len(metric_tuple) - 1
        
        # if no aggregates are specified, skip the metric
        if aggregate_idx_last == 0:
          print_info("No aggregation specified for metric", metric)
          continue

        # skip the first element (metric name) of the tuple and iterate over all aggregates
        for aggregate in metric_tuple[1:]:
          # exception for IPC mean, which is handled separately
          if ipc_avail == False and metric == 'ipc':
            if aggregate == 'mean':
              aggregate_idx += 1
              continue
            elif aggregate == 'max': # determine max IPC from min CPI
              query_str += "1/min(cpi) as maxipc"
            else:
              query_str += aggregate + "(" + metric + ") as " + aggregate + metric
          else:
            query_str += aggregate + "(" + metric + ") as " + aggregate + metric
          
          # no comma after last aggregate
          if aggregate_idx < aggregate_idx_last:
            query_str += ","
          
          aggregate_idx += 1

        # no comma after last metric
        if metric_idx < metric_idx_last:
          query_str += ","
          
        metric_idx += 1
        
        # handle non-contiguous data differently "group by time(60s) fill(linear) where cpu=X"
        #if measurement.startswith('likwid'):
          #metric_idx = 0
          #query_str += " from (select "
          #for metric in metrics:
            #query_str += "sum(" + metric + ") as sum_" + metric
            
            ## no comma after last metric
            #if metric_idx < metric_idx_last:
              #query_str += ","
              
            #metric_idx += 1

          #query_str += " from " + measurement + " where " + where_clause + " group by time(60s))"
        #else:
        
      query_str += " from " + measurement + " where " + where_clause
      #print_info(query_str)
      
      ### END: generate select statement
      result = get_results_from_influxdb(query_str)
      if not result:
        continue
  
      # store the requested metric values
      for metric_tuple in metrics:
        metric = metric_tuple[0]
        
        # if no aggregates are specified, skip the metric
        if len(metric_tuple) < 2:
          continue
        
        metric_key = get_metric_key(measurement, metric)
        
        # add the metric key (measurement + metric) to the footprint
        if metric_key not in footprint:
          footprint[metric_key] = {}
        aggregate_dict = footprint[metric_key]

        # skip the first element (metric name) of the tuple iterate over all aggregates
        for aggregate in metric_tuple[1:]:
          try:
            result_value = float(result[aggregate + metric])
          except:
            #print "No value for " + aggregate + metric
            continue
          else:
            if mflops and metric == "flops_any":
              result_value *= 1e6
            
            # value is available            
            if aggregate == 'mean':
              # sum up all averages (divide by node number later)
              if 'mean' in aggregate_dict:
                aggregate_mean = aggregate_dict['mean']
                
                # create sum of averages over all nodes
                aggregate_mean[0] += result_value
                
                # determine the minimum average and the corresponding node
                if aggregate_mean[1] > result_value:
                  aggregate_mean[1] = result_value
                  aggregate_mean[2] = node
                
                # determine the maximum average and the corresponding node
                if aggregate_mean[3] < result_value:
                  aggregate_mean[3] = result_value
                  aggregate_mean[4] = node
              else:
                # initialize with a tuple of (avg,min_avg,node,max_avg,node)
                aggregate_dict['mean'] = [result_value, result_value, node, result_value, node]

            elif aggregate == 'max':
              # check if values is larger
              if 'max' not in aggregate_dict or aggregate_dict['max'][0] < result_value:
                aggregate_dict['max'] = (result_value, node)

            elif aggregate == 'min':
              # check if values is smaller
              if 'min' not in aggregate_dict or aggregate_dict['min'][0] > result_value:
                aggregate_dict['min'] = (result_value, node)
            else:
              print_info("Unknown aggregate: " + aggregate)
              
    # EXTRA HANDLING for IPC max and min mean node
    if ipc_avail == False:
      meanipc = get_mean_ipc_from_cpi(where_clause_cpu)
      if meanipc < 0:
        continue
      
      if 'ipc' not in footprint:
        footprint['ipc'] = {}
      if 'mean' in footprint['ipc']:
        # determine the minimum average and the corresponding node
        if footprint['ipc']['mean'][1] > meanipc:
          footprint['ipc']['mean'][1] = meanipc
          footprint['ipc']['mean'][2] = node
        # determine the maximum average and the corresponding node
        if footprint['ipc']['mean'][3] < meanipc:
          footprint['ipc']['mean'][3] = meanipc
          footprint['ipc']['mean'][4] = node
      else:
        footprint['ipc']['mean'] = [-1, meanipc, node, meanipc, node]
    ### END: EXTRA HANDLING for IPC mean
        
  # here we have the sum of all averages per node (and metric) as well as the min and max average values and the respective nodes
  # change the sum of averages to a real average
  for metric_key in footprint:
    aggregate_dict = footprint[metric_key]
    for aggregate in aggregate_dict:
      if aggregate == 'mean':
        aggregate_dict[aggregate][0] /= len(nodelist)

  return footprint

def get_per_job_maxima(pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause, time_clause, partition):
  footprint = {} #used as call by reference
  
  global perf_max_per_job
  for measurement in perf_max_per_job:
    ### skip nvml for non-gpu partitions:
    if measurement == "nvml" and partition not in partition_gpu_num:
      continue
    
    # set aggregation interval
    if "likwid" in measurement:
      groupby_clause = " group by time(60s)"
    else:
      groupby_clause = " group by time(30s)"

    # set where clause
    if 'socket' in measurement:
      where_clause = socket_hostnames_clause + time_clause + groupby_clause
    elif 'cpu' in measurement:
      where_clause = cpu_hostnames_clause + time_clause + groupby_clause
    else:
      where_clause = pure_hostnames_clause + time_clause + groupby_clause

    query_str = "select "
    metrics = perf_max_per_job[measurement]
    mctr = 1
    mlen = len(metrics)
    for metric in metrics:
      tmp_str = "max(\"sum" + str(metric)+ "\") as max" + str(metric)
      if mctr < mlen:
        query_str += tmp_str + " , "
      else:
        query_str += tmp_str + " "
      mctr += 1
    
    # sub query
    query_str += " from (select "
    mctr = 1
    for metric in metrics:
      tmp_str = "sum(\"" + str(metric) + "\") as sum" + str(metric)
      if mctr < mlen:
        query_str += tmp_str + " , "
      else:
        query_str += tmp_str + " "
      mctr += 1

    query_str += "from " + str(measurement) + " where " + str(where_clause) + ")"
    print_debug(query_str)
  
    result = get_results_from_influxdb(query_str)

    if result and len(result) > 0:
      for metric_idx, metric in enumerate(metrics):
        metric_key = get_metric_key(measurement, metric)
        result_key_max = "max" + metric
        try:
          value = float(result[result_key_max])
        except:
          #footprint[metric_key] = [-1,-1]
          print_info("No per job values for %s" % metric_key)
        else:
          if mflops and metric_key == "flops_any":
            value *= 1e6
              
          #footprint[metric_key] = nat_divide(value, metric_key)
          footprint[metric_key] = value
          #print_debug(metric_key, "Job Max:", value, "(normalized:", footprint[metric_key], ")")

  return footprint

def get_perf_foot(pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause, time_clause, partition):
  footprint = {} #used as call by reference
  
  # iterate over measurements
  for measurement in perf_foot_metrics:
    ### skip nvml for non-gpu partitions:
    if measurement == "nvml" and partition not in partition_gpu_num:
      continue
    
    # determine where clause
    where_clause = ""
    if measurement == 'likwid_socket':
      where_clause += socket_hostnames_clause
    elif "cpu" in measurement:
      where_clause += cpu_hostnames_clause
    else:
      where_clause += pure_hostnames_clause
    where_clause += time_clause
    
    metrics_tuple = perf_foot_metrics[measurement]
    
    query_str = "select "
    metric_idx = 0
    metric_idx_last = len(metrics_tuple) - 1
    
    # iterate over metric+aggregate tuples of a measurement
    for metric_tuple in metrics_tuple:
      metric = metric_tuple[0]
      aggregate = metric_tuple[1]
      
      # EXTRA HANDLING for IPC average as we have stored CPI only
      if ipc_avail == False and metric == 'ipc' and aggregate == 'mean':
        metric_idx += 1
        continue
      else:
        query_str += aggregate + "(" + metric + ") as " + aggregate + metric
      
      if metric_idx < metric_idx_last:
        query_str +=  ","
      metric_idx += 1
      
    query_str += " from " + measurement + " where " + where_clause
    #print query_str
    
    # perform the query
    result = get_results_from_influxdb(query_str)

    if result and len(result) > 0:
      for metric_tuple in metrics_tuple:
        metric = metric_tuple[0]      
        aggregate = metric_tuple[1]
        
        # EXTRA HANDLING for IPC average as we have stored CPI only
        if ipc_avail == False and metric == 'ipc' and aggregate == 'mean':
          continue
        
        metric_id = aggregate+metric
        if metric_id in result and result[metric_id] != None: 
          # special handling for old FLOPS values
          if mflops and metric == "flops_any":
            footprint[(measurement, metric, aggregate)] = float(result[metric_id]) * 1e6
          else:
            footprint[(measurement, metric, aggregate)] = float(result[metric_id])
        else:
          #if (not (partition == "west" and metric == "rapl_power")) or "highiops" in measurement or "scratch2" in measurement:
          #  print "No value for " + aggregate + metric
          continue
        
        #try:
          #footprint[(measurement,metric,aggregate)] = float(result[aggregate+metric])
        #except:
          #if (not (partition == "west" and metric == "rapl_power")) or "highiops" in measurement or "scratch2" in measurement:
            #print "No value for " + aggregate + metric
          #continue
        
    # EXTRA HANDLING for IPC average as we have stored CPI only and for invalid flops
    if measurement == 'likwid_cpu':
      if ipc_avail == False:
        meanipc = get_mean_ipc_from_cpi(where_clause)
        if meanipc > 0:
          footprint[(measurement,'ipc','mean')] = meanipc
      else:
        # if we have an invalid flops mean value, use median or ignore
        if (measurement, 'ipc', 'mean') in footprint:
          value = footprint[(measurement, 'ipc', 'mean')]
          if value > 50:
            # get median
            query_str = "select median(ipc) as medianipc from " + measurement + " where " + where_clause
            result = get_results_from_influxdb(query_str)
            if result and "medianipc" in result:
              value = float(result['medianipc'])
              print_info("Try to use IPC median %f instead of mean %f" % (value, footprint[(measurement, 'ipc', 'mean')]))
          if value > 50:
            footprint.pop((measurement, 'ipc', 'mean'))
            print_info("Remove IPC (%f) from footprint" % (value,))
        
      # if we have an invalid flops mean value, use median or ignore
      if (measurement, 'flops_any', 'mean') in footprint:
        value = footprint[(measurement, 'flops_any', 'mean')]
        ##############
        if mflops:
          value *= 1e6
        ##############  
        if value > float(2**37):
          # get median
          query_str = "select median(flops_any) as medianflops from " + measurement + " where " + where_clause
          result = get_results_from_influxdb(query_str)
          if result and "medianflops" in result:
            value = float(result['medianflops'])
            ##############
            if mflops:
              value *= 1e6
            ##############  
            print_info("Try to use FLOPS median %f instead of mean %f" % (value, footprint[(measurement, 'flops_any', 'mean')]))
        if value > float(2**37):
          footprint.pop((measurement, 'flops_any', 'mean'))
          print_info("Remove FLOPS (%f) from footprint" % (value,))
          
  return footprint
  
def save_footprint(uid, job_runtime, fp_data, mariadb_connection, uids):
  if len(fp_data) == 0:
    return
   
  # insert all values for each footprint table at once -> generate strings per table
  table_fields = {}
  table_values = {}
  for metric_tuple in fp_data:
    # metric_tuple is (measurement, metric, aggregate)

    (table_name, field_name) = get_table_and_field_name(*metric_tuple)
    
    # footprints for file IO are absolute counts
    if table_name == 'footprint_fileio':
      value = str(int(fp_data[metric_tuple]*job_runtime))
    else:
      value = str(fp_data[metric_tuple])
    
    if table_name in table_fields:
      table_fields[table_name] += "," + field_name
    else:
      table_fields[table_name] = field_name
      
    if table_name in table_values:
      table_values[table_name] += "," + value
    else:
      table_values[table_name] = value
      
  try:
    cursor = mariadb_connection.cursor()
  except mariadb.Error as error:
    print_info("Error in get cursor for insert and update: {}".format(error))
    return

  insert_success = 1
  for table_name in table_fields:
    if table_name in table_values:
      sql_cmd = "INSERT INTO " + table_name + " (UID," + table_fields[table_name] + ") VALUES (" + str(uid) + "," + table_values[table_name] + ")"
      #print sql_cmd
      
      try:
        cursor.execute(sql_cmd)
      except mariadb.Error as error:
        # if the footprint is already in table, we can add the footprint=1 to Job_Data table
        if error[0] != 1062: # duplicate entry error
          print_info("Error in execute INSERT: {}".format(error))
          insert_success &= 0

  # store the flag that footprint is available
  if insert_success == 1:
    uids.append(uid)
    #sql_cmd = "UPDATE Job_Data SET FOOTPRINT=1 WHERE UID=" + str(uid)
    ##print sql_cmd
    #try:
      #cursor.execute(sql_cmd)
    #except mariadb.Error as error:
      #print("Error in execute UPDATE: {}".format(error))

  try:
    mariadb_connection.commit()
    cursor.close()
  except mariadb.Error as error:
    print_info("Could not commit job with UID: %d" % (uid,))
    print_info("Error in commit insert or close cursor: {}".format(error))
  
# update the footprint column for successfully and failed footprints
def update_job_data(mariadb_connection, uids_success, uids_failed):
  try:
    cursor = mariadb_connection.cursor()
    
    # we store either successful (1) or failed (-1)
    for value in (1, -1):
      uids = []
      
      # success
      if value == 1:
        uids = uids_success
      elif value == -1:
        uids = uids_failed
      
      if len(uids) == 0:
        #print "No job footprints to update!"
        continue
      elif len(uids) == 1:
        sql_cmd = "UPDATE Job_Data SET FOOTPRINT=" + str(value) + " WHERE UID=" + str(uids[0])
        print_info(sql_cmd)
      else:      
        sql_cmd = "UPDATE Job_Data SET FOOTPRINT=" + str(value) + " WHERE UID IN " + str(tuple(uids))
        print_info("UPDATE Job_Data SET FOOTPRINT=" + str(value) + " WHERE UID IN (" + str(uids[0]) + ", ..., " + str(uids[-1]) + ");", len(uids), "jobs updated")

      cursor.execute(sql_cmd)
      #format_strings = ','.join(['%s'] * len(uids))
      #cursor.execute("UPDATE Job_Data SET FOOTPRINT=1 WHERE UID IN (%s)" % format_strings, tuple(uids))
        
    mariadb_connection.commit()
    cursor.close()
  except mariadb.Error as error:
    print_info("Error in update Job_Data footprint column: {}".format(error))
  
def print_footprint(f, fp_node_data, fp_job_max, print_json):
  #print "Performance footprint (per node) is available"
  #print fp_node_data
  out = []
  
  if f:
    if num_nodes > 1:
      print("%18s" % "Metric", "%9s" % "[unit]:", "%10s" % "Average", "%10s" % "min Avg", "%13s" % "(node)", "%11s" % "max Avg ", "%12s" % "(node)", "%10s" % "max (nat)", "%13s" % "(node)", "%10s" % "max (job)", file=f)
    else:
      print("%18s" % "Metric", "%9s" % "[unit]:", "%10s" % "Average", "%10s" % "max (nat)", "%10s" % "max (job)", file=f)
  
  for metric_key in metric_output_order:
    # skip metrics without values
    if metric_key not in fp_node_data and metric_key not in fp_job_max:
      print_info("skip %s" % metric_key)
      continue
    
    v_mean = -1
    v_minavg = -1
    v_minavg_node = ""
    v_maxavg = -1
    v_maxavg_node = ""
    v_max_native = -1
    v_max_native_node = ''

    if metric_key in fp_node_data:
      values = fp_node_data[metric_key]
      if 'mean' in values:
        v_mean = values["mean"][0]
        if v_mean > 0:
          v_minavg = values["mean"][1]
          v_minavg_node = "(" + values["mean"][2] + ")"
          v_maxavg = values["mean"][3]
          v_maxavg_node = "(" + values["mean"][4] + ")"

      if 'max' in values:
        v_max_native = values['max'][0]
        v_max_native_node = "(" + values['max'][1] + ")"
      
    v_job_max = -1
    if metric_key in fp_job_max:
      v_job_max = float(fp_job_max[metric_key])
      
      
    if v_job_max <= 0 and v_mean <= 0 and v_max_native <= 0:
      continue
    
    ## get metric descriptor, unit and divisor
    if metric_key in metric_desc_tab:
      metric_print_name = metric_desc_tab[metric_key][0]
      metric_unit = metric_desc_tab[metric_key][1]
    else:
      metric_print_name = metric_key
      metric_unit = ''
      
    metric_divide = 1
    if metric_unit.startswith('X'):
      if v_max_native > 0:
        metric_unit, metric_divide = getUnitAndFactor(metric_unit, v_max_native)
      elif v_maxavg > 0:
        metric_unit, metric_divide = getUnitAndFactor(metric_unit, v_maxavg)
      elif v_mean > 0:
        metric_unit, metric_divide = getUnitAndFactor(metric_unit, v_mean)
      elif v_job_max > 0:
        metric_unit, metric_divide = getUnitAndFactor(metric_unit, v_job_max)
      else:
        metric_unit, metric_divide = getUnitAndFactor(metric_unit, 0)
      
    # add square brackets around unit
    if metric_unit != '':
      metric_unit = '[' + metric_unit + ']'
      
    ### change float values to strings
    # no mean values
    if v_mean == -1:
      v_mean = "%10s" % " "
      v_minavg = "%10s" % " "
      v_minavg_node = "%13s" % " "
      v_maxavg = "%10s" % " "
      v_maxavg_node = "%13s" % " "
    else:
      v_mean = "{:10.4f}".format(v_mean/float(metric_divide))
      v_minavg = "{:10.4f}".format(v_minavg/float(metric_divide))
      v_maxavg = "{:10.4f}".format(v_maxavg/float(metric_divide))
      
    # no max native values
    if v_max_native == -1:
      v_max_native = "%10s" % " "
      v_max_native_node = "%13s" % " "
    else:
      v_max_native = "{:10.4f}".format(v_max_native/float(metric_divide))
      
    # no max job values
    if v_job_max == -1:
      v_job_max = "%10s" % " "
    else:
      v_job_max = "{:10.4f}".format(v_job_max/float(metric_divide))
        
    if f:
      if num_nodes > 1:
        ##native average, min average (node), max average (node), native max (node), job max
        print(("%18s %8s:") % (metric_print_name, metric_unit), v_mean, v_minavg + " " + v_minavg_node , v_maxavg + " " + v_maxavg_node, v_max_native + " " + v_max_native_node, v_job_max, file=f)
      else:
        ##native average, native max, job max
        print(("%18s %8s:") % (metric_print_name, metric_unit), v_mean, v_max_native, v_job_max, file=f)
    
    if print_json:
      out.append({ 'METRIC' : metric_print_name, 
                   'UNIT' : metric_unit,
                   'AVG' : v_mean.replace(' ',''),
                   'MIN_AVG' : v_minavg.replace(' ',''),
                   'MIN_AVG_NODE' : v_minavg_node.replace(' ',''),
                   'MAX_AVG' : v_maxavg.replace(' ',''),
                   'MAX_AVG_NODE' : v_maxavg_node.replace(' ',''),
                   'MAX_VALUE' : v_max_native.replace(' ',''),
                   'MAX_VALUE_NODE' : v_max_native_node.replace(' ',''),
                   'MAX_JOB' : v_job_max.replace(' ','') })
  
  if print_json:
    print(json.dumps(out))

  if f:
    print("", file=f)
    print("* FLOPs are normalized to single precision (e.g. 1 DP-FLOP = 2 normalized FLOPs).", file=f)
    print("* max (nat) ... maximum value on a node, socket, CPU core or GPU (depending on the granularity of the metric", file=f)
    print("* max (job) ... maximum total value (over all on a nodes/sockets/CPU cores/GPUs)", file=f)


def main(start, end, job_id, job_start_input, from_uid, footprint_file, store_to_db, overwrite, print_json, debug):
  # set the debugging flag
  if debug:
    global debug_flag
    debug_flag = True
    print_debug("Debugging output enabled.")
    

  # set output file, if not a time range is given
  outfile = None
  f = None
  if start == -1 and end == -1 and not print_json:
    if footprint_file:
      outfile = footprint_file
    else:
      outfile=str(job_id) + "_" + str(job_start_input) + ".footprint"
    
    # open the file for writing
    f = open(outfile,'w')
    print_info("Print to", outfile)
    
  if print_json:
    global debug_file
    debug_file = open(os.devnull, 'w')

  #get job data for footprint
  sql_cmd = "SELECT UID,JID,SUBMIT,START,END,STATUS,NODELIST,NUM_NODES,CPULIST,NUM_CORES,EXCLUSIVE,P_PARTITION,FOOTPRINT FROM Job_Data WHERE (STATUS='completed' OR STATUS='timeout')"

  query_cond = ""
  if start != -1:
    query_cond += " AND START>=" + str(start)
  
  if end != -1:
    query_cond += " AND START<=" + str(end)
    
  sql_cmd_base = sql_cmd + query_cond
  sql_cmd = sql_cmd_base
    
  if from_uid != -1:
    last_uid = from_uid
    query_cond += " AND UID>" + str(last_uid)
  else:
    last_uid = 0
    
  # get count of footprints to generate -> progress
  jobs_to_handle = 0
  if start != -1 or end != -1 or from_uid != -1:
    sql_cmd_count = "SELECT COUNT(*) FROM Job_Data WHERE (STATUS='completed' OR STATUS='timeout')" + query_cond
    print_info(sql_cmd_count)
    try:
      mariadb_connection_select = connect_to_mariadb()
      cursor_select = mariadb_connection_select.cursor()
      cursor_select.execute(sql_cmd_count)
      results = cursor_select.fetchone()
      jobs_to_handle = int(results[0])
      cursor_select.close()
    except mariadb.Error as error:
      print_info("Error in fetchone: {}".format(error))
      
    print_info("Generate footprints for %d jobs" % (jobs_to_handle,))
    
  chunk_size = 10000
  if job_id != -1 and job_start_input != -1:
    sql_cmd += " AND JID=" + str(job_id) + " AND START=" + str(job_start_input) + " limit 1"
  else:
    sql_cmd = sql_cmd_base + " limit " + str(chunk_size)

  print_info(sql_cmd)

  uids_success = [] # store jobs with successfully generated footprints
  uids_failed = []  # store jobs where footprint could not be generated
  num_jobs_handled = 0
  rowsAvailable = 1
  while rowsAvailable > 0:
    if last_uid > 0:
      sql_cmd = sql_cmd_base + " AND UID>" + str(last_uid) + " limit " + str(chunk_size)
      print_info(sql_cmd)
      if jobs_to_handle > 0:
        print_info("%d/%d jobs handled (%3.2f %%)" % (num_jobs_handled, jobs_to_handle, float(num_jobs_handled)/float(jobs_to_handle)*100.0))
    try:
      mariadb_connection_select = connect_to_mariadb()
      cursor_select = mariadb_connection_select.cursor()
      cursor_select.execute(sql_cmd)
      results = cursor_select.fetchall()
      cursor_select.close()
    except mariadb.Error as error:
      print_info("Error in fetchall: {}".format(error))
      print_info("Number of jobs handled %d" % (num_jobs_handled,))
      break
    
    rowsAvailable = len(results)
    if rowsAvailable < chunk_size:
      rowsAvailable = 0;
    
    for job_data in results:
      job_uid = job_data[0]
      last_uid = job_uid
      job_id = job_data[1]
      job_submit = job_data[2]
      if job_submit:
        job_submit = int(job_submit)
      job_start = job_data[3]
      job_end = job_data[4]
      job_status = job_data[5]
      nodes_compact_str = job_data[6]
      global num_nodes
      num_nodes = job_data[7]
      cpulist = job_data[8]
      global num_cores
      num_cores = job_data[9]
      exclusive = job_data[10]
      partition = job_data[11]
      has_footprint = job_data[12]
      
      # use or open an existing InfluxDB connection
      setInfluxConnection(job_start)
      
      num_jobs_handled += 1
      
      idline = "UID: " + str(job_uid) + ", JID: " + str(job_id) + ", start: " + str(job_start) + ", " + str(partition) + ", " +  nodes_compact_str
      if exclusive == 0:
        idline += ", " + cpulist
        
      # if footprint has been generated (or tried to generate)
      if has_footprint is not None:
        # footprint has been generated
        if int(has_footprint) == 1:
          idline += " footprint already stored in DB"
        elif int(has_footprint) == -1:
          idline += " failed to created footprint, previously"
        
      #print idline
      
      ### This is specific for TUD/ZIH, as we changed CPI to IPC
      ### and MFLOPS to FLOPS at some point in time
      global ipc_avail
      if job_start > 1560769200:
        ipc_avail = True
      else:
        ipc_avail = False
        
      global mflops
      if job_start < 1552654800:
        mflops = True
      else:
        mflops = False
      
      #skip if job is shared and has no cpu list
      if exclusive == 0 and cpulist in 'n/a':
        print(debug_file, "Non-exclusive job without CPU list!")
        continue
      
      if outfile:
        print_info("Store footprint to file:", outfile)
        #print >> f, ""
        print("--- Job Metadata ---", file=f)
        #print >> f, "UID:", job_uid
        print("JID:", job_id, file=f)
        if job_submit > 0:
          print("SUBMIT:", datetime.fromtimestamp(job_start).strftime('%d %b %Y %H:%M:%S'), "(" + str(job_submit) + ")", file=f)
        print("START:", datetime.fromtimestamp(job_start).strftime('%d %b %Y %H:%M:%S'), "(" + str(job_start) + ")", file=f)
        print("END  :", datetime.fromtimestamp(job_end).strftime('%d %b %Y %H:%M:%S'), "(" + str(job_end) + ")", file=f)
        print("DURATION:", job_end-job_start, "seconds", file=f)
        print("STATUS:", job_status, file=f)
        print("PARTITION:", partition, file=f)
        print("NODELIST:", nodes_compact_str, file=f)
        print("NUM_NODES:", num_nodes, file=f)
        print("EXCLUSIVE:", exclusive, file=f)
        if exclusive == 0:
          print("CPULIST:", cpulist, file=f)
        print("NUM_CORES:", num_cores, file=f)
        
      nodelist = hostlist.expand_hostlist(nodes_compact_str)
      if len(nodelist) != num_nodes:
        print_info("Reported number of nodes (%d) != number of entries in node list (%d)" % (num_nodes, len(nodelist)))
      
      if exclusive == 0:
        cpulist_per_node_dict = convert_cpulist_to_cpulistdict(cpulist)
        if len(cpulist_per_node_dict) != num_nodes:
          print_info("Number of nodes (%d) != number of entries in CPU list per node dictionary (%d)" % (num_nodes, len(cpulist_per_node_dict)))
      else:
        cpulist_per_node_dict = {}

      # set time clause for queries
      time_clause = " and time >= " + str(job_start) + "s and time <= " + str(job_end) + "s"
      
      # get hostname and cpu clauses for queries
      hostname_clause_tuple = get_hostnames_clauses(nodelist, cpulist_per_node_dict, partition, exclusive)
      if hostname_clause_tuple:
        (pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause) = hostname_clause_tuple
      else:
        print_info("Could not generate host name clauses", (nodelist, cpulist_per_node_dict, partition, exclusive))
        continue

      # if an output file with extended footprint or a JSON dump is requested
      if outfile or print_json:
        # get footprint maximum values
        fp_job_max = get_per_job_maxima(pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause, time_clause, partition)

        #if fp_job_max:
        #  print "Performance footprint (per job maxima) is available"
        #  print fp_job_max
            
        #if num_nodes > 1:
        fp_node_data = get_per_node_footprint(nodelist, cpulist_per_node_dict, exclusive, partition, time_clause)
        
        # EXTRA HANDLING for global IPC mean    
        #overwrite overall IPC mean value
        
        if ipc_avail == False and 'ipc' in fp_node_data and 'mean' in fp_node_data['ipc']:
          meanipc = get_mean_ipc_from_cpi(cpu_hostnames_clause + time_clause)
          if meanipc >= 0:
            fp_node_data['ipc']['mean'][0] = meanipc
      
        ## if per node data is available
        if fp_node_data or fp_job_max:
          print_footprint(f, fp_node_data, fp_job_max, print_json)
          
        # debugging only
        #perf_foot = get_perf_foot(pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause, time_clause, partition)
        #print perf_foot
          
      else:
        #check if footprint already exists or if it previously could not be created
        if has_footprint is None or int(has_footprint) == 0 or overwrite:
          ### get the performance footprint base metrics
          perf_foot = get_perf_foot(pure_hostnames_clause, socket_hostnames_clause, cpu_hostnames_clause, time_clause, partition)
          
          # if performance footprint is available
          if perf_foot and len(perf_foot) > 0:
            #print "Performance footprint (with base metrics) is available"
            #print perf_foot
            
            if store_to_db:
              #save_footprint(job_uid, job_end-job_start, perf_foot, mariadb_connection_update, uids_success)
              save_footprint(job_uid, job_end-job_start, perf_foot, mariadb_connection_select, uids_success)
              
          else:
            # could not create footprint for job with UID uid
            uids_failed.append(job_uid)
        
      # update Job_Data table every 100 successful footprints
      if len(uids_success) > 99 or len(uids_failed) > 99:
        # update the footprint column for remaining uids/jobs
        update_job_data(mariadb_connection_select, uids_success, uids_failed)
        uids_success = []
        uids_failed = []
              
    # update the footprint column for remaining uids/jobs
    update_job_data(mariadb_connection_select, uids_success, uids_failed)
    uids_success = []
    uids_failed = []
    
    # close connection
    try:
      mariadb_connection_select.close()
    except mariadb.Error as error:
      print_info("Error in MariaDB connection close: {}".format(error))
    
  # update remaining stuff
  try:
    mariadb_connection_select = connect_to_mariadb()
  except mariadb.Error as error:
    print_info("Error in open MariaDB connection for remaining update: {}".format(error))
    
  # update footprint column for finished footprints, but an error occurred
  update_job_data(mariadb_connection_select, uids_success, uids_failed)
  
  try:
    mariadb_connection_select.close()
  except mariadb.Error as error:
    print_info("Error in closing MariaDB connection for remaining updates : {}".format(error))

  # close output file
  if outfile:
    f.close()
  else:
    print_info("Number of jobs handled %d (last UID: %d)" % (num_jobs_handled, last_uid))


def parse_args():
  parser = argparse.ArgumentParser()
  parser.add_argument('--start', type=int, required=False, default=-1)
  parser.add_argument('--end', type=int, required=False, default=-1)
  parser.add_argument('--job_id', type=int, required=False, default=-1)
  parser.add_argument('--job_start', type=int, required=False, default=-1)
  parser.add_argument('--from_uid', type=int, required=False, default=-1)
  parser.add_argument('--footprint_file', type=str, required=False)
  parser.add_argument('--store_to_db', action="store_true", default=False, help='store footprints into database')
  parser.add_argument('--overwrite', action="store_true", default=False, help='overwrite available footprints')
  parser.add_argument('--print_json', action="store_true", default=False, help='print a json dump of the footprints')
  parser.add_argument('--debug', action="store_true", default=False, help='print debugging output')
  return parser.parse_args()


if __name__ == '__main__':
  args = parse_args()
  main(start=args.start,
       end=args.end,
       job_id=args.job_id,
       job_start_input=args.job_start,
       from_uid=args.from_uid,
       footprint_file=args.footprint_file,
       store_to_db=args.store_to_db,
       overwrite=args.overwrite,
       print_json=args.print_json,
       debug=args.debug)