This file is indexed.

/usr/share/perl5/OAR/IO.pm is in liboar-perl 2.5.7-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
# This is the iolib, which manages the layer between the modules and the
# database. This is the only base-dependent layer.
# When adding a new function, the following comments are required before the code of the function:
# - the name of the function
# - a short description of the function
# - the list of the parameters it expect
# - the list of the return values
# - the list of the side effects

# $Id$
package OAR::IO;
require Exporter;

use DBI;
use OAR::Conf qw(init_conf get_conf is_conf reset_conf);
use Data::Dumper;
use Time::Local;
use OAR::Modules::Judas qw(oar_debug oar_warn oar_error send_log_by_email set_current_log_category);
use strict;
use Fcntl;
use OAR::Schedulers::ResourceTree;
use OAR::Tools;
use POSIX qw(strftime);

# suitable Data::Dumper configuration for serialization
$Data::Dumper::Purity = 1;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 0;
$Data::Dumper::Deepcopy = 1;

# PROTOTYPES

# CONNECTION
sub connect();
sub connect_ro();
sub disconnect($);

# JOBS MANAGEMENT
sub get_job_challenge($$);
sub get_jobs_in_state($$);
sub get_jobs_in_state_for_user($$$);
sub is_job_desktop_computing($$);
sub get_job_current_hostnames($$);
sub get_job_current_resources($$$);
sub get_job_host_log($$);
sub get_job_resources($$);
sub get_job_resources_properties($$);
sub get_to_kill_jobs($);
sub is_tokill_job($$);
sub get_timered_job($);
sub get_to_exterminate_jobs($);
sub get_frag_date($$);
sub set_running_date($$);
sub set_running_date_arbitrary($$$);
sub set_assigned_moldable_job($$$);
sub set_finish_date($$);
sub get_possible_wanted_resources($$$$$$$);
sub add_micheline_job($$$$$$$$$$$$$$$$$$$$$$$$$$$$$);
sub get_job($$);
sub get_job_state($$);
sub get_current_moldable_job($$);
sub set_job_state($$$);
sub set_job_resa_state($$$);
sub set_job_message($$$);
sub frag_job($$);
sub ask_checkpoint_job($$);
sub ask_signal_job($$$);
sub hold_job($$$);
sub resume_job($$);
sub job_fragged($$);
sub job_arm_leon_timer($$);
sub job_refrag($$);
sub job_leon_exterminate($$);
sub get_waiting_reservation_jobs($);
sub get_waiting_reservation_jobs_specific_queue($$);
sub get_waiting_toSchedule_reservation_jobs_specific_queue($$);
sub parse_jobs_from_range($);
sub get_jobs_past_and_current_from_range($$$);
sub get_jobs_future_from_range($$$);
sub get_jobs_for_user_query;
sub count_jobs_for_user_query;
sub get_desktop_computing_host_jobs($$);
sub get_stagein_id($$);
sub set_stagein($$$$$$);
sub get_job_stagein($$);
sub is_stagein_deprecated($$$);
sub del_stagein($$);
sub get_jobs_to_schedule($$$);
sub get_job_types_hash($$);
sub set_moldable_job_max_time($$$);
sub is_timesharing_for_2_jobs($$$);

#ARRAY JOBS MANAGEMENT
sub get_jobs_in_array($$);
sub get_job_array_id($$);
sub get_array_subjobs($$);
sub get_array_job_ids($$);


# PROCESSJOBS MANAGEMENT (Resource assignment to jobs)
sub get_resource_job($$);
sub get_resources_jobs($);
sub get_resource_job_to_frag($$);
sub get_node_job($$);
sub get_node_job_to_frag($$);
sub get_resources_in_state($$);
sub add_resource_job_pair($$$);
sub add_resource_job_pairs($$$);
sub add_resource_job_pairs_from_file($$$);

# RESOURCES MANAGEMENT
sub add_resource($$$);
sub list_nodes($);
sub list_resources($);
sub count_all_resources($);
sub get_requested_resources($$$);
sub get_resource_info($$);
sub get_resource_next_value_for_property($$);
sub is_node_exists($$);
sub get_resources_on_node($$);
sub set_node_state($$$$);
sub update_resource_nextFinaudDecision($$$);
sub get_resources_change_state($);
sub set_resource_nextState($$$);
sub set_node_nextState($$$);
sub set_node_expiryDate($$$);
sub set_resources_property($$$$);
sub get_resources_absent_suspected_dead_from_range($$$);
sub get_expired_resources($);
sub is_node_desktop_computing($$);
sub get_resources_data_structure_current_job($$);
sub get_hosts_state($);
sub get_alive_nodes_with_jobs($);
sub get_resources_by_property($$);

# QUEUES MANAGEMENT
sub get_active_queues($);
sub get_all_queue_informations($);

# GANTT MANAGEMENT
sub get_gantt_scheduled_jobs($);
sub get_gantt_visu_scheduled_jobs($);
sub add_gantt_scheduled_jobs($$$$);
sub gantt_flush_tables($$$);
sub set_gantt_date($$);
sub get_gantt_date($);
sub get_gantt_visu_date($);
sub get_gantt_jobs_to_launch($$);
sub get_gantt_resources_for_jobs_to_launch($$);
sub get_gantt_resources_for_job($$);
sub set_gantt_job_startTime($$$);
sub update_gantt_visualization($);
sub get_gantt_visu_scheduled_job_resources($$);

# ADMISSION RULES MANAGEMENT
sub add_admission_rule($$$$);
sub list_admission_rules($$);
sub get_admission_rule($$);
sub get_requested_admission_rules($$$);
sub count_all_admission_rules($);
sub delete_admission_rule($$);
sub update_admission_rule($$$$$);

# TIME CONVERSION
sub ymdhms_to_sql($$$$$$);
sub sql_to_ymdhms($);
sub ymdhms_to_local($$$$$$);
sub local_to_ymdhms($);
sub sql_to_local($);
sub local_to_sql($);
sub sql_to_hms($);
sub hms_to_duration($$$);
sub hms_to_sql($$$);
sub duration_to_hms($);
sub duration_to_sql($);
sub sql_to_duration($);
sub get_date($);

#EVENTS LOG MANAGEMENT
sub add_new_event($$$$);
sub add_new_event_with_host($$$$$);
sub check_event($$$);
sub get_to_check_events($);
sub get_hostname_event($$);
sub get_job_events($$);
sub get_events_for_hostname($$$);
sub get_last_event_from_type($$);

# ACCOUNTING
sub check_accounting_update($$);
sub update_accounting($$$$$$$$$$);
sub get_accounting_summary($$$$$);
sub get_accounting_summary_byproject($$$$$$);
sub get_last_project_karma($$$$);

# LOCK FUNCTIONS:
sub get_lock($$$);
sub release_lock($$);

# SQL HELPER FUNCTIONS
sub sql_count($$);
sub sql_select($$$$);
sub inserts_from_file($$$);

# END OF PROTOTYPES

my $Remote_host;
my $Remote_port;

my %State_to_num = (
    "Alive" => 1,
    "Absent" => 2,
    "Suspected" => 3,
    "Dead" => 4
);

# Log category
# set_current_log_category('main');

my $Db_type = "mysql";

sub get_database_type(){
    return($Db_type);
}

# Duration to add to all jobs when matching the available_upto resource property field
my $Cm_security_duration = 600;

# When the walltime of a job is not defined
my $Default_job_walltime = 3600;

# CONNECTION


my $Max_db_connection_timeout = 30;
my $Timeout_db_connection = 2;

# connect_db
# Connects to database and returns the base identifier
# return value : base
sub connect_db($$$$$$) {
    my $host = shift;
    my $dbport = shift;
    my $name = shift;
    my $user = shift;
    my $pwd = shift;
    my $debug_level = shift;
    my $dbd_opts = ""; 
    
    if($host=~m/;/){
    	my $oldHost = $host;
			$host=~s/;.*//;
			oar_error("[IOlib] Error reading $oldHost attribute from OAR configuration file, using $host instead.\n");
		}
		if($dbport=~m/;/){
			my $oldDbport = $dbport;
			$dbport=~s/;.*//;
			oar_error("[IOlib] Error reading $oldDbport attribute from OAR configuration file, using $dbport instead.\n");
		}
		if($name=~m/;/){
			my $oldname = $name;
			$name=~s/;.*//;
			oar_error("[IOlib] Error reading $oldname attribute from OAR configuration file, using $name instead.\n");
		}
		if($user=~m/;/){
			my $olduser = $user;
			$user=~s/;.*//;
			oar_error("[IOlib] Error reading $olduser attribute from OAR configuration file, using $user instead.\n");
		}

    my $printerror = 0;
    if (defined($debug_level) and ($debug_level >= 3)){
        $printerror = 1;
    }

    my $type;
    if ($Db_type eq "Pg" || $Db_type eq "psql"){
        $type = "Pg";
    }elsif ($Db_type eq "mysql"){
        $type = "mysql";
        $dbd_opts = ";mysql_local_infile=1"; #Mysql option to allow LOAD LOCAL INFILE
    }else{
        oar_error("[IOlib] Cannot recognize DB_TYPE tag \"$Db_type\". So we are using \"mysql\" type.\n");
        $type = "mysql";
        $Db_type = "mysql";
        $dbd_opts = ";mysql_local_infile=1"; #Mysql option to allow LOAD LOCAL INFILE
    }
		my $connection_string;
    if($dbport eq "" || !($dbport>1 && $dbport<65535)){
    	$connection_string = "DBI:$type:database=$name;host=$host".$dbd_opts;
    }
    else{
    	$connection_string = "DBI:$type:database=$name;host=$host;port=$dbport";
    }
    my $dbh = DBI->connect($connection_string, $user, $pwd, {'InactiveDestroy' => 1, 'PrintError' => $printerror});
    
    if (!defined($dbh)){
        oar_error("[IOlib] Cannot connect to database (type=$Db_type, host=$host, user=$user, database=$name) : $DBI::errstr\n");
    }
    return($dbh);
}

# timeout_db
# Check the provided db handler and wait for an incremented time if not ok
sub timeout_db($$) {
  my $dbh = shift;
  my $Max_db_connection_timeout = shift;
  if (!defined($dbh)) {
        oar_warn("[IOlib] I will retry to connect to the database in $Timeout_db_connection s\n");
        send_log_by_email("OAR database connection failed","[IOlib] I will retry to connect to the database in $Timeout_db_connection s\n");
        my $sleep_time = 0;
        while ($sleep_time <= 1){
            $sleep_time = sleep($Timeout_db_connection);
        }
        if ($Timeout_db_connection < $Max_db_connection_timeout){
            $Timeout_db_connection += 2;
        }
    }
} 

# connect
# Connects to database and returns the base identifier
# parameters : /
# return value : base
# side effects : opens a connection to the base specified in ConfLib
sub connect() {
    # Connect to the database.
    my $dbh = undef;
    while (!defined($dbh)){
        $dbh = connect_one();
        my $max_timeout = get_conf("MAX_DB_CONNECTION_TIMEOUT");
        $max_timeout = $Max_db_connection_timeout unless defined($max_timeout);
        timeout_db($dbh,$max_timeout);
    }
    return($dbh);
}

# connect_one
# Connects to database and returns the base identifier. No loop for retry.
# parameters : /
# return value : base
# side effects : opens a connection to the base specified in ConfLib
sub connect_one() {
    # Connect to the database.
    my $dbh = undef;
    reset_conf();
    init_conf($ENV{OARCONFFILE});

    my $host = get_conf("DB_HOSTNAME");
    my $dbport = get_conf("DB_PORT");
    if (not defined($dbport)) {
        $dbport = "";
    }
    my $name = get_conf("DB_BASE_NAME");
    my $user = get_conf("DB_BASE_LOGIN");
    my $pwd = get_conf("DB_BASE_PASSWD");
    $Db_type = get_conf("DB_TYPE");
    
    my $log_level = get_conf("LOG_LEVEL");

    $Remote_host = get_conf("SERVER_HOSTNAME");
    $Remote_port = get_conf("SERVER_PORT");

    return connect_db($host,$dbport,$name,$user,$pwd,$log_level);
}

# connect_ro
# Connects to database and returns the base identifier
# parameters : /
# return value : base
# side effects : opens a connection to the base specified in ConfLib
sub connect_ro() {
    # Connect to the database.
    my $dbh = undef;
    while (!defined($dbh)){
        $dbh = connect_ro_one();
        my $max_timeout = get_conf("MAX_DB_CONNECTION_TIMEOUT");
        $max_timeout = $Max_db_connection_timeout unless defined($max_timeout);
        timeout_db($dbh,$max_timeout);
    }
    return($dbh);
}

# connect_ro_one
# Connects to database and returns the base identifier. No loop for retry.
# parameters : /
# return value : base
# side effects : opens a connection to the base specified in ConfLib
sub connect_ro_one() {
  connect_ro_one_log(undef);
}
sub connect_ro_one_log($) {
    my $log=shift;
    # Connect to the database.
    reset_conf();
    init_conf($ENV{OARCONFFILE});

    my $host = get_conf("DB_HOSTNAME");
    my $dbport = get_conf("DB_PORT");
    if (not defined($dbport)) {
        $dbport = "";
    }
    my $name = get_conf("DB_BASE_NAME");
    my $user = get_conf("DB_BASE_LOGIN_RO");
    $user = get_conf("DB_BASE_LOGIN") if (!defined($user));
    my $pwd = get_conf("DB_BASE_PASSWD_RO");
    $pwd = get_conf("DB_BASE_PASSWD") if (!defined($pwd));
    $Db_type = get_conf("DB_TYPE");
    
    my $log_level;
    if (defined($log)) { $log_level = 3; }
    else { $log_level = get_conf("LOG_LEVEL"); }
    
    $Remote_host = get_conf("SERVER_HOSTNAME");
    $Remote_port = get_conf("SERVER_PORT");

    return connect_db($host,$dbport,$name,$user,$pwd,$log_level);
}

# disconnect
# Disconnect from database
# parameters : base
# return value : /
# side effects : closes a previously opened connection to the specified base
sub disconnect($) {
    my $dbh = shift;

    # Disconnect from the database.
    $dbh->disconnect();
}


sub get_last_insert_id($$){
    my $dbh = shift;
    my $seq = shift;
    
    my $id;
    my $sth;
    if ($Db_type eq "Pg"){
        $sth = $dbh->prepare("SELECT CURRVAL('$seq')");
        $sth->execute();
        my $ref = $sth->fetchrow_hashref();
        my @tmp_array = values(%$ref);
        $id = $tmp_array[0];
        $sth->finish();
    }else{
        $sth = $dbh->prepare("SELECT LAST_INSERT_ID()");
        $sth->execute();
        my $ref = $sth->fetchrow_hashref();
        my @tmp_array = values(%$ref);
        $id = $tmp_array[0];
        $sth->finish();
    }

    return($id);
}


# JOBS MANAGEMENT

# Get the cpuset name for the given job
# args : database ref, job id
sub get_job_cpuset_name($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT job_user
                                FROM jobs
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    my @res = $sth->fetchrow_array();
    my $cpuset = $res[0]."_".$job_id;
    return($cpuset);
}


# get_job_challenge
# gets the challenge string of a OAR Job
# parameters : base, jobid
# return value : challenge
# side effects : /
sub get_job_challenge($$){
    my $dbh = shift;
    my $job_id = shift;
    
    my $sth = $dbh->prepare("SELECT challenge,ssh_private_key,ssh_public_key
                             FROM challenges
                             WHERE
                                job_id = $job_id
                            ");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return($ref->{challenge},$ref->{ssh_private_key},$ref->{ssh_public_key});
}

# get_count_same_ssh_keys_current_jobs
# return the number of current jobs with the same ssh keys
sub get_count_same_ssh_keys_current_jobs($$$$){
    my $dbh = shift;
    my $user = shift;
    my $ssh_private_key = shift;
    my $ssh_public_key = shift;

    $ssh_private_key = $dbh->quote($ssh_private_key);
    $ssh_public_key = $dbh->quote($ssh_public_key);
    my $sth = $dbh->prepare("   SELECT COUNT(challenges.job_id)
                                FROM challenges, jobs
                                WHERE
                                    jobs.state IN (\'Waiting\',\'Hold\',\'toLaunch\',\'toError\',\'toAckReservation\',\'Launching\',\'Running\',\'Suspended\',\'Resuming\') AND
                                    challenges.job_id = jobs.job_id AND
                                    challenges.ssh_private_key = $ssh_private_key AND
                                    challenges.ssh_public_key = $ssh_public_key AND
                                    jobs.job_user != '$user' AND
                                    challenges.ssh_private_key != \'\'
                            ");
    $sth->execute();
    my @ref = $sth->fetchrow_array();
    $sth->finish();
    return($ref[0]);
}

# get_jobs_in_state
# returns the jobs in the specified state
# parameters : base, job state
# return value : flatened list of hashref jobs
# side effects : /
sub get_jobs_in_state($$) {
    my $dbh = shift;
    my $state = $dbh->quote(shift);

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    state = $state
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(@res);
}

# get_jobs_in_multiple_states
# returns the jobs in the specified states
# parameters : base, job state list
# return value : flatened list of hashref jobs
# side effects : /
sub get_jobs_in_multiple_states($$) {
    my $dbh = shift;
    my $states = shift;

    my $state_str;
    foreach my $s (@{$states}){
        $state_str .= $dbh->quote($s);
        $state_str .= ",";
    }
    chop($state_str);

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    state IN (".$state_str.")
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(@res);
}

# get_jobs_in_state_for_user
# returns the jobs in the specified state for the optionaly specified user
# parameters : base, job state, user
# return value : flatened list of hashref jobs
# side effects : /
sub get_jobs_in_state_for_user($$$) {
    my $dbh = shift;
    my $state = $dbh->quote(shift);
    my $user = shift;
    my $user_query = "";

    if (defined $user and "$user" ne "" ) {
      $user_query="AND job_user =" . $dbh->quote($user);
    }

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    state = $state $user_query
                                ORDER BY job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(@res);
}

# get_jobs_in_states_for_user
# returns the jobs in the specified states for the optionaly specified user
# parameters : base, job states, user
# return value : flatened list of hashref jobs
# side effects : /
sub get_jobs_in_states_for_user($$$) {
    my $dbh = shift;
    my $states = shift;
    my $user = shift;

    my $user_query="";
    if (defined $user and "$user" ne "" ) {
      $user_query="AND job_user =" . $dbh->quote($user);
    }

    my $instates;
    foreach my $s (@{$states}){
        $instates .= $dbh->quote($s);
        $instates .= ',';
    }
    chop($instates);

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    state IN (".$instates.")
                                    $user_query
                                ORDER BY job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(\@res);
}

# get_jobs_with_given_properties
# returns the jobs with specified properties
# parameters : base, where SQL constraints
# return value : flatened list of hashref jobs
# side effects : /
sub get_jobs_with_given_properties($$) {
    my $dbh = shift;
    my $where = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    $where
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(@res);
}


# is_job_desktop_computing
# return true if the job will run on desktop_computing nodes
# parameters: base, jobid
# return value: boolean
# side effects: /
sub is_job_desktop_computing($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT COUNT(desktop_computing)
                                FROM assigned_resources, resources, jobs
                                WHERE
                                    jobs.job_id = $job_id AND
                                    assigned_resources.moldable_job_id = jobs.assigned_moldable_job AND
                                    assigned_resources.resource_id = resources.resource_id AND
                                    resources.desktop_computing = \'YES\'
                            ");
    $sth->execute();
    my ($count) = $sth->fetchrow_array();
    return($count > 0);
}

# is_timesharing_for_2_jobs
# return true if both jobs are timesharing compatible
# parameters: base, jobid1, jobid2
# return value: boolean
# side effects: /
sub is_timesharing_for_2_jobs($$$){
    my $dbh = shift;
    my $job_id1 = shift;
    my $job_id2 = shift;

    # this request returns exactly 1 row if and only if both jobs are timesharing compatible
    my $sth = $dbh->prepare("SELECT 1
                             FROM jobs j, job_types t
                             WHERE
                               j.job_id IN ($job_id1, $job_id2) AND
                               j.job_id = t.job_id AND
                               t.type like 'timesharing=%'
                             GROUP BY
                               t.type
                             HAVING
                               COUNT(j.job_id) = 2 AND (
                                 ( t.type = 'timesharing=user,name' AND
                                   COUNT(DISTINCT j.job_user) = 1 AND
                                   COUNT(DISTINCT j.job_name) = 1 ) OR
                                 ( t.type = 'timesharing=user,*' AND
                                   COUNT(DISTINCT j.job_user) = 1 ) OR
                                 ( t.type = 'timesharing=*,name' AND
                                   COUNT(DISTINCT j.job_user) = 1 ) OR
                                 t.type = 'timesharing=*,*' )
                            ");
    my $res = $sth->execute();
    # $res == 1 if the request produced a row, 0E0 otherwise.
    $sth->finish();
    return($res == 1);
}

# get_job_current_hostnames
# returns the list of hosts associated to the job passed in parameter
# parameters : base, jobid
# return value : list of distinct hostnames
# side effects : /
sub get_job_current_hostnames($$) {
    my $dbh = shift;
    my $job_id= shift;

    my $sth = $dbh->prepare("SELECT resources.network_address as hostname
                             FROM assigned_resources, resources, moldable_job_descriptions
                             WHERE 
                                assigned_resources.assigned_resource_index = \'CURRENT\'
                                AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                AND assigned_resources.resource_id = resources.resource_id
                                AND moldable_job_descriptions.moldable_id = assigned_resources.moldable_job_id
                                AND moldable_job_descriptions.moldable_job_id = $job_id
                                AND resources.network_address != \'\'
                                AND resources.type = \'default\'
                             GROUP BY resources.network_address
                             ORDER BY resources.network_address ASC");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{hostname});
    }
    return @res;
}


# get_job_current_resources
# returns the list of resources associated to the job passed in parameter
# parameters : base, moldable_id
# side effects : /
sub get_job_current_resources($$$) {
    my $dbh = shift;
    my $moldable_id= shift;
    my $not_type_list = shift;

    my $tmp_str;
    if (!defined($not_type_list)){
        $tmp_str = "FROM assigned_resources
                    WHERE 
                        assigned_resources.assigned_resource_index = \'CURRENT\' AND
                        assigned_resources.moldable_job_id = $moldable_id";
    }else{
        my $type_str;
        foreach my $t (@{$not_type_list}){
            $type_str .= $dbh->quote($t);
            $type_str .= ',';
        }
        chop($type_str);
        $tmp_str = "FROM assigned_resources,resources
                    WHERE 
                        assigned_resources.assigned_resource_index = \'CURRENT\' AND
                        assigned_resources.moldable_job_id = $moldable_id AND
                        resources.resource_id = assigned_resources.resource_id AND
                        resources.type NOT IN (".$type_str.")";
    }
    my $sth = $dbh->prepare("SELECT assigned_resources.resource_id as resource
                                $tmp_str
                             ORDER BY assigned_resources.resource_id ASC");
    $sth->execute();
    my @res = ();
    my $vec = '';
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{resource});
        vec($vec, $ref->{resource}, 1) = 1;
    }
    return($vec, @res);
}


# get_job_resources
# returns the list of resources associated to the job passed in parameter
# parameters : base, moldable_id
# return value : list of resources
# side effects : /
sub get_job_resources($$) {
    my $dbh = shift;
    my $moldable_id= shift;

    my $sth = $dbh->prepare("SELECT resource_id as resource
                             FROM assigned_resources
                             WHERE 
                                moldable_job_id = $moldable_id
                             ORDER BY resource_id ASC");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{resource});
    }
    return @res;
}


# get_job_network_address
# returns the list of network_address associated to the job passed in parameter
# parameters : base, moldable_id
# return value : list of resources
# side effects : /
sub get_job_network_address($$) {
    my $dbh = shift;
    my $moldable_id= shift;

    my $sth = $dbh->prepare("SELECT DISTINCT(resources.network_address) as hostname
                             FROM assigned_resources, resources
                             WHERE 
                                assigned_resources.moldable_job_id = $moldable_id AND
                                resources.resource_id = assigned_resources.resource_id AND
                                resources.type = \'default\'
                             ORDER BY resources.network_address ASC");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{hostname});
    }
    return(@res);
}

# get_job_resource_properties
# returns the list of resources properties associated to the job passed in
# parameter
# parameters : base, jobid
# return value : list of hashs of each resource properties
# side effects : /
sub get_job_resources_properties($$) {
    my $dbh = shift;
    my $job_id= shift;

    my $sth = $dbh->prepare("SELECT resources.*
                             FROM resources, assigned_resources, jobs
                             WHERE 
                                jobs.job_id = $job_id AND
                                jobs.assigned_moldable_job = assigned_resources.moldable_job_id AND
                                assigned_resources.resource_id = resources.resource_id
                             ORDER BY resource_id ASC");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return @res;
}

# get_job_host_log
# returns the list of hosts associated to the moldable job passed in parameter
# parameters : base, moldable_id
# return value : list of distinct hostnames
# side effects : /
sub get_job_host_log($$) {
    my $dbh = shift;
    my $moldable_id = shift;
    
    my $sth = $dbh->prepare("   SELECT DISTINCT(resources.network_address)
                                FROM assigned_resources, resources
                                WHERE
                                    assigned_resources.moldable_job_id = $moldable_id AND
                                    resources.resource_id = assigned_resources.resource_id AND
                                    resources.network_address != \'\' AND
                                    resources.type = \'default\'
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{network_address});
    }
    return @res;
}


# is_tokill_job
# returns true if the job has its frag state to LEON
# parameters : base, jobid
# return value : boolean
# side effects : /
sub is_tokill_job($$) {
    my $dbh = shift;
    my $job_id = shift;
    my $sth = $dbh->prepare("   SELECT frag_id_job
                                FROM frag_jobs
                                WHERE
                                    frag_state = \'LEON\'
                                    AND frag_id_job = $job_id");
    $sth->execute();
    my @res = $sth->fetchrow_array();
    $sth->finish();
    return ($#res >= 0)
}

# get_to_kill_jobs
# returns the list of jobs that have their frag state to LEON
# parameters : base
# return value : list of jobid
# side effects : /
sub get_to_kill_jobs($) {
    my $dbh = shift;
    my $sth = $dbh->prepare("SELECT jobs.*
                             FROM frag_jobs, jobs
                             WHERE
                                frag_state = \'LEON\'
                                AND jobs.job_id = frag_jobs.frag_id_job
                                AND jobs.state != \'Error\'
                                AND jobs.state != \'Terminated\'
                                AND jobs.state != \'Finishing\'
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}



# get_timered_job
# returns the list of jobs that have their frag state to TIMER_ARMED
# parameters : base
# return value : list of jobid
# side effects : /
sub get_timered_job($) {
    my $dbh = shift;
    my $sth = $dbh->prepare("   SELECT jobs.*
                                FROM frag_jobs, jobs
                                WHERE
                                    frag_jobs.frag_state = \'TIMER_ARMED\'
                                    AND frag_jobs.frag_id_job = jobs.job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}


# get_toexterminate_job
# returns the list of jobs that have their frag state to LEON_EXTERMINATE
# parameters : base
# return value : list of jobid
# side effects : /
sub get_to_exterminate_jobs($) {
    my $dbh = shift;
    my $sth = $dbh->prepare("   SELECT jobs.*
                                FROM frag_jobs, jobs
                                WHERE
                                    frag_state = \'LEON_EXTERMINATE\'
                                    AND frag_jobs.frag_id_job = jobs.job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}


# Get the frag_state value for a specific job
sub get_job_frag_state($$) {
    my $dbh = shift;
    my $jobid = shift;
    my $sth = $dbh->prepare("   SELECT frag_state
                                FROM frag_jobs
                                WHERE
                                    frag_id_job = $jobid
                            ");
    $sth->execute();
    my @ref = $sth->fetchrow_array();
    $sth->finish();

    return($ref[0]);
}


# set_assigned_moldable_job
# sets the assigned_moldable_job field to the given value
# parameters : base, jobid, moldable id
# return value : /
sub set_assigned_moldable_job($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $moldable_id = shift;
    
    $dbh->do("  UPDATE jobs
                SET assigned_moldable_job = $moldable_id
                WHERE
                    job_id = $job_id
            ");
}



# set_running_date
# sets the starting time of the job passed in parameter to the current time
# parameters : base, jobid
# return value : /
# side effects : changes the field startTime of the job in the table Jobs
sub set_running_date($$) {
    my $dbh = shift;
    my $job_id = shift;
    
    my $runningDate;
    my $date = get_date($dbh);
    my $minDate = get_gantt_date($dbh);
    if ($date < $minDate){
        $runningDate = $minDate;
    }else{
        $runningDate = $date;
    }
    
    my $sth = $dbh->prepare("   UPDATE jobs
                                SET start_time = \'$runningDate\'
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    $sth->finish();
}



# set_running_date_arbitrary
# sets the starting time of the job passed in parameter to arbitrary time
# parameters : base, jobid
# return value : /
# side effects : changes the field start_time of the job in the table Jobs
sub set_running_date_arbitrary($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $date = shift;

    $dbh->do("UPDATE jobs SET start_time = \'$date\'
              WHERE job_id = $job_id
             ");
}



# set_finish_date
# sets the maximal stoping time of the job passed in parameter to the current
# time
# parameters : base, jobid
# return value : /
# side effects : changes the field stop_time of the job in the table Jobs
sub set_finish_date($$) {
    my $dbh = shift;
    my $job_id = shift;
    
    my $finishDate;
    my $date = get_date($dbh);
    my $jobInfo = get_job($dbh,$job_id);
    my $minDate = $jobInfo->{'start_time'};
    if ($date < $minDate){
        $finishDate = $minDate;
    }else{
        $finishDate = $date;
    }
    my $sth = $dbh->prepare("   UPDATE jobs
                                SET stop_time = \'$finishDate\'
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    $sth->finish();
}


# set_job_exit_code
# parameters : base, jobid, exit code
sub set_job_exit_code($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $exit_code = shift;
    
    $dbh->do("  UPDATE jobs
                SET exit_code = $exit_code
                WHERE
                    job_id = $job_id
             ");
}


my $TREE_CACHE_HASH;
# get_possible_wanted_resources
# return a tree ref : a data structure with corresponding resources with what is asked
sub get_possible_wanted_resources($$$$$$$){
    my $dbh = shift;
    my $possible_resources_vector = shift;
    my $impossible_resources_vector = shift;
    my $resources_to_ignore_array = shift;
    my $properties = shift;
    my $wanted_resources_ref = shift;
    my $order_part = shift;

    my $sql_in_string = "\'1\'";
    if (defined($resources_to_ignore_array) and ($#{$resources_to_ignore_array} >= 0)){
        $sql_in_string = "resource_id NOT IN (";
        $sql_in_string .= join(",",@{$resources_to_ignore_array});
        $sql_in_string .= ")";
    }

    if (defined($order_part)){
        $order_part = "ORDER BY $order_part";
    }else{
        $order_part = "";
    }
    
    my @wanted_resources = @{$wanted_resources_ref};
    if ($wanted_resources[$#wanted_resources]->{resource} ne "resource_id"){
        push(@wanted_resources, {
                                    resource => "resource_id",
                                    value    => -1,
                                });
    }
    
    my $sql_where_string = "\'1\'";
    
    if ((defined($properties)) and ($properties ne "")){
        $sql_where_string .= " AND ( $properties )";
    }
    
    #Get only wanted resources
    my $resource_string;
    my $resource_tree_cache_key;
    foreach my $r (@wanted_resources){
        $resource_string .= " $r->{resource},";
        $resource_tree_cache_key .= " $r->{resource}=$r->{value},";
    }
    chop($resource_string);

    # Search if this was already seen
    if (defined($TREE_CACHE_HASH->{$resource_tree_cache_key}->{$sql_where_string}->{$sql_in_string}->{$order_part}->{$possible_resources_vector}->{$impossible_resources_vector})){
        #oar_debug("[IOlib] Use tree cache to get ressource structure.\n");
        return(OAR::Schedulers::ResourceTree::clone($TREE_CACHE_HASH->{$resource_tree_cache_key}->{$sql_where_string}->{$sql_in_string}->{$order_part}->{$possible_resources_vector}->{$impossible_resources_vector}));
    }
    my $sth = $dbh->prepare("SELECT $resource_string
                             FROM resources
                             WHERE
                                ($sql_where_string) AND
                                $sql_in_string
                             $order_part
                            ");
    if (!$sth->execute()){
        return(undef);
    }
    
    # Initialize root
    my $result ;
    $result = OAR::Schedulers::ResourceTree::new();
    my $wanted_children_number = $wanted_resources[0]->{value};
    OAR::Schedulers::ResourceTree::set_needed_children_number($result,$wanted_children_number);

    while (my @sql = $sth->fetchrow_array()){
        my $father_ref = $result;
        foreach (my $i = 0; $i <= $#wanted_resources; $i++){
            # Feed the tree for all resources
            $father_ref = OAR::Schedulers::ResourceTree::add_child($father_ref, $wanted_resources[$i]->{resource}, $sql[$i], $result);

            if ($i < $#wanted_resources){
                $wanted_children_number = $wanted_resources[$i+1]->{value};
            }else{
                $wanted_children_number = 0;
            }
            OAR::Schedulers::ResourceTree::set_needed_children_number($father_ref,$wanted_children_number);
            # Verify if we must keep this child if this is resource_id resource name
            if ($wanted_resources[$i]->{resource} eq "resource_id"){
                if ((defined($impossible_resources_vector)) and (vec($impossible_resources_vector, $sql[$i], 1))){
                    OAR::Schedulers::ResourceTree::delete_subtree($father_ref);
                    $i = $#wanted_resources + 1;
                }elsif ((defined($possible_resources_vector)) and (!vec($possible_resources_vector, $sql[$i], 1))){
                    OAR::Schedulers::ResourceTree::delete_subtree($father_ref);
                    $i = $#wanted_resources + 1;
                }
            }
        }
    }
    
    $sth->finish();

    $TREE_CACHE_HASH->{$resource_tree_cache_key}->{$sql_where_string}->{$sql_in_string}->{$order_part}->{$possible_resources_vector}->{$impossible_resources_vector} = $result;
    return(OAR::Schedulers::ResourceTree::clone($result));
}

# estimate_job_nb_resources
# returns an array with an estimation of the number of resources that can be
# used by a job:
#   [
#     {
#       nbresources => int,
#       walltime => int,
#       comment => string
#     }
#   ]
sub estimate_job_nb_resources($$$){
    my ($dbh_ro, $ref_resource_list, $jobproperties) = @_;

    my ($dead_resources_vec, @dead_resources) = OAR::IO::get_resource_ids_in_state($dbh_ro,"Dead");
    my @results = ();
    foreach my $moldable_resource (@{$ref_resource_list}){
        my $tmp_moldable_result = {
                                    nbresources => 0,
                                    walltime => $Default_job_walltime,
                                    comment => "no comment"
                                  };
        $tmp_moldable_result->{walltime} = $moldable_resource->[1] if (defined($moldable_resource->[1]));
        my $resource_id_list_vector = '';
        foreach my $r (@{$moldable_resource->[0]}){
            # SECURITY : we must use read only database access for this request
            my $tmp_properties = $r->{property};
            if ((defined($jobproperties)) and ($jobproperties ne "")){
                if (!defined($tmp_properties)){
                    $tmp_properties = $jobproperties;
                }else{
                    $tmp_properties = "($tmp_properties) AND ($jobproperties)"
                }
            }
            my $tree = get_possible_wanted_resources($dbh_ro, undef, $resource_id_list_vector, \@dead_resources, $tmp_properties, $r->{resources}, undef);
            $tree = OAR::Schedulers::ResourceTree::delete_tree_nodes_with_not_enough_resources_and_unnecessary_subtrees($tree, undef);
            if (!defined($tree)){
                # Resource description does not match with the content of the
                # database
                if ($DBI::errstr ne ""){
                    my $tmp_err = $DBI::errstr;
                    chop($tmp_err);
                    $tmp_moldable_result->{comment} = "Bad resource request ($tmp_err)";
                    $tmp_moldable_result->{nbresources} = 0;
                }else{
                    $tmp_moldable_result->{comment} = "There are not enough resources for your request";
                    $tmp_moldable_result->{nbresources} = 0;
                }
                last;
            }else{
                my ($tmp_leafs_vec, $tmp_leafs_hashref) = OAR::Schedulers::ResourceTree::get_tree_leafs_vec($tree);
                $resource_id_list_vector |= $tmp_leafs_vec;
                my @leafs = keys(%{$tmp_leafs_hashref});
                $tmp_moldable_result->{nbresources} += $#leafs + 1;
            }
        }
        push(@results, $tmp_moldable_result);
    }
    return(@results);
}

# manage the job key if option is activated
# read job key file if import from file 
# generate a job key if no import.
# function returns with $job_key_priv and $job_key_pub set if $use_job_key is set.
sub job_key_management($$$$) {
    my ($use_job_key,$import_job_key_inline,$import_job_key_file,$export_job_key_file) = @_;

    my $job_key_priv = '';
    my $job_key_pub = '';

    if (defined ($use_job_key) and !($import_job_key_inline ne "") and !($import_job_key_file ne "") and defined($ENV{OAR_JOB_KEY_FILE})){
        $import_job_key_file=$ENV{OAR_JOB_KEY_FILE};
    }
    if ((!defined($use_job_key)) and (($import_job_key_inline ne "") or ($import_job_key_file ne "") or ($export_job_key_file ne ""))){
        warn("Error: You must set the --use-job-key (or -k) option in order to use other job key related options.\n");
        return(-15,'','');
    }
    if (defined($use_job_key)){
        if (($import_job_key_inline ne "") and ($import_job_key_file ne "")){
            warn("Error: You cannot import a job key both inline and from a file at the same time.\n");
            return(-15,'','');
        }
        my $tmp_job_key_file = OAR::Tools::get_default_oarexec_directory()."/oarsub_$$.jobkey";
        if (($import_job_key_inline ne "") or ($import_job_key_file ne "")){
            # job key is imported
            if ($import_job_key_inline ne "") {
                # inline import
                print ("Import job key inline.\n");
                unless (sysopen(FH,"$tmp_job_key_file",O_CREAT|O_WRONLY,0600)) {
                    warn("Error: Cannot open tmp file for writing: $tmp_job_key_file\n");
                    return(-14,'','');
                }
                syswrite(FH,$import_job_key_inline);
                close(F);
            } else {
                # file import
                print ("Import job key from file: $import_job_key_file\n");
                my $lusr= $ENV{OARDO_USER};
                # read key files: oardodo su - user needed in order to be able to read the file for sure
                # safer way to do a `cmd`, see perl cookbook 
                my $pid;
                die "cannot fork: $!" unless defined ($pid = open(SAFE_CHILD, "-|"));
                if ($pid == 0) {
                    $ENV{OARDO_BECOME_USER} = $lusr;
                    unless (exec("oardodo cat $import_job_key_file")) {
                        warn ("Error: Cannot read key file:$import_job_key_file\n");
                        exit(-14);
                    }
                    exit(0);
                }else{
                    unless (sysopen(FH,"$tmp_job_key_file",O_CREAT|O_WRONLY,0600)) {
                        warn("Error: Cannot open tmp file for writing: $tmp_job_key_file\n");
                        return(-14,'','');
                    }
                    while (<SAFE_CHILD>) {
                        syswrite(FH,$_);
                    }
                    close(FH);
                }
                close(SAFE_CHILD);
            }
            # extract the public key from the private one
            system({"bash"} "bash","-c","SSH_ASKPASS=/bin/true ssh-keygen -y -f $tmp_job_key_file < /dev/null 2> /dev/null > $tmp_job_key_file.pub");
            if ($? != 0){
                warn ("Error: Fail to extract the public key. Please verify that the job key to import is valid.\n");
                if (-e $tmp_job_key_file) { 
                    unlink($tmp_job_key_file);
                }
                if (-e $tmp_job_key_file.".pub") { 
                    unlink($tmp_job_key_file.".pub");
                }
                return(-14,'','');
            }
        } else {
            # we must generate the key
            print("Generate a job key...\n");
            # ssh-keygen: no passphrase, smallest key (1024 bits), ssh2 rsa faster than dsa.
            system({"bash"} "bash","-c",'ssh-keygen -b 1024 -N "" -t rsa -f "'.$tmp_job_key_file.'" > /dev/null');
            if ($? != 0) {
                warn ("Error: Job key generation failed ($?).\n");
                return(-14,'','');
            }
        }
        # priv and pub key file must now exist.
        unless (open(F, "< $tmp_job_key_file")){
            warn ("Error: fail to read private key.\n");
            return(-14,'','');
        }
        while ($_ = <F>){
            $job_key_priv .= $_;
        }
        close(F);
        unless (open(F, "< $tmp_job_key_file.pub")){
            warn ("Error: fail to read private key.\n");
            return(-14,'','');
        }
        while ($_ = <F>){
            $job_key_pub .= $_;
        }
        close(F);
        unlink($tmp_job_key_file,$tmp_job_key_file.".pub");
    }
    
    # last checks
    if (defined($use_job_key)){
        if ($job_key_pub eq "") {
            warn("Error: missing job public key (private key found).\n");
            return(-15,'','');
        } 
        if ($job_key_priv eq "") {
            warn("Error: missing job private key (public key found).\n");
            return(-15,'','');
        } 
        if ($job_key_pub !~ /^(ssh-rsa|ssh-dss)\s.+\n*$/){
            warn("Error: Bad job key format. The public key must begin with either `ssh-rsa' or `ssh-dss' and is only 1 line.\n");
            return(-14,'','');
        }
        $job_key_pub =~ s/\n//g;
    }

    return(0,$job_key_priv, $job_key_pub);
}


# add_micheline_job
# adds a new job(or multiple in case of array-job) to the table Jobs applying 
# the admission rules from the base  parameters : base, jobtype, nbnodes, 
# weight, command, infotype, maxtime, queuename, jobproperties, 
# startTimeReservation
# return value : ref. of array of created jobids
# side effects : adds an entry to the table Jobs
#                the first jobid is found taking the maximal jobid from 
#                jobs in the table plus 1, the next (if any) takes the next 
#                jobid. Array-job submission is atomic and array_index are 
#                sequential
#                the rules in the base are pieces of perl code directly
#                evaluated here, so in theory any side effect is possible
#                in normal use, the unique effect of an admission rule should
#                be to change parameters

#TODO: moldable and array job, mysql LOAD INFILE, pg COPY or test limit

sub add_micheline_job($$$$$$$$$$$$$$$$$$$$$$$$$$$$$){
   my ($dbh, $dbh_ro, $jobType, $ref_resource_list, $command, $infoType, $queue_name, $jobproperties, $startTimeReservation, $idFile, $checkpoint, $checkpoint_signal, $notify, $job_name,$job_env,$type_list,$launching_directory,$anterior_ref,$stdout,$stderr,$job_hold,$project,$use_job_key,$import_job_key_inline,$import_job_key_file,$export_job_key_file,$initial_request_string, $array_job_nb,$array_params_ref) = @_;

    my $array_id = 0;

    my $startTimeJob = "0";
    my $reservationField = "None";
    #Test if this job is a reservation
    if ($startTimeReservation > 0){
        $reservationField = "toSchedule";
        $startTimeJob = $startTimeReservation;
    }

    my $rules;
    my $user= $ENV{OARDO_USER};

    # Verify notify syntax
    if ((defined($notify)) and ($notify !~ m/^\s*(\[\s*(.+)\s*\]\s*)?(mail|exec)\s*:.+$/m)){
        warn("/!\\Bad syntax for the notify option\n");
        return(-6);
    }
    
    # Check the stdout and stderr path validity
    if ((defined($stdout)) and ($stdout !~ m/^[a-zA-Z0-9_.\/\-\%\\ ]+$/m)) {
      warn("/!\\ Invalid stdout file name (bad character)\n");
      return(-12);
    }
    if (defined($stderr) and ($stderr !~ m/^[a-zA-Z0-9_.\/\-\%\\ ]+$/m)) {
      warn("/!\\ Invalid stderr file name (bad character)\n");
      return(-13);
    }    

#    # Verify job name
#    if ($job_name !~ m/^\w*$/m){
#        warn("ERROR : The job name must contain only alphanumeric characters plus '_'\n");
#        return(-7);
#    }

#    # Verify the content of user command
#    if ( "$command" !~ m/^[\w\s\/\.\-]*$/m ){
#        warn("ERROR : The command to launch contains bad characters -- $command\n");
#        return(-4);
#    }
    
    # Verify the content of env variables
    if ( "$job_env" !~ m/^[\w\=\s\/\.\-\"]*$/m ){
        warn("ERROR : The specified environnement variables contains bad characters -- $job_env\n");
        return(-9);
    }
    #Retrieve Micheline's rules from the table
    my $sth = $dbh->prepare("SELECT rule FROM admission_rules WHERE enabled = 'YES' ORDER BY priority,id");
    $sth->execute();
    while (my $ref = $sth->fetchrow_hashref()) {
        $rules = $rules.$ref->{'rule'};
    }
    $sth->finish();
    # This variable is used to add some resources properties restrictions but
    # after the validation (job is queued even if there are not enough
    # resources availbale)
    my $jobproperties_applied_after_validation = "";
    #Apply rules
    eval $rules;
    if ($@) {
        warn("Admission Rule ERROR : $@ \n");
        return(-2);
    }

    #Test if the queue exists
    my %all_queues = get_all_queue_informations($dbh);
    if (!defined($all_queues{$queue_name})){
        warn("ERROR : The queue $queue_name does not exist\n");
        return(-8);
    }
      
    my @array_job_commands;
    if ($#{$array_params_ref}>=0) {
        foreach my $params (@{$array_params_ref}){
            push(@array_job_commands, $command." ".$params);
        }
    } else {
        for (my $i=0; $i<$array_job_nb; $i++){ 
            push(@array_job_commands,$command);
        }
    } 

    my $array_index = 1;
    my @Job_id_list;
    if (($array_job_nb>1)  and (not defined($use_job_key)) and ($#{$ref_resource_list} == 0)) { #to test  add_micheline_simple_array_job
      warn("Simple array job submission is used\n"); 
      my $simple_job_id_list_ref = add_micheline_simple_array_job_non_contiguous($dbh, $dbh_ro, $jobType, $ref_resource_list, \@array_job_commands, $infoType, $queue_name, $jobproperties, $startTimeReservation, $idFile, $checkpoint, $checkpoint_signal, $notify, $job_name,$job_env,$type_list,$launching_directory,$anterior_ref,$stdout,$stderr,$job_hold,$project,$initial_request_string, $array_id, $user, $reservationField, $startTimeJob, $array_index, $jobproperties_applied_after_validation);
    return($simple_job_id_list_ref);
    } else {
      # single job to submit and when job key is used with array job 
      foreach my $command (@array_job_commands){
      my ($err,$ssh_priv_key,$ssh_pub_key) = job_key_management($use_job_key,$import_job_key_inline,$import_job_key_file,$export_job_key_file);
        if ($err != 0){
          push(@Job_id_list, $err);
          return(\@Job_id_list);
        }
        push(@Job_id_list, add_micheline_subjob($dbh, $dbh_ro, $jobType, $ref_resource_list, $command, $infoType, $queue_name, $jobproperties, $startTimeReservation, $idFile, $checkpoint, $checkpoint_signal, $notify, $job_name,$job_env,$type_list,$launching_directory,$anterior_ref,$stdout,$stderr,$job_hold,$project,$ssh_priv_key,$ssh_pub_key,$initial_request_string, $array_id, $user, $reservationField, $startTimeJob, $array_index, $jobproperties_applied_after_validation));
        if ($Job_id_list[-1] <= 0){
          return(\@Job_id_list);
        } else {
          if ($array_id <= 0){
            $array_id = $Job_id_list[0];
          }
          $array_index++;
        }
        if (defined($use_job_key) and ($export_job_key_file ne "")){
          # we must copy the keys in the directory specified with the right name
          my $export_job_key_file_tmp = $export_job_key_file;
          $export_job_key_file_tmp =~ s/%jobid%/$Job_id_list[-1]/g;
    
          my $lusr= $ENV{OARDO_USER};
          my $pid;
          # write the private job key with the user ownership
          unless (defined ($pid = open(SAFE_CHILD, "|-"))) {
            warn ("Error: Cannot open pipe ($?)");
            exit(-14);
          }
          if ($pid == 0) {
              umask(oct("177"));
              $ENV{OARDO_BECOME_USER} = $lusr;
              open(STDERR, ">/dev/null");
                  unless (exec("oardodo dd of=$export_job_key_file_tmp")) {
                  warn ("Error: Cannot exec user shell ($?)");
                  push(@Job_id_list,-14);
                  return(@Job_id_list);
              }
          } else {
              print SAFE_CHILD $ssh_priv_key;
              unless (close(SAFE_CHILD)) { 
                  warn ("Error: Cannot close pipe {$?}");
                  push(@Job_id_list,-14);
                  return(@Job_id_list);
              }
          }
          print "Export job key to file: ".$export_job_key_file_tmp."\n";
        }
      }
   }
   return(\@Job_id_list);
}

# Format a string which shows the maximum useful info
# Return string is destinated to the "message" job table field
sub format_job_message_text($$$$$$$$$){
    my (
        $job_name,
        $estimated_nb_resources,
        $estimated_walltime,
        $job_type,
        $reservation,
        $queue,
        $project,
        $type_list_array_ref,
        $string
        ) = @_;

    my $job_mode = 'B';
    if ($reservation ne 'None'){
        $job_mode = 'R';
    }elsif ($job_type eq 'INTERACTIVE'){
        $job_mode = 'I';
    }
    my $types_to_text = '';
    $types_to_text = "T=".join('|',@{$type_list_array_ref})."," if ($#{$type_list_array_ref} >= 0);
    my $job_message = "R=$estimated_nb_resources,W=".duration_to_sql($estimated_walltime).",J=$job_mode,";
    $job_message .= "N=$job_name," if ((defined($job_name)) and ($job_name ne ""));
    $job_message .= "Q=$queue," if (($queue ne "default") and ($queue ne "besteffort"));
    $job_message .= "P=$project," if ($project ne "default");
    $job_message .= "$types_to_text";
    chop($job_message);
    $job_message .= " ($string)" if ($string ne '');
    
    return($job_message);
}

sub add_micheline_subjob($$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$){
    my ($dbh, $dbh_ro, $jobType, $ref_resource_list, $command, $infoType, $queue_name, $jobproperties, $startTimeReservation, $idFile, $checkpoint, $checkpoint_signal, $notify, $job_name,$job_env,$type_list,$launching_directory,$anterior_ref,$stdout,$stderr,$job_hold,$project,$ssh_priv_key,$ssh_pub_key,$initial_request_string, $array_id, $user, $reservationField, $startTimeJob, $array_index, $jobproperties_applied_after_validation) = @_;

    # Test if properties and resources are coherent
    my $estimated_nb_resources = 0;
    my $estimated_walltime = 0;
    foreach my $e (estimate_job_nb_resources($dbh_ro, $ref_resource_list, $jobproperties)){
        #print("[TEST] $e->{nbresources} $e->{walltime} $e->{comment}\n");
        if ($e->{nbresources} == 0){
            warn($e->{comment}."\n");
            return(-5);
        }elsif ($estimated_walltime == 0){
            $estimated_nb_resources = $e->{nbresources};
            $estimated_walltime = $e->{walltime};
        }
    }

    # Add admin properties to the job
    if ($jobproperties_applied_after_validation ne ""){
        if ($jobproperties ne ""){
            $jobproperties = "($jobproperties) AND $jobproperties_applied_after_validation";
        }else{
            $jobproperties = "$jobproperties_applied_after_validation";
        }
    }

    lock_table($dbh,["challenges","jobs"]);
    # Verify the content of the ssh keys
    if (($ssh_pub_key ne "") or ($ssh_priv_key ne "")){
        # Check if the keys are used by other jobs
        if (get_count_same_ssh_keys_current_jobs($dbh,$user,$ssh_priv_key,$ssh_pub_key) > 0){
            warn("/!\\ Another job is using the same ssh keys\n");
            return(-10);
        }
    }

    # Check the user validity
    if (! $user =~ /[a-zA-Z0-9_-]+/ ) {
      warn("/!\\ Invalid username: '$user'\n");
      return(-11);
    }
    
    my $job_message = format_job_message_text($job_name,$estimated_nb_resources, $estimated_walltime, $jobType, $reservationField, $queue_name, $project, $type_list, '');

    #Insert job
    my $date = get_date($dbh);
    #lock_table($dbh,["jobs"]);
    my $job_name_quoted = $dbh->quote($job_name);
    $notify = $dbh->quote($notify);
    $command = $dbh->quote($command);
    $job_env = $dbh->quote($job_env);
    $jobproperties = $dbh->quote($jobproperties);
    $launching_directory = $dbh->quote($launching_directory);
    $project = $dbh->quote($project);
    $initial_request_string = $dbh->quote($initial_request_string);
    $dbh->do("INSERT INTO jobs
              (job_type,info_type,state,job_user,command,submission_time,queue_name,properties,launching_directory,reservation,start_time,file_id,checkpoint,job_name,notify,checkpoint_signal,job_env,project,initial_request,array_id,array_index,message)
              VALUES (\'$jobType\',\'$infoType\',\'Hold\',\'$user\',$command,\'$date\',\'$queue_name\',$jobproperties,$launching_directory,\'$reservationField\',\'$startTimeJob\',$idFile,$checkpoint,$job_name_quoted,$notify,\'$checkpoint_signal\',$job_env,$project,$initial_request_string,$array_id,$array_index,\'$job_message\')
             ");

    my $job_id = get_last_insert_id($dbh,"jobs_job_id_seq");
    #unlock_table($dbh);
   
    if ($array_id <= 0){
        $dbh->do("  UPDATE jobs
                    SET array_id = $job_id
                    WHERE
                        job_id = $job_id
                 ");
    }

    $ssh_priv_key = $dbh->quote($ssh_priv_key);
    $ssh_pub_key = $dbh->quote($ssh_pub_key);
    my $random_number = int(rand(1000000000000));
    $dbh->do("INSERT INTO challenges (job_id,challenge,ssh_private_key,ssh_public_key)
              VALUES ($job_id,\'$random_number\',$ssh_priv_key,$ssh_pub_key)
             ");
    unlock_table($dbh);

    if (!defined($stdout) or ($stdout eq "")){
        $stdout = "OAR";
        $stdout .= ".$job_name" if (defined($job_name));
        $stdout .= '.%jobid%.stdout';
    }else{
        $stdout =~ s/%jobname%/$job_name/g;
    }
    if (!defined($stderr) or ($stderr eq "")){
        $stderr = "OAR";
        $stderr .= ".$job_name" if (defined($job_name));
        $stderr .= '.%jobid%.stderr';
    }else{
        $stderr =~ s/%jobname%/$job_name/g;
    }

    $stdout = $dbh->quote($stdout);
    $stderr = $dbh->quote($stderr);

    #TODO: Why this not directly integrated in "INSERT INTO jobs ..." query ???
    $dbh->do("UPDATE jobs
              SET
                  stdout_file = $stdout,
                  stderr_file = $stderr
              WHERE
                  state = \'Hold\'
                  AND job_id = $job_id
    ");

    foreach my $moldable_resource (@{$ref_resource_list}){
        #lock_table($dbh,["moldable_job_descriptions"]);
        $moldable_resource->[1] = $Default_job_walltime if (!defined($moldable_resource->[1]));
        $dbh->do("  INSERT INTO moldable_job_descriptions (moldable_job_id,moldable_walltime)
                    VALUES ($job_id,\'$moldable_resource->[1]\')
                 ");
        my $moldable_id = get_last_insert_id($dbh,"moldable_job_descriptions_moldable_id_seq");
        #unlock_table($dbh);

        foreach my $r (@{$moldable_resource->[0]}){
            #lock_table($dbh,["job_resource_groups"]);
            my $property = $r->{property};
            $property = $dbh->quote($property);
            $dbh->do("  INSERT INTO job_resource_groups (res_group_moldable_id,res_group_property)
                        VALUES ($moldable_id,$property)
                     ");
            my $res_group_id = get_last_insert_id($dbh,"job_resource_groups_res_group_id_seq");
            #unlock_table($dbh);

            my $order = 0;
            foreach my $l (@{$r->{resources}}){
                $dbh->do("  INSERT INTO job_resource_descriptions (res_job_group_id,res_job_resource_type,res_job_value,res_job_order)
                            VALUES ($res_group_id,\'$l->{resource}\',\'$l->{value}\',$order)
                         ");
                $order++;
            }
        }
    }

    foreach my $t (@{$type_list}){
        my $quoted_t = $dbh->quote($t);
        $dbh->do("  INSERT INTO job_types (job_id,type)
                    VALUES ($job_id,$quoted_t)
                 ");
    }

    foreach my $a (@{$anterior_ref}){
        $dbh->do("  INSERT INTO job_dependencies (job_id,job_id_required)
                    VALUES ($job_id,$a)
                 ");
    }

    if (!defined($job_hold)) {
        $dbh->do("INSERT INTO job_state_logs (job_id,job_state,date_start)
                  VALUES ($job_id,\'Waiting\',$date)
                 ");
    
        $dbh->do("  UPDATE jobs
                    SET state = \'Waiting\'
                    WHERE
                        job_id = $job_id
                 ");
    }else{
        $dbh->do("INSERT INTO job_state_logs (job_id,job_state,date_start)
                  VALUES ($job_id,\'Hold\',$date)
                 ");
    }
    #$dbh->do("UNLOCK TABLES");

    return($job_id);
}

# return value : ref. of array of created jobids
# TODO: moldable, very large insertion,   
# ssh_key by job is not supported (,$ssh_priv_key,$ssh_pub_key)
# /!\ this function supposes that database engine provides contiguous id when multiple inserts query is executed (Postgres doesn't provide this)
# 

sub add_micheline_simple_array_job ($$$$$$$$$$$$$$$$$$$$$$$$$$$$){
    my ($dbh, $dbh_ro, $jobType, $ref_resource_list, $array_job_commands_ref, $infoType, $queue_name, $jobproperties, $startTimeReservation, $idFile, $checkpoint, $checkpoint_signal, $notify, $job_name,$job_env,$type_list,$launching_directory,$anterior_ref,$stdout,$stderr,$job_hold,$project,$initial_request_string, $array_id, $user, $reservationField, $startTimeJob, $array_index, $jobproperties_applied_after_validation) = @_;

    my @Job_id_list;

    my $pg=0;
    if ($Db_type eq "Pg") {$pg=1}

    # Check the user validity
    if (! $user =~ /[a-zA-Z0-9_-]+/ ) {
      warn("/!\\ Invalid username: '$user'\n");
      return(-11);
    }

    # Check the jobs are no moldable
    if ($#{$ref_resource_list}>=1) {
      die ("/!\\ array jobs cannot be moldable\n");
    }

    # Test if properties and resources are coherent
    my $estimated_nb_resources = 0;
    my $estimated_walltime = 0;
    foreach my $e (estimate_job_nb_resources($dbh_ro, $ref_resource_list, $jobproperties)){
        #print("[TEST] $e->{nbresources} $e->{walltime} $e->{comment}\n");
        if ($e->{nbresources} == 0){
            warn($e->{comment}."\n");
            return(-5);
        }elsif ($estimated_walltime == 0){
            $estimated_nb_resources = $e->{nbresources};
            $estimated_walltime = $e->{walltime};
        }
    }

    # Add admin properties to the job
    if ($jobproperties_applied_after_validation ne ""){
        if ($jobproperties ne ""){
            $jobproperties = "($jobproperties) AND $jobproperties_applied_after_validation";
        }else{
            $jobproperties = "$jobproperties_applied_after_validation";
        }
    }

    my $job_message = format_job_message_text($job_name,$estimated_nb_resources, $estimated_walltime, $jobType, $reservationField, $queue_name, $project, $type_list, '');

    #insert in jobs table
    #prepare parameter request
    my $date = get_date($dbh);
    my $job_name_quoted = $dbh->quote($job_name);
    $notify = $dbh->quote($notify);
    #$command = $dbh->quote($command);
    $job_env = $dbh->quote($job_env);
    $jobproperties = $dbh->quote($jobproperties);
    $launching_directory = $dbh->quote($launching_directory);
    $project = $dbh->quote($project);
    $initial_request_string = $dbh->quote($initial_request_string);

    if (!defined($stdout) or ($stdout eq "")){
        $stdout = "OAR";
        $stdout .= ".$job_name" if (defined($job_name));
        $stdout .= '.%jobid%.stdout';
    }else{
        $stdout =~ s/%jobname%/$job_name/g;
    }
    if (!defined($stderr) or ($stderr eq "")){
        $stderr = "OAR";
        $stderr .= ".$job_name" if (defined($job_name));
        $stderr .= '.%jobid%.stderr';
    }else{
        $stderr =~ s/%jobname%/$job_name/g;
    }

    $stdout = $dbh->quote($stdout);
    $stderr = $dbh->quote($stderr);

    my $query_jobs = "INSERT INTO jobs
              (job_type,info_type,state,job_user,command,submission_time,queue_name,properties,launching_directory,reservation,start_time,file_id,checkpoint,job_name,notify,checkpoint_signal,stdout_file,stderr_file,job_env,project,initial_request,array_id,array_index,message)
              VALUES ";

    my $nb_jobs = $#{$array_job_commands_ref}+1;
    #print "nb_jobs: $nb_jobs\n";
    foreach my $command (@{$array_job_commands_ref}){
      $command = $dbh->quote($command);
      $query_jobs =  $query_jobs . "(\'$jobType\',\'$infoType\',\'Hold\',\'$user\',$command,\'$date\',\'$queue_name\',$jobproperties,$launching_directory,\'$reservationField\',\'$startTimeJob\',$idFile,$checkpoint,$job_name_quoted,$notify,\'$checkpoint_signal\',$stdout,$stderr,$job_env,$project,$initial_request_string,$array_id,$array_index,\'$job_message\'),";
      $array_index++;
    }
    
    chop($query_jobs);
    lock_table($dbh,["jobs"]);
    $dbh->do($query_jobs);
    my $first_array_job_id = get_last_insert_id($dbh,"jobs_job_id_seq");
    unlock_table($dbh);

    #print "$query_jobs\n";
    #print "First_array_job_id: $first_array_job_id\n";

    if ($pg) {$first_array_job_id  -= $nb_jobs-1}
    my $job_id = $first_array_job_id;

    my $random_number;
    my $query_challenges = "INSERT INTO challenges (job_id,challenge,ssh_private_key,ssh_public_key) VALUES ";

    my $moldable_resource =  @{$ref_resource_list}[0];  
    $moldable_resource->[1] = $Default_job_walltime if (!defined($moldable_resource->[1]));
    my $walltime = $moldable_resource->[1];
    my $query_moldable_job_descriptions="INSERT INTO moldable_job_descriptions (moldable_job_id,moldable_walltime) VALUES "; 
 
    for (my $i=0; $i<$nb_jobs; $i++){
      push(@Job_id_list,$job_id);
      $random_number = int(rand(1000000000000));
      $query_challenges = $query_challenges . "($job_id,\'$random_number\',\'\',\'\'),"; #TODO $ssh_priv_key,$ssh_pub_key
      $query_moldable_job_descriptions = $query_moldable_job_descriptions . "($job_id,\'$walltime\'),";
      $job_id++;
    }
    lock_table($dbh,["challenges"]);
    chop($query_challenges);
    $dbh->do($query_challenges);
    unlock_table($dbh);

    chop($query_moldable_job_descriptions);
    lock_table($dbh,["moldable_job_descriptions"]);
    $dbh->do($query_moldable_job_descriptions);
    my $first_moldable_id = get_last_insert_id($dbh,"moldable_job_descriptions_moldable_id_seq");
    unlock_table($dbh);
    #print "First_moldable_id: $first_moldable_id\n";

    my $moldable_id = $first_moldable_id;
    if ($pg) {$moldable_id -= $nb_jobs-1}
    my $query_job_resource_groups  = "INSERT INTO job_resource_groups (res_group_moldable_id,res_group_property) VALUES ";
    for (my $i=0; $i<$nb_jobs; $i++){
      foreach my $r (@{$moldable_resource->[0]}){
        my $property = $r->{property};
        $property = $dbh->quote($property);
        $query_job_resource_groups = $query_job_resource_groups . "($moldable_id,$property),";
      }
      $moldable_id++;
    }

    my $nb_resource_grp = $#{$moldable_resource->[0]} + 1;
    chop($query_job_resource_groups);
    lock_table($dbh,["job_resource_groups"]);
    $dbh->do($query_job_resource_groups);
    my $first_res_group_id  = get_last_insert_id($dbh,"job_resource_groups_res_group_id_seq");
    unlock_table($dbh);
    #print "First_res_group_id : $first_res_group_id \n";

    my $res_group_id = $first_res_group_id;
     if ($pg) {$res_group_id -= $nb_resource_grp*$nb_jobs-1} #TODO: add *nb_moldable for moldable support 
    my $query_job_resource_descriptions="INSERT INTO job_resource_descriptions (res_job_group_id,res_job_resource_type,res_job_value,res_job_order) VALUES ";
    
    for (my $i=0; $i<$nb_jobs; $i++){
      foreach my $r (@{$moldable_resource->[0]}){
        my $order = 0;
        foreach my $l (@{$r->{resources}}){
          $query_job_resource_descriptions = $query_job_resource_descriptions . "($res_group_id,\'$l->{resource}\',\'$l->{value}\',$order),";
          $order++;
        }
        $res_group_id++;
      }
    }

    chop($query_job_resource_descriptions);
    $dbh->do($query_job_resource_descriptions);

    #populate job_types table
    if  ($#{$type_list}>-1) {
      $job_id = $first_array_job_id;
      my $query_job_types = "INSERT INTO job_types (job_id,type) VALUES "; 
      for (my $i=0; $i<$nb_jobs; $i++){
        foreach my $t (@{$type_list}){
          my $quoted_t = $dbh->quote($t);
          $query_job_types = $query_job_types . "($job_id,$quoted_t),";
        }
        $job_id++;
      }
    
      chop($query_job_types);
      $dbh->do($query_job_types);
    }

    #  
    # anterior job setting
    #
    if ($#{$anterior_ref} >0) {
      $job_id = $first_array_job_id;
      my $query_job_dependencies = "INSERT INTO job_dependencies (job_id,job_id_required) VALUES ";
      for (my $i=0; $i<$nb_jobs; $i++){
        foreach my $a (@{$anterior_ref}){
          $query_job_dependencies = $query_job_dependencies . "($job_id,$a),";
        } 
        $job_id++;
      }
      chop($query_job_dependencies);
      $dbh->do($query_job_dependencies);
    }

    #
    # Hold/Waiting management, array_id and job_state_log setting
    # Job is inserted with hold state first
    #
    my $query_job_state_logs = "INSERT INTO job_state_logs (job_id,job_state,date_start) VALUES ";
    $job_id = $first_array_job_id;
    my $query_array_id = "UPDATE jobs SET ";
    my $state_log = "\'Hold\'";

    if  (defined($job_hold)) {
      $query_array_id =  $query_array_id . " array_id = ". $first_array_job_id . " WHERE job_id IN (";
    }
    else {
      $query_array_id =  $query_array_id . "state = \'Waiting\', array_id = " . $first_array_job_id . " WHERE job_id IN (";
      $state_log = "\'Waiting\'";
    }
  
    #update array_id field and set job to state if waiting and insert job_state_log 
    for (my $i=0; $i<$nb_jobs; $i++){
      $query_job_state_logs = $query_job_state_logs . "($job_id,$state_log,$date),";
      $query_array_id = $query_array_id . "$job_id,";
      $job_id++;
    }
    chop($query_job_state_logs);
    chop($query_array_id);
    $query_array_id = $query_array_id . ")";
    $dbh->do($query_job_state_logs);
    $dbh->do($query_array_id);

    return (\@Job_id_list);
}

# return value : ref. of array of created jobids
# TODO: moldable, very large insertion,   
# ssh_key by job is not supported (,$ssh_priv_key,$ssh_pub_key)
# This function doesn't imply that database engine must provides contiguous id when multiple inserts query is executed (Postgres doesn't provide this)
# 

sub add_micheline_simple_array_job_non_contiguous ($$$$$$$$$$$$$$$$$$$$$$$$$$$$$){
    my ($dbh, $dbh_ro, $jobType, $ref_resource_list, $array_job_commands_ref, $infoType, $queue_name, $jobproperties, $startTimeReservation, $idFile, $checkpoint, $checkpoint_signal, $notify, $job_name,$job_env,$type_list,$launching_directory,$anterior_ref,$stdout,$stderr,$job_hold,$project,$initial_request_string, $array_id, $user, $reservationField, $startTimeJob, $array_index, $jobproperties_applied_after_validation) = @_;

    my @Job_id_list = ();
    my $nb_jobs = $#{$array_job_commands_ref}+1;

    my $pg=0;
    if ($Db_type eq "Pg") {$pg=1}

    # Check the user validity
    if (! $user =~ /[a-zA-Z0-9_-]+/ ) {
      warn("/!\\ Invalid username: '$user'\n");
      return(-11);
    }

    # Check the jobs are no moldable
    if ($#{$ref_resource_list}>=1) {
      die ("/!\\ array jobs cannot be moldable\n");
    }

    # Test if properties and resources are coherent
    my $estimated_nb_resources = 0;
    my $estimated_walltime = 0;
    foreach my $e (estimate_job_nb_resources($dbh_ro, $ref_resource_list, $jobproperties)){
        #print("[TEST] $e->{nbresources} $e->{walltime} $e->{comment}\n");
        if ($e->{nbresources} == 0){
            warn($e->{comment}."\n");
            return(-5);
        }elsif ($estimated_walltime == 0){
            $estimated_nb_resources = $e->{nbresources};
            $estimated_walltime = $e->{walltime};
        }
    }
    
    # Add admin properties to the job
    if ($jobproperties_applied_after_validation ne ""){
        if ($jobproperties ne ""){
            $jobproperties = "($jobproperties) AND $jobproperties_applied_after_validation";
        }else{
            $jobproperties = "$jobproperties_applied_after_validation";
        }
    }

    my $job_message = format_job_message_text($job_name,$estimated_nb_resources, $estimated_walltime, $jobType, $reservationField, $queue_name, $project, $type_list, '');

    #insert in jobs table
    #prepare parameter request
    my $date = get_date($dbh);
    my $job_name_quoted = $dbh->quote($job_name);
    $notify = $dbh->quote($notify);
    #$command = $dbh->quote($command);
    $job_env = $dbh->quote($job_env);
    $jobproperties = $dbh->quote($jobproperties);
    $launching_directory = $dbh->quote($launching_directory);
    $project = $dbh->quote($project);
    $initial_request_string = $dbh->quote($initial_request_string);

    if (!defined($stdout) or ($stdout eq "")){
        $stdout = "OAR";
        $stdout .= ".$job_name" if (defined($job_name));
        $stdout .= '.%jobid%.stdout';
    }
    if (!defined($stderr) or ($stderr eq "")){
        $stderr = "OAR";
        $stderr .= ".$job_name" if (defined($job_name));
        $stderr .= '.%jobid%.stderr';
    }

    $stdout = $dbh->quote($stdout);
    $stderr = $dbh->quote($stderr);

    my $query_jobs = "INSERT INTO jobs
              (job_type,info_type,state,job_user,command,submission_time,queue_name,properties,launching_directory,reservation,start_time,file_id,checkpoint,job_name,notify,checkpoint_signal,stdout_file,stderr_file,job_env,project,initial_request,array_id,array_index,message)
              VALUES ";

    my $command = $dbh->quote(@{$array_job_commands_ref}[0]);
    my $query_first_job =  $query_jobs . "(\'$jobType\',\'$infoType\',\'Hold\',\'$user\',$command,\'$date\',\'$queue_name\',$jobproperties,$launching_directory,\'$reservationField\',\'$startTimeJob\',$idFile,$checkpoint,$job_name_quoted,$notify,\'$checkpoint_signal\',$stdout,$stderr,$job_env,$project,$initial_request_string,$array_id,$array_index,\'$job_message\')";
    $dbh->do($query_first_job);
    #get the job id which will be also be the array_id
    my $first_job_id = get_last_insert_id($dbh,"jobs_job_id_seq");
    $array_id = $first_job_id;
    #update array_id
    my $query_array_id = "UPDATE jobs SET array_id = $array_id WHERE job_id = $array_id";
    $dbh->do($query_array_id);

    #insert remaining array jobs with array_id
    $query_jobs = "INSERT INTO jobs
              (job_type,info_type,state,job_user,command,submission_time,queue_name,properties,launching_directory,reservation,start_time,file_id,checkpoint,               job_name,notify,checkpoint_signal,stdout_file,stderr_file,job_env,project,initial_request,array_id,array_index,message)
              VALUES ";

    foreach my $command (@{$array_job_commands_ref}){
      if ($array_index > 1) {
        $command = $dbh->quote($command);
        $query_jobs =  $query_jobs . "(\'$jobType\',\'$infoType\',\'Hold\',\'$user\',$command,\'$date\',\'$queue_name\',$jobproperties,$launching_directory,\'$reservationField\',\'$startTimeJob\',$idFile,$checkpoint,$job_name_quoted,$notify,\'$checkpoint_signal\',$stdout,$stderr,$job_env,$project,$initial_request_string,$array_id,$array_index,\'$job_message\'),";
      }
      $array_index++;
    }
    chop($query_jobs);
    $dbh->do($query_jobs);

    #retreive job_ids thanks to array_id value
    my $query_job_ids = $dbh->prepare("SELECT job_id FROM jobs WHERE array_id = $array_id ORDER BY job_id ASC");
    $query_job_ids->execute();
    while (my @ref = $query_job_ids->fetchrow_array()){
      push(@Job_id_list,$ref[0]);
    }
    $query_job_ids->finish();

    # populate challenges and moldable_job_descriptions tables and build str_job_ids
    my $random_number;
    my $query_challenges = "INSERT INTO challenges (job_id,challenge,ssh_private_key,ssh_public_key) VALUES ";

    my $moldable_resource =  @{$ref_resource_list}[0];  
    $moldable_resource->[1] = $Default_job_walltime if (!defined($moldable_resource->[1]));
    my $walltime = $moldable_resource->[1];
    my $query_moldable_job_descriptions="INSERT INTO moldable_job_descriptions (moldable_job_id,moldable_walltime) VALUES "; 

    my $str_job_ids = ""; 

    foreach my $job_id (@Job_id_list){
      $random_number = int(rand(1000000000000));
      $query_challenges = $query_challenges . "($job_id,\'$random_number\',\'\',\'\'),"; #TODO $ssh_priv_key,$ssh_pub_key
      $query_moldable_job_descriptions = $query_moldable_job_descriptions . "($job_id,\'$walltime\'),";
      $str_job_ids = $str_job_ids . "$job_id,";
    }
    
    chop($query_challenges);
    $dbh->do($query_challenges);

    chop($query_moldable_job_descriptions);
    $dbh->do($query_moldable_job_descriptions);

    chop($str_job_ids);

    #retreive moldable_ids thanks to job_ids 
    my $query_moldable_ids = $dbh->prepare("SELECT moldable_id FROM moldable_job_descriptions WHERE moldable_job_id IN ($str_job_ids) ORDER BY moldable_id ASC");
    $query_moldable_ids->execute();
    my @moldable_ids = ();
    while (my @ref = $query_moldable_ids->fetchrow_array()){
      push(@moldable_ids,$ref[0]);
    }
    $query_moldable_ids->finish();

    # populate job_resource_groups table and build str_moldable_ids
    my $query_job_resource_groups  = "INSERT INTO job_resource_groups (res_group_moldable_id,res_group_property) VALUES ";
    my $str_moldable_ids = "";
    foreach my $moldable_id (@moldable_ids) {
      foreach my $r (@{$moldable_resource->[0]}){
        my $property = $r->{property};
        $property = $dbh->quote($property);
        $query_job_resource_groups = $query_job_resource_groups . "($moldable_id,$property),";
      }
       $str_moldable_ids = $str_moldable_ids . "$moldable_id,";
    }

    my $nb_resource_grp = $#{$moldable_resource->[0]} + 1;
    chop($query_job_resource_groups);
    $dbh->do($query_job_resource_groups);

    chop($str_moldable_ids);

    #retreive res_group_ids thanks to moldable_ids 
    my $query_res_group_ids =  $dbh->prepare("SELECT res_group_id FROM job_resource_groups WHERE res_group_moldable_id IN ($str_moldable_ids) ORDER BY res_group_id ASC");
    $query_res_group_ids->execute();
    my @res_group_ids = ();
    while (my @ref = $query_res_group_ids->fetchrow_array()){
      push(@res_group_ids,$ref[0]);
    }
    $query_res_group_ids->finish();

    # number of resource group
    #my $nb_resource_grp = $#{$moldable_resource->[0]} + 1;

    #populate job_resource_descriptions table
    my $query_job_resource_descriptions="INSERT INTO job_resource_descriptions (res_job_group_id,res_job_resource_type,res_job_value,res_job_order) VALUES ";
    my $k=0;
    for (my $i=0; $i<$nb_jobs; $i++){
      foreach my $r (@{$moldable_resource->[0]}){
        my $order = 0;
        foreach my $l (@{$r->{resources}}){
          $query_job_resource_descriptions = $query_job_resource_descriptions . "($res_group_ids[$k],\'$l->{resource}\',\'$l->{value}\',$order),";
          $order++;
        }
        $k++;
      }
    }

    chop($query_job_resource_descriptions);
    $dbh->do($query_job_resource_descriptions);

    #populate job_types table
    if  ($#{$type_list}>-1) {
      my $query_job_types = "INSERT INTO job_types (job_id,type) VALUES "; 
      foreach my $job_id (@Job_id_list){
        foreach my $t (@{$type_list}){
          my $quoted_t = $dbh->quote($t);
          $query_job_types = $query_job_types . "($job_id,$quoted_t),";
        }
      }
    
      chop($query_job_types);
      $dbh->do($query_job_types);
    }

    #  
    # anterior job setting
    #
    if ($#{$anterior_ref} >0) {
      my $query_job_dependencies = "INSERT INTO job_dependencies (job_id,job_id_required) VALUES ";
      foreach my $job_id (@Job_id_list){
        foreach my $a (@{$anterior_ref}){
          $query_job_dependencies = $query_job_dependencies . "($job_id,$a),";
        } 
      }
      chop($query_job_dependencies);
      $dbh->do($query_job_dependencies); 
    }

    # Hold/Waiting management, job_state_log setting
    # Job is inserted with hold state first
    my $query_job_state_logs = "INSERT INTO job_state_logs (job_id,job_state,date_start) VALUES ";
    my $state_log = "\'Hold\'";

    if  (!defined($job_hold)) {
      $dbh->do("UPDATE jobs SET state = \'Waiting\' WHERE array_id = $array_id");
      $state_log = "\'Waiting\'";
    }
  
    #update array_id field and set job to state if waiting and insert job_state_log 
    foreach my $job_id (@Job_id_list){
      $query_job_state_logs = $query_job_state_logs . "($job_id,$state_log,$date),";
    }
    chop($query_job_state_logs);
    $query_array_id = $query_array_id . ")";
    $dbh->do($query_job_state_logs);

    return (\@Job_id_list);
}

# get_job
# returns a ref to some hash containing data for the job of id passed in
# parameter
# parameters : base, jobid
# return value : ref
# side effects : /
sub get_job($$) {
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();

    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return($ref);
}


# get_job_state
# returns only the state of a job
# parameter
# parameters : base, jobid
# return value : string
# side effects : /
sub get_job_state($$) {
    my $dbh = shift;
    my $job_id = shift;

    my @res = $dbh->selectrow_array("   SELECT state
                                FROM jobs
                                WHERE
                                    job_id = $job_id
                            ");
    return($res[0]);
}


# get_current_moldable_job
# returns a ref to some hash containing data for the moldable job of id passed in
# parameter
# parameters : base, moldable job id
# return value : ref
# side effects : /
sub get_current_moldable_job($$) {
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM moldable_job_descriptions
                                WHERE
                                    moldable_index = \'CURRENT\'
                                    AND moldable_id = $moldable_job_id
                            ");
    $sth->execute();

    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return $ref;
}


# get_moldable_job
# returns a ref to some hash containing data for the moldable job of id passed in
# parameter
# parameters : base, moldable job id
# return value : ref
# side effects : /
sub get_moldable_job($$) {
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM moldable_job_descriptions
                                WHERE
                                    moldable_id = $moldable_job_id
                            ");
    $sth->execute();

    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return $ref;
}

# get_scheduled_job_description
# returns a ref to some hash containing data for the moldable job corresponding
# to the waiting job given by the id passed in
# parameter
# parameters : base, moldable job id
# return value : ref
# side effects : /
sub get_scheduled_job_description($$) {
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM moldable_job_descriptions,gantt_jobs_predictions_visu
                                WHERE
                                    moldable_job_descriptions.moldable_job_id = $job_id
                                  AND gantt_jobs_predictions_visu.moldable_job_id = moldable_id
                            ");
    $sth->execute();

    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return $ref;
}




# set_job_state
# sets the state field of the job of id passed in parameter
# parameters : base, jobid, state
# return value : /
# side effects : changes the field reservation of the job in the table Jobs
sub set_job_state($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $state = shift;
    
    if ($dbh->do("  UPDATE jobs
                    SET
                        state = \'$state\'
                    WHERE
                        job_id = $job_id AND
                        state != \'Error\' AND
                        state != \'Terminated\' AND
                        state != \'$state\'
                 ") > 0){
        my $date = get_date($dbh);
        $dbh->do("  UPDATE job_state_logs
                    SET
                        date_stop = \'$date\'
                    WHERE
                        date_stop = 0
                        AND job_id = $job_id
                ");
        $dbh->do("  INSERT INTO job_state_logs (job_id,job_state,date_start)
                    VALUES ($job_id,\'$state\',\'$date\')
                 ");

        if (($state eq "Terminated") or ($state eq "Error") or ($state eq "toLaunch") or ($state eq "Running") or ($state eq "Suspended") or ($state eq "Resuming")){
            my $job = get_job($dbh,$job_id);
            my ($addr,$port) = split(/:/,$job->{info_type});
            if ($state eq "Suspended"){
                OAR::Modules::Judas::notify_user($dbh,$job->{notify},$addr,$job->{job_user},$job->{job_id},$job->{job_name},"SUSPENDED","Job is suspended.");
            }elsif ($state eq "Resuming"){
                OAR::Modules::Judas::notify_user($dbh,$job->{notify},$addr,$job->{job_user},$job->{job_id},$job->{job_name},"RESUMING","Job is resuming.");
            }elsif ($state eq "Running"){
                OAR::Modules::Judas::notify_user($dbh,$job->{notify},$addr,$job->{job_user},$job->{job_id},$job->{job_name},"RUNNING","Job is running.");
            }elsif ($state eq "toLaunch"){
                update_current_scheduler_priority($dbh,$job->{job_id},$job->{assigned_moldable_job},"+2","START");
            }elsif (($state eq "Terminated") or ($state eq "Error")){
                #$dbh->do("  DELETE FROM challenges
                #            WHERE job_id = $job_id
                #         ");
            
                if ($job->{stop_time} < $job->{start_time}){
                    $dbh->do("  UPDATE jobs
                                SET stop_time = start_time
                                WHERE
                                    job_id = $job_id
                             ");
                }
                if (defined($job->{assigned_moldable_job}) and ($job->{assigned_moldable_job} ne "")){
                    # Update last_job_date field for resources used
                    OAR::IO::update_scheduler_last_job_date($dbh, $date,$job->{assigned_moldable_job});
                }
    
                if ($state eq "Terminated"){
                    OAR::Modules::Judas::notify_user($dbh,$job->{notify},$addr,$job->{job_user},$job->{job_id},$job->{job_name},"END","Job stopped normally.");
                }else{
                    # Verify if the job was suspended and if the resource
                    # property suspended is updated
                    if ($job->{suspended} eq "YES"){
                        
                        my @r = get_current_resources_with_suspended_job($dbh);
                        if ($#r >= 0){
                        $dbh->do("  UPDATE resources
                                    SET suspended_jobs = \'NO\'
                                    WHERE
                                        resource_id NOT IN (".join(",",@r).")
                                 ");
                        }else{
                            $dbh->do("  UPDATE resources
                                        SET suspended_jobs = \'NO\'
                                     ");
                        }
                    }
                    OAR::Modules::Judas::notify_user($dbh,$job->{notify},$addr,$job->{job_user},$job->{job_id},$job->{job_name},"ERROR","Job stopped abnormally or an OAR error occured.");
                }
                update_current_scheduler_priority($dbh,$job->{job_id},$job->{assigned_moldable_job},"-2","STOP");
                
                # Here we must not be asynchronously with the scheduler
                OAR::IO::log_job($dbh,$job->{job_id});
                # $dbh is valid so these 2 variables must be defined
                OAR::Tools::notify_tcp_socket($Remote_host,$Remote_port,"ChState");
            }
        }
    }
}


# log_job
# sets the index fields to LOG on several tables
# this will speed up future queries
# parameters : base, jobid
# return value : /
sub log_job($$){
    my $dbh = shift;
    my $job_id = shift;
    
    my $job = get_job($dbh,$job_id);
        
    if ($Db_type eq "Pg"){
        $dbh->do("  UPDATE moldable_job_descriptions
                    SET
                        moldable_index = \'LOG\'
                    WHERE
                        moldable_job_descriptions.moldable_index = \'CURRENT\'
                        AND moldable_job_descriptions.moldable_job_id = $job_id
                 ");

        $dbh->do("  UPDATE job_resource_descriptions
                    SET
                        res_job_index = \'LOG\'
                    FROM moldable_job_descriptions, job_resource_groups
                    WHERE
                        moldable_job_descriptions.moldable_job_id = $job_id
                        AND job_resource_groups.res_group_moldable_id = moldable_job_descriptions.moldable_id
                        AND job_resource_descriptions.res_job_group_id = job_resource_groups.res_group_id
             ");
        
        $dbh->do("  UPDATE job_resource_groups
                    SET
                        res_group_index = \'LOG\'
                    FROM moldable_job_descriptions
                    WHERE
                        job_resource_groups.res_group_index = \'CURRENT\'
                        AND moldable_job_descriptions.moldable_index = \'LOG\'
                        AND moldable_job_descriptions.moldable_job_id = $job_id
                        AND job_resource_groups.res_group_moldable_id = moldable_job_descriptions.moldable_id
             ");
    }else{
        $dbh->do("  UPDATE moldable_job_descriptions, job_resource_groups, job_resource_descriptions
                    SET job_resource_groups.res_group_index = \'LOG\',
                        job_resource_descriptions.res_job_index = \'LOG\',
                        moldable_job_descriptions.moldable_index = \'LOG\'
                    WHERE
                        moldable_job_descriptions.moldable_index = \'CURRENT\'
                        AND job_resource_groups.res_group_index = \'CURRENT\'
                        AND job_resource_descriptions.res_job_index = \'CURRENT\'
                        AND moldable_job_descriptions.moldable_job_id = $job_id
                        AND job_resource_groups.res_group_moldable_id = moldable_job_descriptions.moldable_id
                        AND job_resource_descriptions.res_job_group_id = job_resource_groups.res_group_id
                ");
    }

    $dbh->do("  UPDATE job_types
                SET types_index = \'LOG\'
                WHERE
                    job_types.types_index = \'CURRENT\'
                    AND job_types.job_id = $job_id
             ");
    
    $dbh->do("  UPDATE job_dependencies
                SET job_dependency_index = \'LOG\'
                WHERE
                    job_dependencies.job_dependency_index = \'CURRENT\'
                    AND job_dependencies.job_id = $job_id
             ");

    if (defined($job->{assigned_moldable_job}) and ($job->{assigned_moldable_job} ne "")){
        $dbh->do("  UPDATE assigned_resources
                    SET assigned_resource_index = \'LOG\'
                    WHERE
                        assigned_resource_index = \'CURRENT\'
                        AND moldable_job_id = $job->{assigned_moldable_job}
                ");
    }
}

# Get the amount of time in the defined state for a job
# args : base, job_id, job_state
# returns a number of seconds
sub get_job_duration_in_state($$$){
    my $dbh = shift;
    my $job_id = shift;
    my $job_state = shift;

    my $current_time = get_date($dbh);

    my $sth = $dbh->prepare("   SELECT date_start, date_stop
                                FROM job_state_logs
                                WHERE
                                    job_id = $job_id AND
                                    job_state = \'$job_state\'
                            ");
    $sth->execute();
    my $sum = 0;
    while (my $ref = $sth->fetchrow_hashref()){
        my $tmp_sum = 0;
        if ($ref->{date_stop} == 0){
            $tmp_sum = $current_time - $ref->{date_start};
        }else{
            $tmp_sum += $ref->{date_stop} - $ref->{date_start};
        }
        $sum += $tmp_sum if ($tmp_sum > 0);
    }
    $sth->finish();

    return($sum);
}

# archive_some_moldable_job_nodes
# sets the index fields to LOG in the table assigned_resources
# parameters : base, mjobid, hostnames
# return value : /
sub archive_some_moldable_job_nodes($$$){
    my $dbh = shift;
    my $mjob_id = shift;
    my $hosts = shift;
   
    my $value_str;
    foreach my $v (@{$hosts}){
        $value_str .= $dbh->quote($v);
        $value_str .= ',';
    }
    chop($value_str);
    if ($Db_type eq "Pg"){
        $dbh->do("  UPDATE assigned_resources
                    SET
                        assigned_resource_index = \'LOG\'
                    FROM resources
                    WHERE
                        assigned_resources.assigned_resource_index = \'CURRENT\'
                        AND assigned_resources.moldable_job_id = $mjob_id
                        AND resources.resource_id = assigned_resources.resource_id
                        AND resources.network_address IN (".$value_str.") 
             ");
    }else{
        $dbh->do("  UPDATE assigned_resources, resources
                    SET 
                        assigned_resources.assigned_resource_index = \'LOG\'
                    WHERE
                        assigned_resources.assigned_resource_index = \'CURRENT\'
                        AND assigned_resources.moldable_job_id = $mjob_id
                        AND resources.resource_id = assigned_resources.resource_id
                        AND resources.network_address IN (".$value_str.")
                ");
    }
}


# Resubmit a job and give the new job_id
# args : database, job id
sub resubmit_job($$){
    my $dbh = shift;
    my $job_id = shift;

    my $lusr= $ENV{OARDO_USER};
    
    my $job = get_job($dbh, $job_id);
    return(0) if (!defined($job->{job_id}));
    return(-1) if ($job->{job_type} ne "PASSIVE");
    return(-2) if (($job->{state} ne "Error") and ($job->{state} ne "Terminated") and ($job->{state} ne "Finishing"));
    return(-3) if (($lusr ne $job->{job_user}) and ($lusr ne "oar") and ($lusr ne "root"));
    
    lock_table($dbh,["challenges","jobs"]);
    # Verify the content of the ssh keys
    my ($job_challenge,$ssh_private_key,$ssh_public_key) = OAR::IO::get_job_challenge($dbh,$job_id);
    if (($ssh_public_key ne "") or ($ssh_private_key ne "")){
        # Check if the keys are used by other jobs
        if (get_count_same_ssh_keys_current_jobs($dbh,$job->{job_user},$ssh_private_key,$ssh_public_key) > 0){
            return(-4);
        }
    }

    my $command = $dbh->quote($job->{command});
    my $jobproperties = $dbh->quote($job->{properties});
    my $launching_directory = $dbh->quote($job->{launching_directory});
    my $file_id = $dbh->quote($job->{file_id});
    my $jenv = $dbh->quote($job->{job_env});
    my $project = $dbh->quote($job->{project});
    my $initial_request_string = $dbh->quote($job->{initial_request});
    my $job_name = $dbh->quote($job->{job_name});
    my $date = get_date($dbh);
    my $start_time = 0;
    $start_time = $job->{start_time} if ($job->{reservation} ne "None");
    #lock_table($dbh,["jobs"]);
    $dbh->do("INSERT INTO jobs
              (job_type,info_type,state,job_user,command,submission_time,queue_name,properties,launching_directory,file_id,checkpoint,job_name,notify,checkpoint_signal,reservation,resubmit_job_id,start_time,job_env,project,initial_request,array_id,array_index)
              VALUES (\'$job->{job_type}\',\'$job->{info_type}\',\'Hold\',\'$job->{job_user}\',$command,\'$date\',\'$job->{queue_name}\',$jobproperties,$launching_directory,$file_id,$job->{checkpoint},$job_name,\'$job->{notify}\',\'$job->{checkpoint_signal}\',\'$job->{reservation}\',$job_id,\'$start_time\',$jenv,$project,$initial_request_string,$job->{array_id},$job->{array_index})
             ");
    my $new_job_id = get_last_insert_id($dbh,"jobs_job_id_seq");
    #unlock_table($dbh);

    my $random_number = int(rand(1000000000000));
    #$dbh->do("INSERT INTO challenges (job_id,challenge)
    #          VALUES ($new_job_id,\'$random_number\')
    #         ");
    
    my $pub_key = "";
    my $priv_key = "";
    my $sth = $dbh->prepare("   SELECT ssh_private_key, ssh_public_key
                                FROM challenges
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    my $ref_keys = $sth->fetchrow_hashref();
    $sth->finish();
    if (defined($ref_keys)){
        $priv_key = $ref_keys->{ssh_private_key};
        $pub_key = $ref_keys->{ssh_public_key};
    }
    $priv_key = $dbh->quote($priv_key);
    $pub_key = $dbh->quote($pub_key);
   
    $dbh->do("INSERT INTO challenges (job_id,challenge,ssh_private_key,ssh_public_key)
              VALUES ($new_job_id,\'$random_number\',$priv_key,$pub_key)
             ");
    unlock_table($dbh);

    my $stdout_file = $dbh->quote($job->{stdout_file});
    my $stderr_file = $dbh->quote($job->{stderr_file});

    $dbh->do("UPDATE jobs
              SET
                  stdout_file = $stdout_file,
                  stderr_file = $stderr_file
              WHERE
                  state = \'Hold\'
                  AND job_id = $new_job_id
    ");

    $sth = $dbh->prepare("   SELECT moldable_id,moldable_walltime
                             FROM moldable_job_descriptions
                             WHERE
                                 moldable_job_id = $job_id
                         ");
    $sth->execute();
    my @moldable_ids = ();
    while (my @ref = $sth->fetchrow_array()) {
        push(@moldable_ids, [$ref[0], $ref[1]]);
    }
    $sth->finish();

    foreach my $m (@moldable_ids){
        my $moldable_resource = $m->[0];
        #lock_table($dbh,["moldable_job_descriptions"]);
        $dbh->do("  INSERT INTO moldable_job_descriptions (moldable_job_id,moldable_walltime)
                    VALUES ($new_job_id,\'$m->[1]\')
                 ");
        my $moldable_id = get_last_insert_id($dbh,"moldable_job_descriptions_moldable_id_seq");
        #unlock_table($dbh);
    
        $sth = $dbh->prepare("  SELECT res_group_id,res_group_property
                                FROM job_resource_groups
                                WHERE
                                    res_group_moldable_id = $moldable_resource
                             ");
        $sth->execute();
        my @groups = ();
        while (my @ref = $sth->fetchrow_array()) {
            push(@groups, [$ref[0],$ref[1]]);
        }
        $sth->finish();

        foreach my $res (@groups){
            my $r = $res->[0];
            #lock_table($dbh,["job_resource_groups"]);
            my $prop = $dbh->quote($res->[1]);
            $dbh->do("  INSERT INTO job_resource_groups (res_group_moldable_id,res_group_property)
                        VALUES ($moldable_id,$prop)
                     ");
            my $res_group_id = get_last_insert_id($dbh,"job_resource_groups_res_group_id_seq");
            #unlock_table($dbh);

            $sth = $dbh->prepare("  SELECT res_job_group_id,res_job_resource_type,res_job_value,res_job_order
                                    FROM job_resource_descriptions
                                    WHERE
                                        res_job_group_id = $r
                                ");
            $sth->execute();
            my @groups_desc = ();
            while (my @ref = $sth->fetchrow_array()) {
                push(@groups_desc, [$ref[0],$ref[1],$ref[2],$ref[3]]);
            }
            $sth->finish();

            foreach my $d (@groups_desc){
                $dbh->do("  INSERT INTO job_resource_descriptions (res_job_group_id,res_job_resource_type,res_job_value,res_job_order)
                            VALUES ($res_group_id,\'$d->[1]\',$d->[2],$d->[3])
                         ");
            }
        }
    }

    $sth = $dbh->prepare("  SELECT type
                            FROM job_types
                            WHERE
                                job_id = $job_id
                                ");
    $sth->execute();
    my @types = ();
    while (my @ref = $sth->fetchrow_array()) {
        push(@types, $ref[0]);
    }
    $sth->finish();

    foreach my $t (@types){
        $t = $dbh->quote($t);
        $dbh->do("  INSERT INTO job_types (job_id,type)
                    VALUES($new_job_id, $t)
                 ");
    }

    $dbh->do("  UPDATE job_dependencies
                SET job_id_required = $new_job_id
                WHERE
                    job_id_required = $job_id
             ");
   
    $dbh->do("INSERT INTO job_state_logs (job_id,job_state,date_start)
              VALUES ($new_job_id,\'Waiting\',$date)
             ");
    
    $dbh->do("  UPDATE jobs
                SET state = \'Waiting\'
                WHERE
                    job_id = $new_job_id
             ");

    return($new_job_id);
}


# is_job_already_resubmitted
# Check if the job was already resubmitted
# args : db ref, job id
sub is_job_already_resubmitted($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT COUNT(*)
                                FROM jobs
                                WHERE
                                    resubmit_job_id = $job_id
                            ");
    $sth->execute();
    my @ref = $sth->fetchrow_array();
    $sth->finish();
   
    return($ref[0]);
}

# set_job_resa_state
# sets the reservation field of the job of id passed in parameter
# parameters : base, jobid, state
# return value : /
# side effects : changes the field state of the job in the table Jobs
sub set_job_resa_state($$$){
    my $dbh = shift;
    my $job_id = shift;
    my $state = shift;
    my $sth = $dbh->prepare("UPDATE jobs SET reservation = \'$state\'
                             WHERE job_id = $job_id");
    $sth->execute();
    $sth->finish();
}



# set_job_message
# sets the message field of the job of id passed in parameter
# parameters : base, jobid, message
# return value : /
# side effects : changes the field message of the job in the table Jobs
sub set_job_message($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $message = shift;

    $message = $dbh->quote($message);
    $dbh->do("  UPDATE jobs
                SET message = $message
                WHERE
                    job_id = $job_id
             ");
}


# set_job_scheduler_info
# sets the scheduler_info field of the job of id passed in parameter
# parameters : base, jobid, message
# return value : /
sub set_job_scheduler_info($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $message = shift;

    $message = $dbh->quote($message);
    $dbh->do("  UPDATE jobs
                SET scheduler_info = $message
                WHERE
                    job_id = $job_id
             ");
}


# frag_job
# sets the flag 'ToFrag' of a job to 'Yes'
# parameters : base, jobid
# return value : 0 on success, -1 on error (if the user calling this method
#                is not the user running the job or oar), -2 if the job was
#                already killed
# side effects : changes the field ToFrag of the job in the table Jobs
sub frag_job($$) {
    my $dbh = shift;
    my $job_id = shift;

    my $lusr= $ENV{OARDO_USER};

    my $job = get_job($dbh, $job_id);

    if((defined($job)) && (($lusr eq $job->{job_user}) or ($lusr eq "oar") or ($lusr eq "root"))) {
        my $nbRes = $dbh->do("SELECT *
                              FROM frag_jobs
                              WHERE
                                frag_id_job = $job_id
                             ");
        if ( $nbRes < 1 ){
            my $date = get_date($dbh);
            $dbh->do("INSERT INTO frag_jobs (frag_id_job,frag_date)
                      VALUES ($job_id,\'$date\')
                     ");
            add_new_event($dbh,"FRAG_JOB_REQUEST",$job_id,"User $lusr requested to frag the job $job_id");
            return(0);
        }else{
            # Job already killed
            return(-2);
        }
    }else{
        return(-1);
    }
}


# ask_checkpoint_job
# Verify if the user is able to checkpoint the job
# args : database ref, job id
# returns : 0 if all is good, 1 if the user cannot do this, 2 if the job is not running, 3 if the job is Interactive
sub ask_checkpoint_job($$){
    my $dbh = shift;
    my $job_id = shift;

    my $lusr= $ENV{OARDO_USER};

    my $job = get_job($dbh, $job_id);

    return(3) if ((defined($job)) and ($job->{job_type} eq "INTERACTIVE"));
    if((defined($job)) && (($lusr eq $job->{job_user}) or ($lusr eq "oar") or ($lusr eq "root"))) {
        if ($job->{state} eq "Running"){
            #$dbh->do("LOCK TABLE event_log WRITE");
            add_new_event($dbh,"CHECKPOINT",$job_id,"User $lusr requested a checkpoint on the job $job_id");
            #$dbh->do("UNLOCK TABLES");
            return(0);
        }else{
            return(2);
        }
    }else{
        return(1);
    }   
}

# ask_signal_job
# Verify if the user is able to signal the job
# args : database ref, job id, signal
# returns : 0 if all is good, 1 if the user cannot do this, 2 if the job is not running, 3 if the job is Interactive
sub ask_signal_job($$$){
    my $dbh = shift;
    my $job_id = shift;
    my $signal = shift;

    my $lusr= $ENV{OARDO_USER};

    my $job = get_job($dbh, $job_id);

    return(3) if ((defined($job)) and ($job->{job_type} eq "INTERACTIVE"));
    if((defined($job)) && (($lusr eq $job->{job_user}) or ($lusr eq "oar") or ($lusr eq "root"))) {
        if ($job->{state} eq "Running"){
            #$dbh->do("LOCK TABLE event_log WRITE");
            add_new_event($dbh,"SIGNAL_$signal",$job_id,"User $lusr requested the signal $signal on the job $job_id");
            #$dbh->do("UNLOCK TABLES");
	    #oar_debug("[OAR::IO] added an event of type SIGNAL_$signal for job $job_id\n");
            return(0);
        }else{
            return(2);
        }
    }else{
        return(1);
    }   
}

# hold_job
# sets the state field of a job to 'Hold'
# equivalent to set_job_state(base,jobid,"Hold") except for permissions on user
# parameters : base, jobid
# return value : 0 on success, -1 on error (if the user calling this method
#                is not the user running the job)
# side effects : changes the field state of the job to 'Hold' in the table Jobs
sub hold_job($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $waiting_and_running = shift;

    my $lusr = $ENV{OARDO_USER};

    my $job = get_job($dbh, $job_id);
  
    my $user_allowed_hold_resume =  (lc(get_conf("USERS_ALLOWED_HOLD_RESUME")) eq "yes");
  
    my $event_type = "HOLD_WAITING_JOB";
    $event_type = "HOLD_RUNNING_JOB" if (defined($waiting_and_running));
    if (defined($job)){
        if (defined($waiting_and_running) and (not $user_allowed_hold_resume) and ($lusr ne "oar") and ($lusr ne "root")){
            return(-4);
        }elsif (($lusr eq $job->{job_user}) || ($lusr eq "oar") || ($lusr eq "root")){
            if (($job->{'state'} eq "Waiting") or ($job->{'state'} eq "Resuming")){
                add_new_event($dbh, $event_type, $job_id, "User $lusr launched oarhold on the job $job_id");
                return 0;
            }elsif((defined($waiting_and_running)) and (($job->{state} eq "toLaunch") or ($job->{state} eq "Launching") or ($job->{state} eq "Running"))){
                add_new_event($dbh, $event_type, $job_id, "User $lusr launched oarhold on the job $job_id");
                return 0;
            }else{
                return(-3);
            }
        }else{
            return(-2);
        }
    }else{
        return(-1);
    }
}



# resume_job
# returns the state of the job from 'Hold' to 'Waiting'
# equivalent to set_job_state(base,jobid,"Waiting") except for permissions on
# user and the fact the job must already be in 'Hold' state
# parameters : base, jobid
# return value : 0 on success, -1 on error (if the user calling this method
#                is not the user running the job)
# side effects : changes the field state of the job to 'Waiting' in the table
#                Jobs
sub resume_job($$) {
    my $dbh = shift;
    my $job_id = shift;

    my $lusr = $ENV{OARDO_USER};

    my $job = get_job($dbh, $job_id);

    my $user_allowed_hold_resume =  (lc(get_conf("USERS_ALLOWED_HOLD_RESUME")) eq "yes");

    if (defined($job)){
        if (($job->{'state'} eq "Suspended") and (not $user_allowed_hold_resume) and ($lusr ne "oar") and ($lusr ne "root")){
            return(-4);
        }elsif (($lusr eq $job->{job_user}) || ($lusr eq "oar") || ($lusr eq "root")){
            if (($job->{'state'} eq "Hold") or ($job->{'state'} eq "Suspended")){
                add_new_event($dbh, "RESUME_JOB", $job_id, "User $lusr launched oarresume on the job $job_id");
                return(0);
            }
            return(-3);
        }
        return(-2);
    } else {
        return(-1);
    }
}


# get the amount of time in the suspended state of a job
# args : base, job id, time in seconds
sub get_job_suspended_sum_duration($$$){
    my $dbh = shift;
    my $job_id = shift;
    my $current_time = shift;

    my $sth = $dbh->prepare("   SELECT date_start, date_stop
                                FROM job_state_logs
                                WHERE
                                    job_id = $job_id AND
                                    (job_state = \'Suspended\' OR
                                     job_state = \'Resuming\')
                            ");
    $sth->execute();
    my $sum = 0;
    while (my $ref = $sth->fetchrow_hashref()) {
        my $tmp_sum = 0;
        if ($ref->{date_stop} == 0){
            $tmp_sum = $current_time - $ref->{date_start};
        }else{
            $tmp_sum += $ref->{date_stop} - $ref->{date_start};
        }
        $sum += $tmp_sum if ($tmp_sum > 0);
    }
    $sth->finish();

    return($sum);
}


# Return the list of jobs running on resources allocated to another given job
# args : base, resume job id
sub get_jobs_on_resuming_job_resources($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT DISTINCT(j2.job_id) as job_id
                                FROM jobs j1,jobs j2,assigned_resources a1,assigned_resources a2
                                WHERE
                                    a1.assigned_resource_index = \'CURRENT\' AND
                                    a2.assigned_resource_index = \'CURRENT\' AND
                                    j1.job_id = $job_id AND
                                    j1.job_id != j2.job_id AND
                                    a1.moldable_job_id = j1.assigned_moldable_job AND
                                    a2.resource_id = a1.resource_id AND
                                    a2.moldable_job_id = j2.assigned_moldable_job AND
                                    j2.state IN (\'toLaunch\',\'toError\',\'toAckReservation\',\'Launching\',\'Running\',\'Finishing\')
                            ");
    $sth->execute();
    my @res;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res,$ref->{job_id});
    }
    $sth->finish();

    return(@res);
}


# Return the list of resources where there are Suspended jobs
# args: base
sub get_current_resources_with_suspended_job($){
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM assigned_resources, jobs
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\' AND
                                    jobs.state = \'Suspended\' AND
                                    jobs.assigned_moldable_job = assigned_resources.moldable_job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{resource_id});
    }
    $sth->finish();

    return(@res);
}

# suspend_job_action
# perform all action when a job is suspended
# parameters : base, jobid, moldable jobid
sub suspend_job_action($$$) {
    my $dbh = shift;
    my $job_id = shift;
    my $moldable_job_id = shift;

    set_job_state($dbh,$job_id,"Suspended");
    $dbh->do("  UPDATE jobs
                SET suspended = \'YES\'
                WHERE
                    job_id = $job_id
             ");
    my @r = get_current_resources_with_suspended_job($dbh);
    $dbh->do("  UPDATE resources
                SET suspended_jobs = \'YES\'
                WHERE
                   resource_id IN (".join(",",@r).")
             ");
}


# resume_job_action
# perform all action when a job is suspended
# parameters : base, jobid
sub resume_job_action($$) {
    my $dbh = shift;
    my $job_id = shift;

    set_job_state($dbh,$job_id,"Running");
    my @r = get_current_resources_with_suspended_job($dbh);
    if ($#r >= 0){
        $dbh->do("  UPDATE resources
                    SET suspended_jobs = \'NO\'
                    WHERE
                       resource_id NOT IN (".join(",",@r).")
                 ");
    }else{
        $dbh->do("  UPDATE resources
                    SET suspended_jobs = \'NO\'
                 ");
    }
}


# job_fragged
# sets the flag 'ToFrag' of a job to 'No'
# parameters : base, jobid
# return value : /
# side effects : changes the field ToFrag of the job in the table Jobs
sub job_fragged($$) {
    my $dbh = shift;
    my $job_id = shift;

    $dbh->do("UPDATE frag_jobs
              SET frag_state = \'FRAGGED\'
              WHERE frag_id_job = $job_id
             ");
}



# job_arm_leon_timer
# sets the state to TIMER_ARMED of job
# parameters : base, jobid
# return value : /
sub job_arm_leon_timer($$) {
    my $dbh = shift;
    my $job_id = shift;

    $dbh->do("  UPDATE frag_jobs
                SET frag_state = \'TIMER_ARMED\'
                WHERE
                    frag_id_job = $job_id
             ");
}


# job_refrag
# sets the state to LEON of job
# parameters : base, jobid
# return value : /
sub job_refrag($$) {
    my $dbh = shift;
    my $job_id = shift;

    $dbh->do("UPDATE frag_jobs SET frag_state = \'LEON\'
              WHERE frag_id_job = $job_id
             ");
}



# job_leon_exterminate
# sets the state LEON_EXTERMINATE of job
# parameters : base, jobid
# return value : /
sub job_leon_exterminate($$) {
    my $dbh = shift;
    my $job_id = shift;

    $dbh->do("UPDATE frag_jobs SET frag_state = \'LEON_EXTERMINATE\'
              WHERE frag_id_job = $job_id
             ");
}



# get_frag_date
# gets the date of the frag of a job
# parameters : base, jobid
# return value : date
sub get_frag_date($$) {
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("SELECT frag_date
                             FROM frag_jobs
                             WHERE frag_id_job = $job_id
                            ");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    $sth->finish();
    return($ref->{'frag_date'});
}


# Get all waiting reservation jobs
# parameter : database ref
# return an array of job informations
sub get_waiting_reservation_jobs($){
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs j
                                WHERE
                                    (j.state = \'Waiting\'
                                        OR j.state = \'toAckReservation\')
                                    AND j.reservation = \'Scheduled\'
                                ORDER BY j.job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return @res;
}


# Get all waiting reservation jobs in the specified queue
# parameter : database ref, queuename
# return an array of job informations
sub get_waiting_reservation_jobs_specific_queue($$){
    my $dbh = shift;
    my $queue = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs j
                                WHERE
                                    j.state=\'Waiting\'
                                    AND j.reservation = \'Scheduled\'
                                    AND j.queue_name = \'$queue\'
                                ORDER BY j.job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return @res;
}


# Get if it exists waiting jobs in the specified queue or not
# parameter : database ref, queuename
# return 0 --> no
#        1 --> yes
sub is_waiting_job_specific_queue_present($$){
    my $dbh = shift;
    my $queue = shift;

    my $sth = $dbh->prepare("   SELECT count(*)
                                FROM jobs
                                WHERE
                                    state=\'Waiting\'
                                    AND queue_name = \'$queue\'
                                LIMIT 1
                            ");
    $sth->execute();
    my ($res) = $sth->fetchrow_array();
    $sth->finish();
    return ($res > 0);
}


# get_jobs_to_schedule
# args : base ref, queue name
sub get_jobs_to_schedule($$$){
    my $dbh = shift;
    my $queue = shift;
    my $limit = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    state = \'Waiting\'
                                    AND reservation = \'None\'
                                    AND queue_name = \'$queue\'
                                ORDER BY job_id
                                LIMIT $limit
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}


# get_fairsharing_jobs_to_schedule
# args : base ref, queue name
sub get_fairsharing_jobs_to_schedule($$$){
    my $dbh = shift;
    my $queue = shift;
    my $limit = shift;

    my $req = "SELECT distinct(job_user)
               FROM jobs
               WHERE
                   state = \'Waiting\'
                   AND reservation = \'None\'
                   AND queue_name = \'$queue\'
               ";
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my @users = ();
    while (my @ref = $sth->fetchrow_array()) {
        push(@users, $ref[0]);
    }
    $sth->finish();

    my @res = ();
    foreach my $u (@users){
        my $req2 = "SELECT *
                    FROM jobs
                    WHERE
                        state = \'Waiting\'
                        AND reservation = \'None\'
                        AND queue_name = \'$queue\'
                        AND job_user = \'$u\'
                    ORDER BY job_id
                    LIMIT $limit
               ";
        my $sth = $dbh->prepare($req2);
        $sth->execute();
        while (my $ref = $sth->fetchrow_hashref()) {
            push(@res, $ref);
        }
        $sth->finish();
    }

    return(@res);
}


# get_job_types_hash
# return a hash table with all types for the given job ID
sub get_job_types_hash($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT type
                                FROM job_types
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    my %res;
    while (my $ref = $sth->fetchrow_hashref()) {
        if ($ref->{type} =~ m/^\s*(token)\s*\:\s*(\w+)\s*=\s*(\d+)\s*$/m){
            $res{$1}->{$2} = $3;
        }elsif ($ref->{type} =~ m/^\s*(\w+)\s*=\s*(.+)$/m){
            $res{$1} = $2;
        }else{
            $res{$ref->{type}} = "true";
        }
    }
    $sth->finish();

    return(\%res);
}


# get_job_types
# return the list of types for the given job ID
sub get_job_types($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT type
                                FROM job_types
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    my @res;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res,$ref->{type});
    }
    $sth->finish();

    return(@res);
}


# add_current_job_types
sub add_current_job_types($$$){
    my $dbh = shift;
    my $job_id = shift;
    my $type = shift;

    $dbh->do("  INSERT INTO job_types (job_id,type,types_index)
                VALUES ($job_id,\'$type\',\'CURRENT\')
             ");
}

# remove_current_job_types
sub remove_current_job_types($$$){
    my $dbh = shift;
    my $job_id = shift;
    my $type = shift;

    $dbh->do("  DELETE FROM job_types
                WHERE
                    job_id = $job_id AND
                    type = \'$type\' AND
                    types_index = \'CURRENT\'
             ");
}


# get_current_job_dependencies
# return an array table with all dependencies for the given job ID
sub get_current_job_dependencies($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT job_id_required
                                FROM job_dependencies
                                WHERE
                                    job_dependency_index = \'CURRENT\'
                                    AND job_id = $job_id
                            ");
    $sth->execute();
    my @res;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{job_id_required});
    }
    $sth->finish();

    return(@res);
}


# get_job_dependencies
# return an array table with all dependencies for the given job ID
sub get_job_dependencies($$){
    my $dbh = shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT job_id_required
                                FROM job_dependencies
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();
    my @res;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{job_id_required});
    }
    $sth->finish();

    return(@res);
}


# Get all waiting toSchedule reservation jobs in the specified queue
# parameter : database ref, queuename
# return an array of job informations
sub get_waiting_toSchedule_reservation_jobs_specific_queue($$){
    my $dbh = shift;
    my $queue = shift;

    my $sth = $dbh->prepare("   SELECT j.*
                                FROM jobs j
                                WHERE
                                    j.state=\'Waiting\'
                                    AND j.reservation = \'toSchedule\'
                                    AND j.queue_name = \'$queue\'
                                ORDER BY j.job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return @res;
}


# set walltime for a moldable job
sub set_moldable_job_max_time($$$){
    my ($dbh, $mol, $walltime) = @_;

    $dbh->do("  UPDATE moldable_job_descriptions
                SET moldable_walltime = \'$walltime\'
                WHERE
                    moldable_id = $mol
             ");
}


#ARRAY JOBS MANAGEMENT

# get_jobs_in_array
# returns the jobs within a same array
# parameters : base, array_id
# return value : flatened list of hashref jobs ids
sub get_jobs_in_array($$) {
    my $dbh = shift;
    my $array_id = $dbh->quote(shift);

    my $sth = $dbh->prepare("   SELECT job_id
                                FROM jobs
                                WHERE
                                    array_id = $array_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(@res);
}


# get_job_array_id($$)
# get array_id of a job with given job_id
# parameters : base,  job_id
# return value : array_id of the job
# side effects : / 
sub get_job_array_id($$){
    my $dbh = shift;
    my $job_id = shift;
    my $sth;

    $sth = $dbh->prepare("  SELECT array_id
                            FROM jobs
                            WHERE
                                job_id = $job_id
                         ");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    my @tmp_array = values(%$ref);

    my $array_id = $tmp_array[0];
    $sth->finish();
  
    return($array_id);
}
 

# get_array_subjobs($$)
# Get all the jobs of a given array_job
# parameters : base, array_id
# return value : array of jobs of a given array_job
# side effects : / 
sub get_array_subjobs($$){
    my $dbh = shift;
    my $array_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM jobs
                                WHERE
                                    array_id = $array_id
                                ORDER BY job_id
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    
    return(@res);
}



# get_array_job_ids($$)
# Get all the job_ids of a given array_job
# parameters : base, array_id
# return value : array of jobids of a given array_job
# side effects : / 
sub get_array_job_ids($$){
    my $dbh = shift;
    my $array_id = shift;

    my $sth = $dbh->prepare("   SELECT job_id
                                FROM jobs
                                WHERE
                                    array_id = $array_id
                                ORDER BY job_id
                            ");
    $sth->execute();

    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        my @tmp_array = values(%$ref);
        push(@res,  $tmp_array[0]);
    }

    $sth->finish();
    return(@res);
}


# PROCESSJOBS MANAGEMENT (Host assignment to jobs)

# get_resource_job
# returns the list of jobs associated to the resource passed in parameter
# parameters : base, resource
# return value : list of jobid
# side effects : /
sub get_resource_job($$) {
    my $dbh = shift;
    my $resource = shift;
    my $sth = $dbh->prepare("   SELECT jobs.job_id
                                FROM assigned_resources, moldable_job_descriptions, jobs
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND assigned_resources.resource_id = $resource
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND (jobs.state = \'Waiting\'
                                           OR jobs.state = \'Hold\'
                                           OR jobs.state = \'toLaunch\'
                                           OR jobs.state = \'toAckReservation\'
                                           OR jobs.state = \'Launching\'
                                           OR jobs.state = \'Running\'
                                           OR jobs.state = \'Suspended\'
                                           OR jobs.state = \'Resuming\'
                                           OR jobs.state = \'Finishing\')
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{'job_id'});
    }
    return @res;
}

# get_resource_job_with_state
# returns the list of jobs associated to the resource passed in parameter
# parameters : base, resource
# return value : list of jobid
# side effects : /
sub get_resource_job_with_state($$$) {
    my $dbh = shift;
    my $resource = shift;
    my $state = shift;
    my $sth = $dbh->prepare("   SELECT jobs.job_id
                                FROM assigned_resources, moldable_job_descriptions, jobs
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND assigned_resources.resource_id = $resource
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND jobs.state = \'$state\'
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{'job_id'});
    }
    return @res;
}

# get_resources_jobs
# returns the list of jobs associated to all resources
# parameters : base
# return value : hash of resource_id->array of job_id
# side effects : /
sub get_resources_jobs($) {
  my $dbh = shift;
  my $sth = $dbh->prepare("   SELECT jobs.job_id,assigned_resources.resource_id
                                FROM assigned_resources, moldable_job_descriptions, jobs
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND (jobs.state = \'Waiting\'
                                           OR jobs.state = \'Hold\'
                                           OR jobs.state = \'toLaunch\'
                                           OR jobs.state = \'toAckReservation\'
                                           OR jobs.state = \'Launching\'
                                           OR jobs.state = \'Running\'
                                           OR jobs.state = \'Suspended\'
                                           OR jobs.state = \'Resuming\'
                                           OR jobs.state = \'Finishing\');
                            ");
  $sth->execute();
  my %res;
  while (my @ref = $sth->fetchrow_array()) {
        push(@{$res{$ref[1]}}, $ref[0]);
  }
  return(\%res);
}

# get_resource_job_to_frag
# same as get_resource_job but excepts the cosystem jobs
# parameters : base, resource
# return value : list of jobid
# side effects : /
sub get_resource_job_to_frag($$) {
    my $dbh = shift;
    my $resource = shift;
    my $sth = $dbh->prepare("   SELECT jobs.job_id
                                FROM assigned_resources, moldable_job_descriptions, jobs
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND assigned_resources.resource_id = $resource
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND jobs.state != \'Terminated\'
                                    AND jobs.state != \'Error\'
                                    AND jobs.job_id NOT IN (
                                                             SELECT job_id from job_types
                                                             WHERE
                                                                 type=\'cosystem\'
                                                                 AND types_index=\'CURRENT\'
                                                           )
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{'job_id'});
    }
    return @res;
}

# get_node_job
# returns the list of jobs associated to the hostname passed in parameter
# parameters : base, hostname
# return value : list of jobid
# side effects : /
sub get_node_job($$) {
    my $dbh = shift;
    my $hostname = shift;
    my $sth = $dbh->prepare("   SELECT jobs.job_id
                                FROM assigned_resources, moldable_job_descriptions, jobs, resources
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND resources.network_address = \'$hostname\'
                                    AND assigned_resources.resource_id = resources.resource_id
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND jobs.state != \'Terminated\'
                                    AND jobs.state != \'Error\'
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{'job_id'});
    }
    return @res;
}

# get_alive_nodes_with_jobs
# returns the list of occupied nodes
# parameters : base
# return value : list of node names
# side effects : /
sub get_alive_nodes_with_jobs($) {
    my $dbh = shift;
    my $sth;
    if ($Db_type eq "Pg"){
        $sth = $dbh->prepare("   SELECT resources.network_address
                                 FROM assigned_resources, moldable_job_descriptions, jobs, resources
                                 WHERE
                                    assigned_resources.resource_id = resources.resource_id
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND jobs.state IN (\'Waiting\',\'Hold\',\'toLaunch\',\'toError\',\'toAckReservation\',\'Launching\',\'Running\',\'Suspended\',\'Resuming\')
                                    AND (resources.state = 'Alive' or resources.next_state='Alive')
                            ");
    }else{
        $sth = $dbh->prepare("   SELECT resources.network_address
                                 FROM assigned_resources, moldable_job_descriptions, jobs, resources
                                 WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND (resources.state = 'Alive' or resources.next_state='Alive')
                                    AND assigned_resources.resource_id = resources.resource_id
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND jobs.state IN (\'Waiting\',\'Hold\',\'toLaunch\',\'toError\',\'toAckReservation\',\'Launching\',\'Running\',\'Suspended\',\'Resuming\')
                            ");
    }

    $sth->execute();
    my @res = ();
    while (my @ary = $sth->fetchrow_array) {
        push(@res, $ary[0]);
    }
    return @res;
    $sth->finish();
}


# get_resources_by_property
# returns the list of resources grouped by a given property
# parameters : base
# return value : hash of property_value->array of resource_id
# side effects : /
sub get_resources_by_property($$) {
  my $dbh = shift;
  my $property = shift;
  my $sth = $dbh->prepare("  select resource_id,$property from resources order by $property;");
  $sth->execute();
  my %res = ();
  while (my @ref = $sth->fetchrow_array()) {
        push(@{$res{$ref[1]}}, $ref[0]);
  }
  return(\%res);
}


# get_node_job_to_frag
# same as get_node_job but excepts cosystem jobs
# parameters : base, hostname
# return value : list of jobid
# side effects : /
sub get_node_job_to_frag($$) {
    my $dbh = shift;
    my $hostname = shift;
    my $sth = $dbh->prepare("   SELECT jobs.job_id
                                FROM assigned_resources, moldable_job_descriptions, jobs, resources
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND moldable_job_descriptions.moldable_index = \'CURRENT\'
                                    AND resources.network_address = \'$hostname\'
                                    AND assigned_resources.resource_id = resources.resource_id
                                    AND assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND moldable_job_descriptions.moldable_job_id = jobs.job_id
                                    AND jobs.state != \'Terminated\'
                                    AND jobs.state != \'Error\'
                                    AND jobs.job_id NOT IN (
                                                             SELECT job_id from job_types
                                                             WHERE
                                                                 type=\'cosystem\'
                                                                 AND types_index=\'CURRENT\'
                                                           )
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{'job_id'});
    }
    return @res;
}

# get_resources_in_state
# returns the list of resources in the state specified
# parameters : base, state
# return value : list of resource ref
sub get_resources_in_state($$) {
    my $dbh = shift;
    my $state = shift;
    
    my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                                WHERE
                                    state = \'$state\'
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return @res;
}

# get_resource_ids_in_state
# returns the resource ids in the specified state
# parameters : base, state
sub get_resource_ids_in_state($$) {
    my $dbh = shift;
    my $state = shift;
    
    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM resources
                                WHERE
                                    state = \'$state\'
                            ");
    $sth->execute();
    my @res = ();
    my $vec = '';
    while (my @r = $sth->fetchrow_array) {
        push(@res, $r[0]);
        vec($vec, $r[0], 1) = 1;
    }
    $sth->finish();
    return($vec, @res);
}

# get_finaud_nodes
# returns the list of nodes for finaud
# parameters : base
# return value : list of nodes
sub get_finaud_nodes($) {
    my $dbh = shift;
    my $sth = "";
    if ($Db_type eq "Pg"){
      $sth = $dbh->prepare("   SELECT DISTINCT(network_address), *
                                  FROM resources
                                  WHERE
                                    (state = \'Alive\' OR
                                    (state = \'Suspected\' AND finaud_decision = \'YES\')) AND
                                    type = \'default\' AND
                                    desktop_computing = \'NO\' AND
                                    next_state = \'UnChanged\'
                              ");
    }
    else{
      my @result;
      my $presth = $dbh->prepare("DESC resources"); 
      $presth->execute();
      while (my $ref = $presth->fetchrow_hashref()){
        my $current_value = $ref->{'Field'};
        push(@result, $current_value);
      }
    
      $presth->finish();
    
      my $str = "SELECT DISTINCT(network_address)";
      foreach(@result){
        $str = $str.", ".$_;
      }
      $str = $str." FROM resources
                    WHERE
                      (state = \'Alive\' OR
                      (state = \'Suspected\' AND finaud_decision = \'YES\')) AND
                      type = \'default\' AND
                      desktop_computing = \'NO\' AND
                      next_state = \'UnChanged\'";
      $sth = $dbh->prepare($str);
    }
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return @res;
}


# get_resources_that_can_be_waked_up
# returns a list of resources
# parameters : base, date max
# return value : vec of resource_id
sub get_resources_that_can_be_waked_up($$) {
    my $dbh = shift;
    my $max_date = shift;
    
    $max_date = $max_date + $Cm_security_duration;
    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM resources
                                WHERE
                                    state = \'Absent\' AND
                                    resources.available_upto > $max_date
                            ");
    $sth->execute();
    my $vec = '';
    while (my @r = $sth->fetchrow_array) {
        vec($vec, $r[0], 1) = 1;
    }
    $sth->finish();
    return($vec);
}

# get_nodes_that_can_be_waked_up
# returns a list of resources
# parameters : base, date max
# return value : list of node names
sub get_nodes_that_can_be_waked_up($$) {
    my $dbh = shift;
    my $max_date = shift;
    
    $max_date = $max_date + $Cm_security_duration;
    my $sth = $dbh->prepare("   SELECT distinct(network_address)
                                FROM resources
                                WHERE
                                    state = \'Absent\' AND
                                    resources.available_upto > $max_date
                            ");
    $sth->execute();
    my @res = ();
    while (my @ary = $sth->fetchrow_array) {
        push(@res, $ary[0]);
    }
    return @res;
}


# get_resources_that_will_be_out
# returns a list of resources
# parameters : base, job max date
# return value : vec of resource_id
sub get_resources_that_will_be_out($$) {
    my $dbh = shift;
    my $max_date = shift;
    
    $max_date = $max_date + $Cm_security_duration;
    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM resources
                                WHERE
                                    state = \'Alive\' AND
                                    resources.available_upto < $max_date
                            ");
    $sth->execute();
    my $vec = '';
    while (my @r = $sth->fetchrow_array) {
        vec($vec, $r[0], 1) = 1;
    }
    $sth->finish();
    return($vec);
}

# get_energy_saving_resources_availability
# returns a list of resources and when they will be available
# parameters : base, min_start_date
# return value : end_date_availability => [resource id list]
sub get_energy_saving_resources_availability($$) {
    my $dbh = shift;
    my $current_time = shift;
    
    my $sth = $dbh->prepare("   SELECT resource_id, available_upto
                                FROM resources
                                WHERE
                                    (state = \'Absent\' AND
                                     available_upto > $current_time)
                                    OR
                                    (state = \'Alive\' AND
                                     available_upto < 2147483646 AND
                                     available_upto > 0)
                            ");
    $sth->execute();
    my %res = ();
    while (my @ref = $sth->fetchrow_array()) {
        push(@{$res{$ref[1]}}, $ref[0]);
    }
    return(\%res);
}

# add_resource_job_pair
# adds a new pair (jobid, resource) to the table assigned_resources
# parameters : base, jobid, resource id
# return value : /

#TODO: consider the use  of multiple values insertion within one request : INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
sub add_resource_job_pair($$$) {
    my $dbh = shift;
    my $moldable = shift;
    my $resource = shift;

    $dbh->do("INSERT INTO assigned_resources (moldable_job_id,resource_id,assigned_resource_index)
              VALUES ($moldable,$resource,\'CURRENT\')");
}

# add_resource_job_pairs
# adds new pairs (jobid, resource) to the table assigned_resources
# parameters : base, jobid, resource id array
# return value : /
sub add_resource_job_pairs($$$) {
    my $dbh = shift;
    my $moldable = shift;
    my $resources = shift;

    my $query = "INSERT INTO assigned_resources (moldable_job_id,resource_id,assigned_resource_index) VALUES ";

    foreach my $r (@{$resources}){
      $query .= "($moldable,$r,\'CURRENT\'),";
    }
    #oar_debug("[OAR::IO] add_resource_job_pairs $query\n");
    chop($query);
    $dbh->do($query);
}

# add_resource_job_pairs_from_file
# adds new pairs (jobid, resource) to the table assigned_resources
# use insert from file to obtain better performance
# parameters : base, jobid, resource id array
# return value : /
sub add_resource_job_pairs_from_file($$$) {
  my $dbh = shift;
  my $moldable = shift;
  my $resources = shift;
  my $values = "";

  foreach my $r (@{$resources}){
    $values .= "$moldable,$r,CURRENT\n";
  }
  inserts_from_file($dbh,'assigned_resources',$values);
}

# parse jobs retrieved by the 2 functions:
# - get_jobs_past_and_current_from_range
# - get_jobs_future_from_range
# args : db query result handle
sub parse_jobs_from_range($) {
    my $sth = shift;
    my $jobs = {};
    while (my @ref = $sth->fetchrow_array()) {
        if (! exists($jobs->{$ref[0]})) {
            $jobs->{$ref[0]} = {
                'job_id' => $ref[0],
                'job_name' => $ref[1],
                'project' => $ref[2],
                'job_type' => $ref[3],
                'state' => $ref[4],
                'user' => $ref[5],
                'command' => $ref[6],
                'queue_name' => $ref[7],
                'walltime' => $ref[8],
                'properties' => $ref[9],
                'launching_directory' => $ref[10],
                'submission_time' => $ref[11],
                'start_time' => $ref[12],
                'stop_time' => $ref[13],
                'resource_id' => [],
                'network_address' => [],
            }
        }
        push(@{$jobs->{$ref[0]}->{'resource_id'}}, $ref[14]);
        if (defined($ref[15])){
            push(@{$jobs->{$ref[0]}->{'network_address'}}, $ref[15]);
        }
        if (defined($ref[16])){
            push(@{$jobs->{$ref[0]}->{'types'}}, $ref[16]);
        }
    }
    return $jobs;
}

# get past and current jobs in a range of dates
# args : base, start range, end range
sub get_jobs_past_and_current_from_range($$$){
    my $dbh = shift;
    my $date_start = shift;
    my $date_end = shift;
    my $query_filter = shift;

    my $req =  <<EOT;
SELECT
    jobs.job_id,
    jobs.job_name,
    jobs.project,
    jobs.job_type,
    jobs.state,
    jobs.job_user,
    jobs.command,
    jobs.queue_name,
    moldable_job_descriptions.moldable_walltime,
    jobs.properties,
    jobs.launching_directory,
    jobs.submission_time,
    jobs.start_time,
    jobs.stop_time,
    assigned_resources.resource_id,
    resources.network_address,
    job_types.type
FROM
    (jobs LEFT JOIN job_types ON (job_types.job_id = jobs.job_id)),
    assigned_resources,
    moldable_job_descriptions,
    resources
WHERE
    (   
        jobs.stop_time >= $date_start OR
        (   
            jobs.stop_time = \'0\' AND
            (jobs.state = \'Running\' OR
             jobs.state = \'Suspended\' OR
             jobs.state = \'Resuming\')
        )
    ) AND
    jobs.start_time < $date_end AND
    jobs.assigned_moldable_job = assigned_resources.moldable_job_id AND
    moldable_job_descriptions.moldable_job_id = jobs.job_id AND
    resources.resource_id = assigned_resources.resource_id
ORDER BY
    jobs.job_id
EOT
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my $jobs = parse_jobs_from_range($sth);
    $sth->finish();

    return $jobs
}


# get future (scheduled) jobs in a range of dates
# args : base, start range, end range
sub get_jobs_future_from_range($$$){
    my $dbh = shift;
    my $date_start = shift;
    my $date_end = shift;
    my $query_filter = shift;

    my $req = <<EOT;
SELECT
    jobs.job_id,
    jobs.job_name,
    jobs.project,
    jobs.job_type,
    jobs.state,
    jobs.job_user,
    jobs.command,
    jobs.queue_name,
    moldable_job_descriptions.moldable_walltime,
    jobs.properties,
    jobs.launching_directory,
    jobs.submission_time,
    gantt_jobs_predictions_visu.start_time,
    (gantt_jobs_predictions_visu.start_time + moldable_job_descriptions.moldable_walltime),
    gantt_jobs_resources_visu.resource_id,
    resources.network_address,
    job_types.type
FROM
    (jobs LEFT JOIN job_types ON (job_types.job_id = jobs.job_id)),
    moldable_job_descriptions,
    gantt_jobs_resources_visu,
    gantt_jobs_predictions_visu,
    resources
WHERE
    gantt_jobs_predictions_visu.moldable_job_id = gantt_jobs_resources_visu.moldable_job_id AND
    gantt_jobs_predictions_visu.moldable_job_id = moldable_job_descriptions.moldable_id AND
    jobs.job_id = moldable_job_descriptions.moldable_job_id AND
    gantt_jobs_predictions_visu.start_time < $date_end AND
    resources.resource_id = gantt_jobs_resources_visu.resource_id AND
    gantt_jobs_predictions_visu.start_time + moldable_job_descriptions.moldable_walltime >= $date_start AND
    jobs.job_id NOT IN ( SELECT job_id FROM job_types WHERE type = 'besteffort' AND types_index = 'CURRENT' )
ORDER BY
    jobs.job_id
EOT
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my $jobs = parse_jobs_from_range($sth);
    $sth->finish();

    return $jobs
}


# get all distinct jobs for a user query
# args : base, start range, end range, jobs states, limit, offset, user
sub get_jobs_for_user_query {
    my $dbh = shift;
    my $date_start = shift || "";
    my $date_end = shift || "";
    my $state = shift || "";
    my $limit = shift || "";
    my $offset = shift;
    my $user = shift || "";
    my $array_id = shift || "";
    my $ids = shift || [];
    my $first_query_date_start = "";
    my $second_query_date_start = "";
    my $third_query_date_start = "";
    my $first_query_date_end = "";
    my $second_query_date_end = "";
    my $third_query_date_end = "";
    my $id_filter = "";

    if ($date_start ne "") {
    	$first_query_date_start = "(
                 			jobs.stop_time >= $date_start OR
                 			(   
                     			jobs.stop_time = \'0\' AND
                     			( (jobs.state = \'Running\' AND 
                                          jobs.start_time + moldable_job_descriptions.moldable_walltime >= $date_start ) OR
                  			jobs.state = \'Suspended\' OR
                      			jobs.state = \'Resuming\')
                 			)
             			) AND";
    	$second_query_date_start = " AND gantt_jobs_predictions_visu.start_time + moldable_job_descriptions.moldable_walltime >= $date_start ";
    	$third_query_date_start = " AND $date_start <= jobs.submission_time";
    }
    if ($date_end ne "") {
    	$first_query_date_end = "jobs.start_time < $date_end AND";
    	$second_query_date_end = " AND gantt_jobs_predictions_visu.start_time < $date_end ";
    	$third_query_date_end = " AND jobs.submission_time <= $date_end";
    }
    if ($state ne "") { $state = " AND jobs.state IN (".$state.") ";}
    if ($limit ne "") { $limit = "LIMIT $limit"; }
    if (defined($offset)) { $offset = "OFFSET $offset"; }
    if ($user ne "") { $user = " AND jobs.job_user = ".$dbh->quote($user); }
    if ($array_id ne "") { $array_id = " AND jobs.array_id = ".$dbh->quote($array_id); }
    if (@{$ids} > 0) {
      $id_filter = " AND jobs.job_id in (".join(',',@{$ids}).")";
    }
    my $req =
        "
        SELECT jobs.job_id,jobs.job_name,jobs.state,jobs.job_user,jobs.queue_name,jobs.submission_time, jobs.assigned_moldable_job,jobs.reservation,jobs.project,jobs.properties,jobs.exit_code,jobs.command,jobs.initial_request,jobs.launching_directory,jobs.message,jobs.job_type,jobs.array_id,jobs.stderr_file,jobs.stdout_file,jobs.start_time,moldable_job_descriptions.moldable_walltime,jobs.stop_time
        FROM jobs LEFT JOIN moldable_job_descriptions ON jobs.assigned_moldable_job = moldable_job_descriptions.moldable_id
        INNER JOIN
              (
         						 SELECT DISTINCT jobs.job_id AS job_id
         						 FROM jobs, assigned_resources, moldable_job_descriptions
         						 WHERE
                 					$first_query_date_start
             						$first_query_date_end
             						jobs.assigned_moldable_job = assigned_resources.moldable_job_id AND
             						moldable_job_descriptions.moldable_job_id = jobs.job_id
             						$state $user $array_id $id_filter

         						UNION

         						SELECT DISTINCT jobs.job_id AS job_id
         						FROM jobs, moldable_job_descriptions, gantt_jobs_resources_visu, gantt_jobs_predictions_visu
         						WHERE
         						   gantt_jobs_predictions_visu.moldable_job_id = gantt_jobs_resources_visu.moldable_job_id AND
         						   gantt_jobs_predictions_visu.moldable_job_id = moldable_job_descriptions.moldable_id AND
         						   jobs.job_id = moldable_job_descriptions.moldable_job_id
         						   $second_query_date_start
         						   $second_query_date_end
         						   $state $user $array_id $id_filter
         						
         						UNION
         						
         						SELECT DISTINCT jobs.job_id AS job_id
         						FROM jobs
         						WHERE 
         						   jobs.start_time = \'0\'
         						   $third_query_date_start
         						   $third_query_date_end
         						   $state $user $array_id $id_filter
         						) unionsql ON unionsql.job_id = jobs.job_id
         ORDER BY jobs.job_id $limit $offset";

    my $sth = $dbh->prepare($req);
    $sth->execute();

    my %results;
    while (my @ref = $sth->fetchrow_array()) {
         $results{$ref[0]} = {
            	            'job_name' => $ref[1],
                            'state' => $ref[2],
                            'job_user' => $ref[3],
                            'queue_name' => $ref[4],
                            'submission_time' => $ref[5],
                            'assigned_moldable_job' => $ref[6],
                            'reservation' => $ref[7],
                            'project' => $ref[8],
                            'properties' => $ref[9],
                            'exit_code' => $ref[10],
                            'command' => $ref[11],
                            'initial_request' => $ref[12],
                            'launching_directory' => $ref[13],
                            'message' => $ref[14],
                            'job_type' => $ref[15],
                            'array_id' => $ref[16],
                            'stdout_file' => $ref[18],
                            'stderr_file' => $ref[17],
                            'start_time' => $ref[19],
                            'walltime' => $ref[20],
                            'stop_time' => $ref[21]
                              };
    }
    $sth->finish();

    return %results;
}


# count all distinct jobs for a user query
# args : base, start range, end range, jobs states, limit, offset, user
sub count_jobs_for_user_query {
	my $dbh = shift;
    my $date_start = shift || "";
    my $date_end = shift || "";
    my $state = shift || "";
    my $limit = shift || "";
    my $offset = shift;
    my $user = shift || "";
    my $array_id = shift || "";
    my $ids = shift || [];
    my $first_query_date_start = "";
    my $second_query_date_start = "";
    my $third_query_date_start = "";
    my $first_query_date_end = "";
    my $second_query_date_end = "";
    my $third_query_date_end = "";
    my $id_filter = "";

    if ($date_start ne "") {
    	$first_query_date_start = "(   
                 						jobs.stop_time >= $date_start OR
                 						(   
                     						jobs.stop_time = \'0\' AND
                     						(jobs.state = \'Running\' OR
                      						jobs.state = \'Suspended\' OR
                      						jobs.state = \'Resuming\')
                 						)
             						) AND";
    	$second_query_date_start = " AND gantt_jobs_predictions_visu.start_time + moldable_job_descriptions.moldable_walltime >= $date_start ";
    	$third_query_date_start = " AND $date_start <= jobs.submission_time";
    }
    if ($date_end ne "") {
    	$first_query_date_end = "jobs.start_time < $date_end AND";
    	$second_query_date_end = " AND gantt_jobs_predictions_visu.start_time < $date_end ";
    	$third_query_date_end = " AND jobs.submission_time <= $date_end";
    }
    if ($state ne "") { $state = " AND jobs.state IN (".$state.") ";}
    if ($limit ne "") { $limit = "LIMIT $limit"; }
    if (defined($offset)) { $offset = "OFFSET $offset"; }
    if ($user ne "") { $user = " AND jobs.job_user = ".$dbh->quote($user); }
    if ("$array_id" ne "") { $array_id = " AND jobs.array_id = ".$dbh->quote($array_id); }
    if (@{$ids} > 0) {
      $id_filter = " AND jobs.job_id in (".join(',',@{$ids}).")";
    }

    my $req =
        "
        SELECT COUNT(*)
        FROM (
         						 SELECT DISTINCT jobs.job_id
         						 FROM jobs, assigned_resources, moldable_job_descriptions
         						 WHERE
                 					$first_query_date_start
             						$first_query_date_end
             						jobs.assigned_moldable_job = assigned_resources.moldable_job_id AND
             						moldable_job_descriptions.moldable_job_id = jobs.job_id
             						$state $user $array_id $id_filter

         						UNION

         						SELECT DISTINCT jobs.job_id
         						FROM jobs, moldable_job_descriptions, gantt_jobs_resources_visu, gantt_jobs_predictions_visu
         						WHERE
         						   gantt_jobs_predictions_visu.moldable_job_id = gantt_jobs_resources_visu.moldable_job_id AND
         						   gantt_jobs_predictions_visu.moldable_job_id = moldable_job_descriptions.moldable_id AND
         						   jobs.job_id = moldable_job_descriptions.moldable_job_id
         						   $second_query_date_start
         						   $second_query_date_end
         						   $state $user $array_id $id_filter

         						UNION

         						SELECT DISTINCT jobs.job_id
         						FROM jobs
         						WHERE
         						   jobs.start_time = \'0\'
         						   $third_query_date_start
         						   $third_query_date_end
         						   $state $user $array_id $id_filter
         						) AS unionsql
             ";

    my $sth = $dbh->prepare($req);
    $sth->execute();

    my ($count) = $sth->fetchrow_array();
    return $count ;
}

# get scheduling informations about Interactive jobs in Waiting state
# args : base
sub get_gantt_waiting_interactive_prediction_date($){
    my $dbh = shift;

    my $req =
        "SELECT jobs.job_id, jobs.info_type, gantt_jobs_predictions_visu.start_time, jobs.message
         FROM jobs, moldable_job_descriptions, gantt_jobs_predictions_visu
         WHERE
             jobs.state = \'Waiting\' AND
             jobs.job_type = \'INTERACTIVE\' AND
             jobs.reservation = \'None\' AND
             moldable_job_descriptions.moldable_index = \'CURRENT\' AND
             moldable_job_descriptions.moldable_job_id = jobs.job_id AND
             gantt_jobs_predictions_visu.moldable_job_id = moldable_job_descriptions.moldable_id
        ";
    if ($Db_type eq "Pg"){
        $req = "SELECT jobs.job_id, jobs.info_type, gantt_jobs_predictions_visu.start_time, jobs.message
                FROM jobs, moldable_job_descriptions, gantt_jobs_predictions_visu
                WHERE
                    jobs.state = \'Waiting\' AND
                    jobs.job_type = \'INTERACTIVE\' AND
                    jobs.reservation = \'None\' AND
                    moldable_job_descriptions.moldable_job_id = jobs.job_id AND
                    gantt_jobs_predictions_visu.moldable_job_id = moldable_job_descriptions.moldable_id";
    }
    
    my $sth = $dbh->prepare($req);
    $sth->execute();

    my @results;
    while (my @ref = $sth->fetchrow_array()) {
        my $tmp = {
                    'job_id' => $ref[0],
                    'info_type' => $ref[1],
                    'start_time' => $ref[2],
                    'message' => $ref[3],
                  };
        push(@results, $tmp);
    }
    $sth->finish();

    return(@results);
}


# get_desktop_computing_host_jobs($$);
# get the list of jobs and attributs affected to a desktop computing node
# parameters: base, nodename
# return value: jobs hash
# side effects: none
sub get_desktop_computing_host_jobs($$) {
    my $dbh = shift;
    my $hostname = shift;

    my $sth = $dbh->prepare("   SELECT jobs.job_id, jobs.state, jobs.command, jobs.launching_directory, jobs.stdout_file, jobs.stderr_file
                                FROM jobs, assigned_resources, resources
                                WHERE
                                    resources.network_address = \'$hostname\' AND
                                    resources.desktop_computing = \'YES\' AND
                                    resources.resource_id = assigned_resources.resource_id AND
                                    jobs.assigned_moldable_job = assigned_resources.moldable_job_id AND
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                            ");
    $sth->execute;
    my $results;
    while (my @array = $sth->fetchrow_array()) {
        $results->{$array[0]} = {
                                    state => $array[1],
                                    command => $array[2],
                                    directory => $array[3],
                                    stdout_file => OAR::Tools::replace_jobid_tag_in_string($array[4],$array[0]),
                                    stderr_file => OAR::Tools::replace_jobid_tag_in_string($array[5],$array[0])
                                };
    }
    return($results);
}

# get_stagein_id($$);
# retrieve stagein idFile form its md5sum
# parameters: base, md5sum
# return value: idFile or undef if md5sum is not found
# side effects: none
sub get_stagein_id($$) {
    my $dbh = shift;
    my $md5sum = shift;

    my $sth = $dbh->prepare("   SELECT file_id
                                FROM files
                                WHERE
                                    md5sum = \'$md5sum\'
                            ");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    $sth->finish();
    return($ref->{file_id});
}

# set_stagein($$$$$$);
# set a stagein information
# parameters: base, md5sum, location, method, compression, size
# return value: the idFile of the new stagein.
# side effects: none
sub set_stagein($$$$$$) {
    my $dbh = shift;
    my $md5sum = shift;
    my $location = shift;
    my $method = shift;
    my $compression = shift;
    my $size = shift;
    my $idFile;
    lock_table($dbh, ["files"]);
    $dbh->do("INSERT INTO files (md5sum,location,method,compression,size)
              VALUES (\'$md5sum\',\'$location\',\'$method\',\'$compression\',$size)");
    $idFile = get_last_insert_id($dbh,"files_file_id_seq");
    unlock_table($dbh);
    return $idFile;
}

# del_stagein($$);
# remove a stagein from database
# parameters: base, md5sum
# return value: none
# side effects: none
sub del_stagein($$) {
    my $dbh = shift;
    my $md5sum = shift;
    
    lock_table($dbh, ["files"]);
    $dbh->do("DELETE FROM files WHERE md5sum = \'$md5sum\'");
    unlock_table($dbh);
}

# is_stagein_deprecated($$$);
# check if a stagein file is to old to be kept in cache
# parameters: base, md5sum, expiry
# return value: boolean, true if deprecated
# side effects: none
sub is_stagein_deprecated($$$) {
    my $dbh = shift;
    my $md5sum = shift;
    my $expiry_delay = shift;
   
    my $date = get_date($dbh);
    my $sth = $dbh->prepare("   SELECT jobs.start_time
                                FROM jobs, files
                                WHERE
                                    jobs.file_id = files.file_id AND
                                    files.md5sum = \'$md5sum\'
                            ");
    $sth->execute();
    my $result = 1;
    while (my @res = $sth->fetchrow_array()){
        if (($res[0] + $expiry_delay) > $date){
            $result = 0;
            return(0);
        }
    }
    return ($result);
}

# get_job_stagein($$);
# get a job stagein information: pathname and md5sum
# parameters: base, jobid
# return value: a hash with 2 keys: pathname and md5sum
# side effects: none
sub get_job_stagein($$) {
    my $dbh = shift;
    my $job_id = shift;
    my $sth = $dbh->prepare("   SELECT files.md5sum,files.location,files.method,files.compression,files.size
                                FROM jobs, files
                                WHERE	
                                    jobs.job_id = $job_id AND
                                    jobs.file_id = files.file_id
                            ");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    $sth->finish();
    return($ref);
}

# ADMISSION RULES MANAGEMENT

# add_admission_rule
# adds a new rule in the table admission_rule
# parameters : base, priority, enabled, rule
# return value : new admission rule id
sub add_admission_rule($$$$) {
    my $dbh = shift;
    my $priority = shift;
    my $enabled = shift;
    my $rule = $dbh->quote(shift);
     
    $dbh->do("  INSERT INTO admission_rules (priority, enabled, rule)
                VALUES ($priority, ".($enabled?"'YES'":"'NO'").", $rule)
             ");
    my $id = get_last_insert_id($dbh,"admission_rules_id_seq");

    return($id);
}

# list_admission_rules
# get the list of all admission rules
# parameters : base
# return value : list of admission rules
# side effects : /
sub list_admission_rules($$) {
	my $dbh = shift;
    my $enabled = shift;
	
    my $where = "";
    if (defined($enabled)) {
        $where = ($enabled)?"WHERE enabled = 'YES'":"WHERE enabled = 'NO'";
    }
        
	my $sth = $dbh->prepare("   SELECT *
                                FROM admission_rules $where
                                ORDER BY priority, id
                           ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return @res;
}

# get_requested_admission_rules
# get requested admission rules
# parameters : base limit offset
# side effects : /
sub get_requested_admission_rules($$$) {
	my $dbh = shift;
	my $limit = shift;
	my $offset= shift;
	
	my $sth = $dbh->prepare("   SELECT *
                                FROM admission_rules
                                ORDER BY id LIMIT $limit OFFSET $offset
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}

# count_all_admission_rules
# count all admissions rules
# parameters : base
# side effects : /
sub count_all_admission_rules($) {
	my $dbh = shift;
	
	my $sth = $dbh->prepare("	SELECT COUNT(*)
	                            FROM admission_rules
	                        ");
    $sth->execute();
    
    my ($count) = $sth->fetchrow_array();
    return $count ;
}

# get_admission_rule
# returns a ref to some hash containing data for the admission rule of id passed in
# parameter
# parameters : base, admission_rule_id
# return value : ref
# side effects : /
sub get_admission_rule($$) {
    my $dbh = shift;
    my $rule_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM admission_rules
                                WHERE
                                    id = $rule_id
                            ");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return($ref);
}

# delete_admission_rule
# parameter
# parameters : base, admission_rule_id
# return value : id of the deleted admission rule if ok, undef else
sub delete_admission_rule($$) {
    my $dbh = shift;
    my $id = shift;

    my $sth = $dbh->prepare("       SELECT COUNT(*)
                                    FROM admission_rules where id=$id
                                ");
    $sth->execute();
    if($sth->fetchrow_array() > 0) {
      my $sth2 = $dbh->prepare("   DELETE
                                FROM admission_rules
                                WHERE
                                    id = $id
                            ");
      $sth2->execute();
      return $id;
    }else{
      return undef;
    }
}

# update_admission_rule
# updates an existing rule in the table admission_rule
# parameters : base, rule id, priority, enabled, rule
# return value : id of the updated admission rule if ok, undef else
sub update_admission_rule($$$$$) {
    my $dbh = shift;
    my $id = shift;
    my $priority = shift;
    my $enabled = shift;
    my $rule = $dbh->quote(shift);

    my $sth = $dbh->prepare("       SELECT COUNT(*)
                                    FROM admission_rules where id=$id
                                ");
    $sth->execute();
    if($sth->fetchrow_array() > 0) {
      $dbh->do("  UPDATE admission_rules
                SET priority= $priority, enabled = ".($enabled?"'YES'":"'NO'").", rule = $rule
                WHERE id=$id
               ");
      return($id);
    }else{
      return undef;
    }
}

# NODES MANAGEMENT

# add_resource
# adds a new resource in the table resources and resource_properties
# parameters : base, name, state
# return value : new resource id
sub add_resource($$$) {
    my $dbh = shift;
    my $name = shift;
    my $state = shift;

    #lock_table($dbh,["resources"]);
    $dbh->do("  INSERT INTO resources (network_address,state,state_num)
                VALUES (\'$name\',\'$state\',$State_to_num{$state})
             ");
    my $id = get_last_insert_id($dbh,"resources_resource_id_seq");
    #unlock_table($dbh);
    my $date = get_date($dbh);
    $dbh->do("  INSERT INTO resource_logs (resource_id,attribute,value,date_start)
                VALUES ($id,\'state\',\'$state\',\'$date\')
             ");
    return $id;
}

# get_last_resource_id
# get the last resource id
sub get_last_resource_id($) {
    my $dbh = shift;
    my $sth = $dbh->prepare("SELECT MAX(resource_id) from resources");
    $sth->execute();
    my @arr = $sth->fetchrow_array();
    $sth->finish();
    return $arr[0];
} 

# add_resources
# adds an array of resources in the table resources in block
# parameters : base, name, resources
# return value : array of newly created resources ids
sub add_resources($$) {
    my $dbh = shift;
    my $resources = shift;

    lock_table($dbh,["resources","resource_logs"]);

    # Getting the last id as we are not using auto_increment
    my $id=get_last_resource_id($dbh);    
    my @ids;

    # Construct the properties list
    my @properties;
    foreach my $r (@$resources) {
      foreach my $prop (keys(%$r)) {
        if(!grep(/^$prop$/,@properties)) {
          push(@properties,$prop);
        }
      }  
    }

    # Construct the queries
    my $query="INSERT INTO resources (resource_id,state,state_num,".join(",",@properties).") VALUES ";
    my $log_query="INSERT INTO resource_logs (resource_id,attribute,value,date_start) VALUES ";
    my $date = get_date($dbh);
    my $first=1;
    my @values;
    my @log_values;
    foreach my $r (@$resources) {
      if ($first) { $query.="("; }
      else        { $query.=",(";}
      @values=();
      $id++;
      push(@values,$id);
      push(@log_values,"($id,\'state\',\'Alive\',\'$date\')");
      push(@values,"\'Alive\'");
      push(@values,$State_to_num{"Alive"});
      push(@ids,$id);
      foreach my $p (@properties) {
        if (defined($r->{$p})) { 
          push(@values,"\'".$r->{$p}."\'");
          push(@log_values,"($id,\'$p\',\'$r->{$p}\',\'$date\')");
        }
        else { push(@values,"NULL");   }  
      }
      $query.=join(",",@values);
      $query.=")";
      $first=0;
    }
    $log_query.=join(",",@log_values);

    # Execute the query
    $dbh->do($query);
    if ($DBI::err) {
      @ids=["Error: ". $DBI::errstr ."Query: " .$query];
    }else{
      $dbh->do($log_query);
    }
    unlock_table($dbh);
    return(@ids);
}


# get_alive_resources
# gets the list of resources in the Alive state.
# parameters : base
# return value : list of resource refs
# side effects : /
sub get_alive_resources($) {
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                                WHERE
                                    state = \'Alive\'
                                    OR state = \'Suspected\'
                                    OR state = \'Absent\'
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return @res;
}


# list_resources
# gets the list of all resources
# parameters : base
# return value : list of resources
# side effects : /
sub list_resources($) {
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}

# get_vecs_resources
# returns max resource_id value and 2 vectors:
#   - first:  with 1 for all resource_id
#   - second: with 1 for resource_id of the type "default"
# parameters : base
sub get_vecs_resources($) {
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT resource_id, type
                                FROM resources
                            ");
    $sth->execute();
    my $vec_all = '';
    my $vec_only_default = '';
    my $max_resources = 1;
    while (my @r = $sth->fetchrow_array()){
        $max_resources = $r[0] if ($r[0] > $max_resources);
        vec($vec_all, $r[0], 1) = 1;
        if ($r[1] eq "default"){
            vec($vec_only_default, $r[0], 1) = 1;
        }else{
            vec($vec_only_default, $r[0], 1) = 0;
        }
    }
    $sth->finish();

    return($max_resources, $vec_all, $vec_only_default);
}

# count_all_resources
# count all resources
# parameters : base
# side effects : /
sub count_all_resources($) {
	my $dbh = shift;
	
	my $sth = $dbh->prepare("	SELECT COUNT(*)
	                            FROM resources
	                        ");
    $sth->execute();

    my ($count) = $sth->fetchrow_array();
    return $count ;
}

# get_requested_resources
# get requested resources
# parameters : base limit offset
# side effects : /
sub get_requested_resources($$$) {
	my $dbh = shift;
	my $limit = shift;
	my $offset= shift;
	
	my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                                ORDER BY resource_id LIMIT $limit OFFSET $offset
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();
    return(@res);
}


# list_nodes
# gets the list of all nodes.
# parameters : base
# return value : list of hostnames
# side effects : /
sub list_nodes($) {
    my $dbh = shift;

    #my $sth = $dbh->prepare("   SELECT distinct(network_address), resource_id
    #                            FROM resources
    #                            ORDER BY resource_id ASC");
    my $sth = $dbh->prepare("   SELECT distinct(network_address)
                                FROM resources
                                ORDER BY network_address ASC
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{'network_address'});
    }
    $sth->finish();
    return(@res);
}


# get_resource_info
# returns a ref to some hash containing data for the nodes of the resource passed in parameter
# parameters : base, resource id
# return value : ref
# side effects : /
sub get_resource_info($$) {
    my $dbh = shift;
    my $resource = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                                WHERE
                                    resource_id = $resource
                            ");
    $sth->execute();

    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return $ref;
}


# get_resource_next_value_for_property
# returns the next possible numerical value for a property
# parameters : base, property
# return value : int
# side effects : /
sub get_resource_last_value_of_property($$) {
    my $dbh = shift;
    my $property = shift;
    my $res;

    my %properties = list_resource_properties_fields($dbh);
    if (grep(/^$property$/,keys(%properties))) {
        my $sth = $dbh->prepare("   SELECT $property
                                    FROM resources
                                    ORDER BY $property DESC
                                    LIMIT 1
                                ");
        $sth->execute();

        ($res) = $sth->fetchrow_array();
        $sth->finish();
    }
    return $res;
}


# get_node_info
# returns a ref to some hash containing data for the node passed in parameter
# parameters : base, hostname
# return value : ref
sub get_node_info($$) {
    my $dbh = shift;
    my $hostname = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                                WHERE
                                    network_address = \'$hostname\'
                                ORDER BY resource_id ASC
                            ");
    $sth->execute();

    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    $sth->finish();

    return(@res);
}


# is_node_exists
# returns 1 if the given hostname exists in the database otherwise 0.
# parameters : base, hostname
# return value : ref
# side effects : /
sub is_node_exists($$) {
    my $dbh = shift;
    my $hostname = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM resources
                                WHERE
                                    network_address = \'$hostname\'
                            ");
    $sth->execute();

    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    if (defined($ref)){
        return(1);
    }else{
        return(0);
    }
}


# get_current_assigned_nodes
# returns the current nodes
# parameters : base
sub get_current_assigned_nodes($) {
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT DISTINCT(resources.network_address)
                                FROM assigned_resources, resources
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\' AND
                                    resources.resource_id = assigned_resources.resource_id
                            ");
    $sth->execute();
    my %result;
    while (my @ref = $sth->fetchrow_array()){
        $result{$ref[0]} = 1;
    }
    $sth->finish();

    return(\%result);
}


# get_current_assigned_resources
# returns the current resources
# parameters : base
sub get_current_assigned_resources($) {
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM assigned_resources
                                WHERE
                                    assigned_resource_index = \'CURRENT\'
                            ");
    $sth->execute();
    my @result;
    while (my $ref = $sth->fetchrow_hashref()){
        push(@result, $ref->{resource_id});
    }
    $sth->finish();

    return(@result);
}


# get_current_assigned_job_resources
# returns the current resources ref for a job
# parameters : base, moldable id
sub get_current_assigned_job_resources($$){
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("   SELECT resources.*
                                FROM assigned_resources, resources
                                WHERE
                                    assigned_resource_index = \'CURRENT\'
                                    AND assigned_resources.moldable_job_id = $moldable_job_id
                                    AND resources.resource_id = assigned_resources.resource_id
                            ");
    $sth->execute();
    my @result;
    while (my $ref = $sth->fetchrow_hashref()){
        push(@result, $ref);
    }
    $sth->finish();

    return(@result);
}


# get_specific_resource_states
# returns a hashtable with each given resources and their states
# parameters : base, resource type
sub get_specific_resource_states($$){
    my $dbh = shift;
    my $type = shift;

    my %result;
    my $sth = $dbh->prepare("   SELECT resource_id, state
                                FROM resources
                                WHERE
                                    type = \'$type\'
                            ");
    $sth->execute();
    while (my @ref = $sth->fetchrow_array()){
        push(@{$result{$ref[1]}}, $ref[0]);
    }
    $sth->finish();

    return(\%result);
}

# get_resource_state
# returns the state for the resource
# parameters : base, resource_id
# return value : string
# side effects : /
# sub get_resource_state($$){
#   my $dbh = shift;
#   my $resource_id = shift;
#   my $result;
#   my $sth = $dbh->prepare("     SELECT state
#                                 FROM resources
#                                 WHERE
#                                     resource_id = $resource_id
#                             ")
#     $sth->execute();
#     while (my @ref = $sth->fetchrow_array()){
#         $result = $ref[0];
#     }
#     $sth->finish();
#     return($result);
# }


# get_current_free_resources_of_node
# return an array of free resources for the specified network_address
sub get_current_free_resources_of_node($$){
    my $dbh = shift;
    my $host = shift;

    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM resources
                                WHERE
                                    network_address = \'$host\'
                                    AND resource_id NOT IN (
                                        SELECT resource_id from assigned_resources
                                        where assigned_resource_index = \'CURRENT\'                                    
                                    )
                            ");
    $sth->execute();
    my @result;
    while (my $ref = $sth->fetchrow_hashref()){
        push(@result, $ref->{resource_id});
    }
    $sth->finish();

    return @result;
}


# get_resources_on_node
# returns the current resources on node whose hostname is passed in parameter
# parameters : base, hostname
# return value : weight
# side effects : /
sub get_resources_on_node($$) {
    my $dbh = shift;
    my $hostname = shift;

    my $sth = $dbh->prepare("   SELECT resources.resource_id as resource
                                FROM assigned_resources, resources
                                WHERE
                                    assigned_resources.assigned_resource_index = \'CURRENT\'
                                    AND resources.network_address = \'$hostname\'
                                    AND resources.resource_id = assigned_resources.resource_id
                            ");
    $sth->execute();
    my @result;
    while (my $ref = $sth->fetchrow_hashref()){
        push(@result, $ref->{resource});
    }
    $sth->finish();

    return @result;
}


# get_all_resources_on_node
# returns the current resources on node whose hostname is passed in parameter
# parameters : base, hostname
# return value : resources ids
# side effects : /
sub get_all_resources_on_node($$) {
    my $dbh = shift;
    my $hostname = shift;

    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM resources
                                WHERE
                                    network_address = \'$hostname\'
                            ");
    $sth->execute();
    my @result;
    while (my $ref = $sth->fetchrow_hashref()){
        push(@result, $ref->{resource_id});
    }
    $sth->finish();
    return @result;
}

# set_node_state
# sets the state field of some node identified by its hostname in the base.
# parameters : base, hostname, state, finaudDecision
# return value : /
# side effects : changes the state value in some field of the nodes table
sub set_node_state($$$$) {
    my $dbh = shift;
    my $hostname = shift;
    my $state = shift;
    my $finaud = shift;


    if ($state eq "Suspected"){
        if ($dbh->do("  UPDATE resources
                    SET state = \'$state\', finaud_decision = \'$finaud\', state_num = $State_to_num{$state}
                    WHERE
                        network_address = \'$hostname\'
                        AND (state = \'Alive\'
                             OR (state = \'Suspected\' AND \'$finaud\' = \'NO\' AND finaud_decision = \'YES\'))
                ") <= 0){
            # OAR wants to turn the node into Suspected state but it is not in
            # the Alive state --> so we do nothing
            OAR::Modules::Judas::oar_debug("[OAR::IO] Try to turn the node $hostname into Suspected but it is not into the Alive state SO we do nothing\n");
            return();
        }
    }else{
        $dbh->do("  UPDATE resources
                    SET state = \'$state\', finaud_decision = \'$finaud\', state_num = $State_to_num{$state}
                    WHERE
                        network_address = \'$hostname\'
                ");
    }

    my $date = get_date($dbh);
    if ($Db_type eq "Pg"){
        $dbh->do("  UPDATE resource_logs
                    SET date_stop = \'$date\'
                    FROM resources
                    WHERE
                        resource_logs.date_stop = 0
                        AND resource_logs.attribute = \'state\'
                        AND resources.network_address = \'$hostname\'
                        AND resource_logs.resource_id = resources.resource_id
                 ");
    }else{
        $dbh->do("  UPDATE resource_logs, resources
                    SET resource_logs.date_stop = \'$date\'
                    WHERE
                        resource_logs.date_stop = 0
                        AND resource_logs.attribute = \'state\'
                        AND resources.network_address = \'$hostname\'
                        AND resource_logs.resource_id = resources.resource_id
                 ");
    }

    $dbh->do("INSERT INTO resource_logs (resource_id,attribute,value,date_start,finaud_decision)
                SELECT resources.resource_id,\'state\',\'$state\',\'$date\',\'$finaud\'
                FROM resources
                WHERE
                    resources.network_address = \'$hostname\'
             ");
}

# set_resource_nextState
# sets the nextState field of a resource identified by its resource_id
# parameters : base, resource id, nextState
# return value : /
sub set_resource_nextState($$$) {
    my $dbh = shift;
    my $resource = shift;
    my $next_state = shift;

    my $result = $dbh->do(" UPDATE resources
                            SET next_state = \'$next_state\', next_finaud_decision = \'NO\'
                            WHERE resource_id = $resource
                          ");
    return($result);
}

# set_resources_nextState
# sets the nextState field of a set of resources identified by their resource_id
# parameters : base, ref to an arry of resource id, nextState
# return value : number of updates
sub set_resources_nextState($$$) {
    my $dbh = shift;
    my $resources = shift;
    my $next_state = shift;

    my $result = $dbh->do(" UPDATE resources
                            SET next_state = \'$next_state\', next_finaud_decision = \'NO\'
                            WHERE resource_id IN (".join(",", @{$resources}).")
                          ");
    return($result);
}

# set_resource_state
# sets the state field of a resource
# parameters : base, resource id, state, finaudDecision
sub set_resource_state($$$$) {
    my $dbh = shift;
    my $resource_id = shift;
    my $state = shift;
    my $finaud = shift;

    $dbh->do("  UPDATE resources
                SET state = \'$state\', finaud_decision = \'$finaud\', state_num = $State_to_num{$state}
                WHERE
                    resource_id = $resource_id
             ");

    my $date = get_date($dbh);
    $dbh->do("  UPDATE resource_logs
                SET date_stop = \'$date\'
                WHERE
                    date_stop = 0
                    AND attribute = \'state\'
                    AND resource_id = $resource_id
             ");
    $dbh->do("INSERT INTO resource_logs (resource_id,attribute,value,date_start,finaud_decision)
              VALUES ($resource_id, \'state\', \'$state\',\'$date\',\'$finaud\')
             ");
}


# set_node_nextState
# sets the nextState field of a node identified by its network_address
# parameters : base, network_address, nextState
# return value : /
sub set_node_nextState($$$) {
    my $dbh = shift;
    my $hostname = shift;
    my $next_state = shift;

    my $result = $dbh->do(" UPDATE resources
                            SET next_state = \'$next_state\', next_finaud_decision = \'NO\'
                            WHERE
                                network_address = \'$hostname\'
                          ");
    return($result);
}


# set_node_nextState_if_necessary
sub set_node_nextState_if_necessary($$$) {
    my $dbh = shift;
    my $hostname = shift;
    my $next_state = shift;

    my $result = $dbh->do(" UPDATE resources
                            SET next_state = \'$next_state\', next_finaud_decision = \'NO\'
                            WHERE
                                network_address = \'$hostname\'
                                AND state != \'$next_state\'
                                AND next_state = \'UnChanged\'
                          ");
    return($result);
}


# update_resource_nextFinaudDecision
# update nextFinaudDecision field
# parameters : base, resource_id, "YES" or "NO"
sub update_resource_nextFinaudDecision($$$){
    my $dbh = shift;
    my $resource_id = shift;
    my $finaud = shift;

    $dbh->do("  UPDATE resources
                SET next_finaud_decision = \'$finaud\'
                WHERE
                    resource_id = $resource_id
             ");
}


# update_node_nextFinaudDecision
# update nextFinaudDecision field
# parameters : base, network_address, "YES" or "NO"
sub update_node_nextFinaudDecision($$$){
    my $dbh = shift;
    my $node = shift;
    my $finaud = shift;

    $dbh->do("  UPDATE resources
                SET next_finaud_decision = \'$finaud\'
                WHERE
                    network_address = \'$node\'
             ");
}


# set_node_expiryDate
# sets the expiryDate field of some node identified by its hostname in the base.
# parameters : base, hostname, expiryDate
# return value : /
# side effects : changes the expiryDate value in some field of the nodeProperties table
sub set_node_expiryDate($$$) {
    my $dbh = shift;
    my $hostname = shift;
    my $expiry_date = shift;

    # FIX ME: check first that the expiryDate is actually in the future, return error else
    $dbh->do("  UPDATE resources
                SET expiry_date = \'$expiry_date\'
                WHERE
                    network_address =\'$hostname\'
             ");
}


# set resources property
# change a property value in the resource table
# parameters : base, a hash ref defining the nodes or resources to change, property name, value
# return : # of changed rows
sub set_resources_property($$$$){
    my $dbh = shift;
    my $resources = shift; # e.g. {nodes => [...]}} or {resources => [...]}
    my $property = shift;
    my $value = shift;
    my $where;

#    lock_table($dbh, ["resources","resource_logs"]);
    if (exists($resources->{nodes})){
        $where = "network_address IN (".join(",", map {"'$_'"} @{$resources->{nodes}}).")";
    }elsif (exists($resources->{resources})){
        $where = "resource_id IN (".join(",", @{$resources->{resources}}).")"
    }else{
        return -1;
    }
    my $sth = $dbh->prepare("SELECT resource_id
                             FROM resources
                             WHERE
                                 $where
                                 AND ( $property != \'$value\' OR $property IS NULL )
                            ");
    $sth->execute();
    my @ids = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@ids, $ref->{resource_id});
    }
    my $nbRowsAffected = $#ids + 1;
    if ($nbRowsAffected > 0){
        $nbRowsAffected = $dbh->do("UPDATE resources
                                    SET $property = \'$value\'
                                    WHERE
                                        resource_id IN (".join(",", @ids).")
                                   ");
        # in case of error, $nbRowsAffected can be equal to undef or -1 
        # and if no row was actually updated, equal to 0
        if (defined($nbRowsAffected) and ($nbRowsAffected > 0)){
            #Update LOG table
            my $date = get_date($dbh);
            my $res;
            $res = $dbh->do("UPDATE resource_logs
                             SET date_stop = \'$date\'
                             WHERE
                                 date_stop = 0
                                 AND attribute = \'$property\'
                                 AND resource_id IN (".join(",", @ids).")
                            ");
            if (not defined($res) or ($res < 0)){
                warn("Error: failed to update resource_logs $res \n");
            }
            my $query = "INSERT INTO resource_logs (resource_id,attribute,value,date_start) VALUES ";
            foreach my $i (@ids){
                $query .= " ($i, \'$property\', \'$value\', \'$date\'),";
            }
            chop($query);
            $res = $dbh->do($query);
            if (not defined($res) or ($res != $nbRowsAffected)){
                warn("Error: failed to add resource_logs\n");
            }
        }else{
            warn("Error: failed to update resources\n");
        }
    }
#   unlock_table($dbh;
    return($nbRowsAffected);
}

# add_event_maintenance_on
# add an event in the table resource_logs indicating that this 
# resource is in maintenance (state = Absent, available_upto = 0)
# params: base, resource_id, date_start
sub add_event_maintenance_on($$$){
    my $dbh = shift;
    my $resource_id = shift;
    my $date_start = shift;

    $dbh->do("  INSERT INTO resource_logs (resource_id,attribute,value,date_start)
                    VALUES ($resource_id, \'maintenance\', \'on\', \'$date_start\')
    ");

    return(0);

}

# add_event_maintenance_off
# update the event in the table resource_logs indicating that this 
# resource is in maintenance (state = Absent, available_upto = 0) 
# set the date_stop
# params: base, resource_id, date_stop
sub add_event_maintenance_off($$$){
    my $dbh = shift;
    my $resource_id = shift;
    my $date_stop = shift;

    $dbh->do("  UPDATE resource_logs
		SET date_stop = \'$date_stop\'
		WHERE
		    date_stop = 0
		    AND resource_id = \'$resource_id\'
		    AND attribute = \'maintenance\'
	      ");

    return(0);

}


# get_resources_with_given_sql
# gets the resource list with the given sql properties
# parameters : base, $sql where clause
# return value : list of resource id
# side effects : /
sub get_resources_with_given_sql($$) {
    my $dbh = shift;
    my $where = shift;

    my $sth = $dbh->prepare("   SELECT resource_id
                                FROM resources
                                WHERE
                                    $where
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{resource_id});
    }
    $sth->finish();
    return(@res);
}

# get_nodes_with_given_sql
# gets the nodes list with the given sql properties
# parameters : base, $sql where clause
# return value : list of network addresses
# side effects : /
sub get_nodes_with_given_sql($$) {
    my $dbh = shift;
    my $where = shift;

    my $sth = $dbh->prepare("   SELECT distinct(network_address)
                                FROM resources
                                WHERE
                                    $where
                            ");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref->{network_address});
    }
    $sth->finish();
    return(@res);
}

## return all properties for a specific resource
## parameters : base, resource
#sub get_resource_properties($$){
#    my $dbh = shift;
#    my $resource = shift;
#
#    my $sth = $dbh->prepare("   SELECT *
#                                FROM resources
#                                WHERE
#                                    resource_id = $resource");
#    $sth->execute();
#    my %results = %{$sth->fetchrow_hashref()};
#    $sth->finish();
#
#    return(%results);
#}

# get resource names that will change their state
# parameters : base
sub get_resources_change_state($){
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT resource_id, next_state
                                FROM resources
                                WHERE
                                    next_state != \'UnChanged\'");
    $sth->execute();

    my %results;
    while (my @ref = $sth->fetchrow_array()) {
        $results{$ref[0]} = $ref[1];
    }
    $sth->finish();

    return(%results);
}


# list property fields of the resource_properties table
# args : db ref
sub list_resource_properties_fields($){
    my $dbh = shift;
    
    my $req;
    if ($Db_type eq "Pg"){

				$req = "SELECT column_name AS field FROM information_schema.columns WHERE table_name = \'resources\'";

    }else{
        $req = "SHOW COLUMNS FROM resources";
    }

    my $sth = $dbh->prepare($req);
    $sth->execute();

    my %results;
    while (my @ref = $sth->fetchrow_array()) {
        $results{$ref[0]} = 1;
    }
    $sth->finish();

    return(%results);

}


# update_current_scheduler_priority
# Update the scheduler_priority field of the table resources
sub update_current_scheduler_priority($$$$$){
    my $dbh = shift;
    my $job_id = shift;
    my $moldable_id = shift;
    my $value = shift;
    my $state = shift;
    
    $state = "STOP" if ($state ne "START");

    if (is_conf("SCHEDULER_PRIORITY_HIERARCHY_ORDER")){
        my $types = OAR::IO::get_job_types_hash($dbh,$job_id);
        if (((defined($types->{besteffort})) or (defined($types->{timesharing})))
            and (($state eq "START" and (is_an_event_exists($dbh,$job_id,"SCHEDULER_PRIORITY_UPDATED_START") <= 0))
                or (($state eq "STOP") and (is_an_event_exists($dbh,$job_id,"SCHEDULER_PRIORITY_UPDATED_START") > 0)))
           ){
            my $coeff = 1;
            if ((defined($types->{timesharing})) and !(defined($types->{besteffort}))){
                $coeff = 10;
            }
            my $index = 0;
            foreach my $f (split('/',get_conf("SCHEDULER_PRIORITY_HIERARCHY_ORDER"))){
                next if ($f eq "");
                $index++;

                my $sth = $dbh->prepare("   SELECT distinct(resources.$f)
                                            FROM assigned_resources, resources
                                            WHERE
                                                assigned_resource_index = \'CURRENT\' AND
                                                moldable_job_id = $moldable_id AND
                                                assigned_resources.resource_id = resources.resource_id
                                        ");
                $sth->execute();
                my $value_str;
                while (my @ref = $sth->fetchrow_array()){
                    $value_str .= $dbh->quote($ref[0]);
                    $value_str .= ',';
                }
                $sth->finish();
                return if (!defined($value_str));
                chop($value_str);
                my $req =  "UPDATE resources
                            SET scheduler_priority = scheduler_priority + ($value * $index * $coeff)
                            WHERE
                                $f IN (".$value_str.")
                           ";
                $dbh->do($req);       
            }
            add_new_event($dbh,"SCHEDULER_PRIORITY_UPDATED_$state",$job_id,"Scheduler priority for job $job_id updated (".get_conf("SCHEDULER_PRIORITY_HIERARCHY_ORDER").")");
        }
    }
}


#get the range when nodes are dead between two dates
# arg : base, start date, end date
sub get_resources_absent_suspected_dead_from_range($$$){
    my $dbh = shift;
    my $date_start = shift;
    my $date_end = shift;

    # get dead nodes between two dates
    my $req = "SELECT resource_id, date_start, date_stop, value
               FROM resource_logs
               WHERE
                   attribute = \'state\' AND
                   (
                       value = \'Absent\' OR
                       value = \'Dead\' OR
                       value = \'Suspected\'
                   ) AND
                   date_start <= $date_end AND
                   (
                       date_stop = 0 OR
                       date_stop >= $date_start
                   )
              ";

    my $sth = $dbh->prepare($req);
    $sth->execute();

    my %results;
    while (my @ref = $sth->fetchrow_array()) {
        my $interval_stopDate = $ref[2];
        if (!defined($interval_stopDate)){
            $interval_stopDate = $date_end;
        }
        push(@{$results{$ref[0]}}, [$ref[1],$interval_stopDate,$ref[3]]);
    }
    $sth->finish();

    return(%results);
}

# get_expired_resources
# get the list of resources whose expiry_date is in the past and which are not dead yet.
# 0000-00-00 00:00:00 is always considered as in the future
# parameters: base
# return value: list of resources
# side effects: /
sub get_expired_resources($){
    my $dbh = shift;
    # get expired nodes

    my $date = get_date($dbh);
    my $req = "SELECT resources.resource_id
               FROM resources
               WHERE
                   resources.state = \'Alive\' AND
                   resources.expiry_date > 0 AND
                   resources.desktop_computing = \'YES\' AND
                   resources.expiry_date < $date
              ";
    
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my @results;
    while (my @res = $sth->fetchrow_array()){
        push(@results, $res[0]);
    }
    $sth->finish();
    
    return(@results);
}

# is_node_desktop_computing
# tell if a node is for desktop computing.
# parameters: base, hostname
# return value: boolean
# side effects: /
sub is_node_desktop_computing($$){
    my $dbh = shift;
    my $hostname = shift;
    
    my $sth = $dbh->prepare("   SELECT desktop_computing
                                FROM resources
                                WHERE
                                    network_address = \'$hostname\'
                            ");
    $sth->execute();
    my @ref;
    my $result;
    while (@ref = $sth->fetchrow_array()){
        $result = $ref[0];
        if ($result ne "YES"){
	    return($result);
        }
    }
    return($result);
}


# Return a data structure with the resource description of the given job
# arg : database ref, job id
# return a data structure (an array of moldable jobs):
# example for the first moldable job of the list:
# $result = [
#               [
#                   {
#                       property  => SQL property
#                       resources => [
#                                       {
#                                           resource => resource name
#                                           value    => number of this wanted resource
#                                       }
#                                    ]
#                   }
#               ],
#               walltime,
#               moldable_id
#           ]
sub get_resources_data_structure_current_job($$){
    my $dbh = shift;
    my $job_id = shift;

#    my $sth = $dbh->prepare("   SELECT moldable_job_descriptions.moldable_id, job_resource_groups.res_group_id, moldable_job_descriptions.moldable_walltime, job_resource_groups.res_group_property, job_resource_descriptions.res_job_resource_type, job_resource_descriptions.res_job_value
#                                FROM moldable_job_descriptions, job_resource_groups, job_resource_descriptions, jobs
#                                WHERE
#                                    moldable_job_descriptions.moldable_index = \'CURRENT\'
#                                    AND job_resource_groups.res_group_index = \'CURRENT\'
#                                    AND job_resource_descriptions.res_job_index = \'CURRENT\'
#                                    AND jobs.job_id = $job_id
#                                    AND jobs.job_id = moldable_job_descriptions.moldable_job_id
#                                    AND job_resource_groups.res_group_moldable_id = moldable_job_descriptions.moldable_id
#                                    AND job_resource_descriptions.res_job_group_id = job_resource_groups.res_group_id
#                                ORDER BY moldable_job_descriptions.moldable_id, job_resource_groups.res_group_id, job_resource_descriptions.res_job_order ASC
#                            ");

    my $sth = $dbh->prepare("   SELECT moldable_job_descriptions.moldable_id, job_resource_groups.res_group_id, moldable_job_descriptions.moldable_walltime, job_resource_groups.res_group_property, job_resource_descriptions.res_job_resource_type, job_resource_descriptions.res_job_value
                                FROM moldable_job_descriptions, job_resource_groups, job_resource_descriptions, jobs
                                WHERE
                                    jobs.job_id = $job_id
                                    AND jobs.job_id = moldable_job_descriptions.moldable_job_id
                                    AND job_resource_groups.res_group_moldable_id = moldable_job_descriptions.moldable_id
                                    AND job_resource_descriptions.res_job_group_id = job_resource_groups.res_group_id
                                ORDER BY moldable_job_descriptions.moldable_id, job_resource_groups.res_group_id, job_resource_descriptions.res_job_order ASC
                            ");
 


    $sth->execute();
    my $result;
    my $group_index = -1;
    my $moldable_index = -1;
    my $previous_group = 0;
    my $previous_moldable = 0;
    while (my @ref = $sth->fetchrow_array()){
        if ($previous_moldable != $ref[0]){
            $moldable_index++;
            $previous_moldable = $ref[0];
            $group_index = 0;
            $previous_group = $ref[1];
        }elsif ($previous_group != $ref[1]){
            $group_index++;
            $previous_group = $ref[1];
        }
        # Store walltime
        $result->[$moldable_index]->[1] = $ref[2];
        $result->[$moldable_index]->[2] = $ref[0];
        #Store properties group
        $result->[$moldable_index]->[0]->[$group_index]->{property} = $ref[3];
        my %tmp_hash =  (
                resource    => $ref[4],
                value       => $ref[5]
                        );
        push(@{$result->[$moldable_index]->[0]->[$group_index]->{resources}}, \%tmp_hash);
        
    }
    $sth->finish();
    
    return($result);
}


# get_absent_suspected_resources_for_a_timeout
# args : base ref, timeout in seconds
sub get_absent_suspected_resources_for_a_timeout($$){
    my $dbh = shift;
    my $timeout = shift;

    my $date = get_date($dbh);
    my $req = "SELECT resource_id
                FROM resource_logs
                WHERE
                    attribute = \'state\'
                    AND date_stop = 0
                    AND date_start + $timeout < $date
              ";
    my $sth = $dbh->prepare($req);
    $sth->execute();

    my @results;
    while (my @ref = $sth->fetchrow_array()) {
        push(@results, $ref[0]);
    }
    $sth->finish();

    return(@results);

}


# get_cpuset_values_for_a_moldable_job
# get cpuset values for each nodes of a MJob
sub get_cpuset_values_for_a_moldable_job($$$){
    my $dbh = shift;
    my $cpuset_field = shift;
    my $moldable_job_id = shift;

    my $sql_where_string = "\'0\'";
    my $resources_to_always_add_type = get_conf("SCHEDULER_RESOURCES_ALWAYS_ASSIGNED_TYPE");
    if (defined($resources_to_always_add_type) and ($resources_to_always_add_type ne "")){
        $sql_where_string = "resources.type = \'$resources_to_always_add_type\'";
    }
    
    my $sth = $dbh->prepare("   SELECT resources.network_address, resources.$cpuset_field
                                FROM resources, assigned_resources
                                WHERE
                                    assigned_resources.moldable_job_id = $moldable_job_id AND
                                    assigned_resources.resource_id = resources.resource_id AND
                                    resources.network_address != \'\' AND
                                    (resources.type = \'default\' OR
                                     $sql_where_string)
                                GROUP BY resources.network_address, resources.$cpuset_field
                            ");
    $sth->execute();

    my $results;
    while (my @ref = $sth->fetchrow_array()) {
        push(@{$results->{$ref[0]}}, $ref[1]);
    }

    return($results);
}

# QUEUES MANAGEMENT

# get_queues
# create the list of queues sorted by descending priority
# only return the Active queues.
# return value : list of queues
# side effects : /
sub get_active_queues($) {
    my $dbh = shift;
    my $sth = $dbh->prepare("   SELECT queue_name,scheduler_policy
                                FROM queues
                                WHERE
                                    state = \'Active\'
                                ORDER BY priority DESC
                            ");
    $sth->execute();
    my @res ;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, [ $ref->{'queue_name'}, $ref->{'scheduler_policy'} ]);
    }
    $sth->finish();
    return @res;
}


# get_all_queue_informations
# return a hashtable with all queues and their properties
sub get_all_queue_informations($){
    my $dbh = shift;
    
    my $sth = $dbh->prepare(" SELECT *
                              FROM queues
                            ");
    $sth->execute();
    my %res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        $res{$ref->{queue_name}} = $ref ;
    }
    $sth->finish();
   
    return %res;
}


# stop_all_queues
sub stop_all_queues($){
    my $dbh = shift;
    
    $dbh->do("  UPDATE queues
                SET state = \'notActive\'
             ");
}

# start_all_queues
sub start_all_queues($){
    my $dbh = shift;
    
    $dbh->do("  UPDATE queues
                SET state = \'Active\'
             ");
}


# stop_a_queue
sub stop_a_queue($$){
    my $dbh = shift;
    my $queue = shift;
    
    $dbh->do("  UPDATE queues
                SET state = \'notActive\'
                WHERE
                    queue_name = \'$queue\'
             ");
}

# start_a_queue
sub start_a_queue($$){
    my $dbh = shift;
    my $queue = shift;
    
    $dbh->do("  UPDATE queues
                SET state = \'Active\'
                WHERE
                    queue_name = \'$queue\'
             ");
}

# delete a queue
sub delete_a_queue($$){
    my $dbh = shift;
    my $queue = shift;
    
    $dbh->do("DELETE FROM queues WHERE queue_name = \'$queue\'");
}

# create a queue
sub create_a_queue($$$$){
    my $dbh = shift;
    my $queue = shift;
    my $policy = shift;
    my $priority = shift;
    
    $dbh->do("  INSERT INTO queues (queue_name,priority,scheduler_policy)
                VALUES (\'$queue\',$priority,\'$policy\')");
}


# GANTT MANAGEMENT

#get previous scheduler decisions
#args : base
#return a hashtable : job_id --> [start_time,walltime,queue_name,\@resources,state]
sub get_gantt_scheduled_jobs($){
    my $dbh = shift;
    my $sth;
    if ($Db_type eq "Pg"){
        $sth = $dbh->prepare("SELECT j.job_id, g2.start_time, m.moldable_walltime, g1.resource_id, j.queue_name, j.state, j.job_user, j.job_name,m.moldable_id,j.suspended,j.project
                             FROM gantt_jobs_resources g1, gantt_jobs_predictions g2, moldable_job_descriptions m, jobs j
                             WHERE
                                g1.moldable_job_id = g2.moldable_job_id
                                AND m.moldable_id = g2.moldable_job_id
                                AND j.job_id = m.moldable_job_id
                             ORDER BY j.start_time, j.job_id
                            ");
    }else{
        $sth = $dbh->prepare("SELECT j.job_id, g2.start_time, m.moldable_walltime, g1.resource_id, j.queue_name, j.state, j.job_user, j.job_name,m.moldable_id,j.suspended,j.project
                             FROM gantt_jobs_resources g1, gantt_jobs_predictions g2, moldable_job_descriptions m, jobs j
                             WHERE
                                m.moldable_index = \'CURRENT\'
                                AND g1.moldable_job_id = g2.moldable_job_id
                                AND m.moldable_id = g2.moldable_job_id
                                AND j.job_id = m.moldable_job_id
                             ORDER BY j.start_time, j.job_id
                            ");
    }
    $sth->execute();
    my %res ;
    my @order;
    while (my @ref = $sth->fetchrow_array()) {
        if (!defined($res{$ref[0]})){
            $res{$ref[0]}->[0] = $ref[1];
            $res{$ref[0]}->[1] = $ref[2];
            $res{$ref[0]}->[2] = $ref[4];
            $res{$ref[0]}->[4] = $ref[5];
            $res{$ref[0]}->[5] = $ref[6];
            $res{$ref[0]}->[6] = $ref[7];
            $res{$ref[0]}->[7] = $ref[8];
            $res{$ref[0]}->[8] = $ref[9];
            $res{$ref[0]}->[9] = $ref[10];
            $res{$ref[0]}->[10] = '';  # vector with resources
            push(@order,$ref[0]);
        }
        push(@{$res{$ref[0]}->[3]}, $ref[3]);
        vec($res{$ref[0]}->[10], $ref[3], 1) = 1;
    }
    $sth->finish();

    return(\@order, %res);
}


#get previous scheduler decisions for visu
#args : base
#return a hashtable : job_id --> [start_time,weight,walltime,queue_name,\@nodes]
sub get_gantt_visu_scheduled_jobs($){
    my $dbh = shift;
    my $sth = $dbh->prepare("SELECT g2.job_id, g2.start_time, j.weight, j.maxTime, g1.hostname, j.queue_name, j.state
                             FROM ganttJobsNodes_visu g1, ganttJobsPrediction_visu g2, jobs j
                             WHERE g1.job_id = g2.job_id
                                AND j.job_id = g1.job_id
                            ");
    $sth->execute();
    my %res ;
    while (my @ref = $sth->fetchrow_array()) {
        if (!defined($res{$ref[0]})){
            $res{$ref[0]}->[0] = $ref[1];
            $res{$ref[0]}->[1] = $ref[2];
            $res{$ref[0]}->[2] = $ref[3];
            $res{$ref[0]}->[3] = $ref[5];
            $res{$ref[0]}->[5] = $ref[6];
        }
        push(@{$res{$ref[0]}->[4]}, $ref[4]);
    }
    $sth->finish();

    return %res;
}


#add scheduler decisions
#args : base,moldable_job_id,start_time,\@resources
#return nothing
sub add_gantt_scheduled_jobs($$$$){
    my $dbh = shift;
    my $moldable_job_id = shift;
    my $start_time = shift;
    my $resource_list = shift;

    $dbh->do("INSERT INTO gantt_jobs_predictions (moldable_job_id,start_time)
              VALUES ($moldable_job_id,\'$start_time\')
             ");

    my $str = "";
    foreach my $i (@{$resource_list}){
        $str .= "($moldable_job_id,$i),";
    }
    chop($str);
    $dbh->do("INSERT INTO gantt_jobs_resources (moldable_job_id,resource_id)
              VALUES $str
             ");
}


# Remove an entry in the gantt
# params: base, job_id, resource
sub remove_gantt_resource_job($$$){
    my $dbh = shift;
    my $job = shift;
    my $resource = shift;

    $dbh->do("DELETE FROM gantt_jobs_resources WHERE moldable_job_id = $job AND resource_id = $resource");
}



# Add gantt date (now) in database
# args : base, date
sub set_gantt_date($$){
    my $dbh = shift;
    my $date = shift;

    $dbh->do("INSERT INTO gantt_jobs_predictions (moldable_job_id,start_time)
              VALUES (0,\'$date\')
             ");
}


# Update start_time in gantt for a specified job
# args : base, job id, date
sub set_gantt_job_startTime($$$){
    my $dbh = shift;
    my $job = shift;
    my $date = shift;

    $dbh->do("UPDATE gantt_jobs_predictions
              SET start_time = \'$date\'
              WHERE moldable_job_id = $job
             ");
}


# Get start_time for a given job
# args : base, job id
sub get_gantt_job_start_time($$){
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("SELECT gantt_jobs_predictions.start_time, gantt_jobs_predictions.moldable_job_id
                             FROM gantt_jobs_predictions,moldable_job_descriptions
                             WHERE
                                moldable_job_descriptions.moldable_job_id = $moldable_job_id
                                AND gantt_jobs_predictions.moldable_job_id = moldable_job_descriptions.moldable_id
                            ");
    $sth->execute();
    my @res = $sth->fetchrow_array();
    $sth->finish();
    
    if (defined($res[0])){
        return($res[0],$res[1]);
    }else{
        return(undef);
    }
}


# Get start_time for a given job
# args : base, job id
sub get_gantt_job_start_time_visu($$){
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("SELECT gantt_jobs_predictions_visu.start_time, gantt_jobs_predictions_visu.moldable_job_id
                             FROM gantt_jobs_predictions_visu,moldable_job_descriptions
                             WHERE
                                moldable_job_descriptions.moldable_job_id = $moldable_job_id
                                AND gantt_jobs_predictions_visu.moldable_job_id = moldable_job_descriptions.moldable_id
                            ");
    $sth->execute();
    my @res = $sth->fetchrow_array();
    $sth->finish();
    
    if (defined($res[0])){
        return($res[0],$res[1]);
    }else{
        return(undef);
    }
}


# Update ganttJobsPrediction_visu and ganttJobsNodes_visu with values in ganttJobsPrediction and in ganttJobsNodes
# arg: database ref
sub update_gantt_visualization($){
    my $dbh = shift;

    lock_table($dbh, ["gantt_jobs_predictions_visu","gantt_jobs_resources_visu","gantt_jobs_predictions","gantt_jobs_resources"]);

    $dbh->do("DELETE FROM gantt_jobs_predictions_visu");
    $dbh->do("DELETE FROM gantt_jobs_resources_visu");
##    $dbh->do("OPTIMIZE TABLE ganttJobsResources_visu, ganttJobsPredictions_visu");
    $dbh->do("INSERT INTO gantt_jobs_predictions_visu
              SELECT *
              FROM gantt_jobs_predictions
             ");
    
    $dbh->do("INSERT INTO gantt_jobs_resources_visu
              SELECT *
              FROM gantt_jobs_resources
             ");

    unlock_table($dbh);
}



# Return date of the gantt
sub get_gantt_date($){
    my $dbh = shift;

    my $sth = $dbh->prepare("SELECT start_time
                             FROM gantt_jobs_predictions
                             WHERE
                                moldable_job_id = 0
                            ");
    $sth->execute();
    my @res = $sth->fetchrow_array();
    $sth->finish();

    return $res[0];
}


# Return date of the gantt for visu
sub get_gantt_visu_date($){
    my $dbh = shift;

    my $sth = $dbh->prepare("SELECT start_time
                             FROM gantt_jobs_predictions_visu
                             WHERE
                                moldable_job_id = 0
                            ");
    $sth->execute();
    my @res = $sth->fetchrow_array();
    $sth->finish();

    return($res[0]);
}


# Get all waiting reservation jobs
# parameter : database ref
# return an array of moldable job informations
sub get_waiting_reservations_already_scheduled($){
    my $dbh = shift;

    my $sth = $dbh->prepare("   SELECT moldable_job_descriptions.moldable_job_id, gantt_jobs_predictions.start_time, gantt_jobs_resources.resource_id, moldable_job_descriptions.moldable_walltime, moldable_job_descriptions.moldable_id
                                FROM jobs, moldable_job_descriptions, gantt_jobs_predictions, gantt_jobs_resources
                                WHERE
                                    (jobs.state = \'Waiting\'
                                        OR jobs.state = \'toAckReservation\')
                                    AND jobs.reservation = \'Scheduled\'
                                    AND jobs.job_id = moldable_job_descriptions.moldable_job_id
                                    AND gantt_jobs_predictions.moldable_job_id = moldable_job_descriptions.moldable_id
                                    AND gantt_jobs_resources.moldable_job_id = moldable_job_descriptions.moldable_id
                            ");
    $sth->execute();
    my $res;
    while (my @ref = $sth->fetchrow_array()) {
        push(@{$res->{$ref[0]}->{resources}}, $ref[2]);
        $res->{$ref[0]}->{start_time} = $ref[1];
        $res->{$ref[0]}->{walltime} = $ref[3];
        $res->{$ref[0]}->{moldable_id} = $ref[4];
    }
    $sth->finish();
    return($res);
}


#Flush gantt tables
sub gantt_flush_tables($$$){
    my $dbh = shift;
    my $reservations_to_keep = shift;
    my $log = shift;

    if (defined($log)){
        my $date = get_gantt_date($dbh);
        $dbh->do("  INSERT INTO gantt_jobs_predictions_log (sched_date,moldable_job_id,start_time)
                        SELECT \'$date\', gantt_jobs_predictions.moldable_job_id, gantt_jobs_predictions.start_time
                        FROM gantt_jobs_predictions
                        WHERE
                            gantt_jobs_predictions.moldable_job_id != 0
        ");
        $dbh->do("  INSERT INTO gantt_jobs_resources_log (sched_date,moldable_job_id,resource_id)
                        SELECT \'$date\', gantt_jobs_resources.moldable_job_id, gantt_jobs_resources.resource_id
                        FROM gantt_jobs_resources
        ");
    }

    my $sql = "\'1\'";
    my @moldable_jobs_to_keep;
    foreach my $i (keys(%{$reservations_to_keep})){
        push(@moldable_jobs_to_keep, $reservations_to_keep->{$i}->{moldable_id});
    }
    if ($#moldable_jobs_to_keep >= 0){
        $sql = "moldable_job_id NOT IN (".join(',',@moldable_jobs_to_keep).")";
        $dbh->do("  DELETE FROM gantt_jobs_predictions
                    WHERE
                        $sql
                 ");
        $dbh->do("  DELETE FROM gantt_jobs_resources
                    WHERE
                        $sql
                 ");
    }else{
        $dbh->do("DELETE FROM gantt_jobs_predictions");
        $dbh->do("DELETE FROM gantt_jobs_resources");
    }
}


sub update_scheduler_last_job_date($$$){
    my $dbh = shift;
    my $date = shift;
    my $moldable_id = shift;

    my $req;
    if ($Db_type eq "Pg"){
        $req = "UPDATE resources
                SET
                    last_job_date = $date
                FROM assigned_resources
                WHERE
                    assigned_resources.moldable_job_id = $moldable_id AND
                    assigned_resources.resource_id = resources.resource_id
               ";
    }else{
        $req = "UPDATE resources, assigned_resources
                SET
                    resources.last_job_date = $date
                WHERE
                    assigned_resources.moldable_job_id = $moldable_id AND
                    assigned_resources.resource_id = resources.resource_id
               ";
    }
    return($dbh->do($req));
}

sub search_idle_nodes($$){
    my $dbh = shift;
    my $date = shift;

    my $req = "SELECT resources.network_address
               FROM resources, gantt_jobs_resources, gantt_jobs_predictions
               WHERE
                   resources.resource_id = gantt_jobs_resources.resource_id AND
                   gantt_jobs_predictions.start_time <= $date AND
                   resources.network_address != \'\' AND
                   resources.type = \'default\' AND
		   gantt_jobs_predictions.moldable_job_id = gantt_jobs_resources.moldable_job_id
               GROUP BY resources.network_address
              ";
              
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my %nodes_occupied;
    while (my @ref = $sth->fetchrow_array()) {
        $nodes_occupied{$ref[0]} = 1;
    }
    $sth->finish();

    $req = "SELECT resources.network_address, MAX(resources.last_job_date)
            FROM resources
            WHERE
                resources.state = \'Alive\' AND
                resources.network_address != \'\' AND
                resources.type = \'default\' AND
                resources.available_upto < 2147483647 AND
                resources.available_upto > 0
            GROUP BY resources.network_address";
    $sth = $dbh->prepare($req);
    $sth->execute();
    my %res ;
    while (my @ref = $sth->fetchrow_array()) {
        if (!defined($nodes_occupied{$ref[0]})){
            $res{$ref[0]} = $ref[1];
        }
    }
    $sth->finish();

    return(%res);
}


sub get_next_job_date_on_node($$){
    my $dbh = shift;
    my $hostname = shift;

    my $req = "SELECT MIN(gantt_jobs_predictions.start_time)
               FROM resources, gantt_jobs_predictions, gantt_jobs_resources
               WHERE
                   resources.network_address = \'$hostname\' AND
                   gantt_jobs_resources.resource_id = resources.resource_id AND
                   gantt_jobs_predictions.moldable_job_id = gantt_jobs_resources.moldable_job_id
              ";

    my $sth = $dbh->prepare($req);
    $sth->execute();
    my @ref = $sth->fetchrow_array();
    $sth->finish();

    return($ref[0]);
}

sub get_last_wake_up_date_of_node($$){
    my $dbh = shift;
    my $hostname = shift;
    
    my $req = "SELECT date
               FROM event_log_hostnames,event_logs
               WHERE
                  event_log_hostnames.event_id = event_logs.event_id AND
                  event_log_hostnames.hostname = \'$hostname\' AND
                  event_logs.type = \'WAKEUP_NODE\'
               ORDER BY date DESC
               LIMIT 1";

        my $sth = $dbh->prepare($req);
    $sth->execute();
    my @ref = $sth->fetchrow_array();
    $sth->finish();

    return($ref[0]);
}

#Get jobs to launch at a given date
#args : base, date in sql format
sub get_gantt_jobs_to_launch($$){
    my $dbh = shift;
    my $date = shift;

    # postgresql is quicker without the moldable_index filter
    my $moldable_index_current = "";
    if ($Db_type eq "mysql") {
        $moldable_index_current = "m.moldable_index = \'CURRENT\' AND";
    }
    my $req;
    # only use the "CASE WHEN.." query when the energy saving feature is on
    # (although it would function for both cases)
    if (is_conf("SCHEDULER_NODE_MANAGER_WAKE_UP_CMD") or (get_conf("ENERGY_SAVING_INTERNAL") eq "yes")) {
        $req = <<EOS;
SELECT gp.moldable_job_id, gr.resource_id, j.job_id
FROM gantt_jobs_resources gr, gantt_jobs_predictions gp, jobs j, moldable_job_descriptions m, resources r
WHERE
    $moldable_index_current gr.moldable_job_id = gp.moldable_job_id
    AND m.moldable_id = gr.moldable_job_id
    AND j.job_id = m.moldable_job_id
    AND gp.start_time <= $date
    AND j.state = \'Waiting\'
    AND r.resource_id = gr.resource_id
    AND CASE WHEN EXISTS (
                       SELECT 1
                       FROM job_types t
                       WHERE 
                           m.moldable_job_id = t.job_id
                           AND t.type in (\'deploy=standby\', \'cosystem=standby\', \'noop=standby\')
        )
        THEN (
            (r.state = \'Alive\' OR ( r.state = \'Absent\' AND (gp.start_time + m.moldable_walltime) <= r.available_upto))
            AND NOT EXISTS ( 
                SELECT 1
                FROM resources rr, gantt_jobs_resources gg
                WHERE
                    gg.moldable_job_id = gr.moldable_job_id
                    AND rr.resource_id = gg.resource_id
                    AND (
                        rr.state IN (\'Dead\',\'Suspected\')
                        OR rr.next_state IN (\'Dead\',\'Suspected\')
                        OR (rr.state = \'Absent\' AND (gp.start_time + m.moldable_walltime) > rr.available_upto)
                        OR ( rr.next_state = \'Absent\' AND (gp.start_time + m.moldable_walltime) > rr.available_upto)
                    )
            )
        )
        ELSE (
            r.state = \'Alive\'
            AND NOT EXISTS ( 
                SELECT 1
                FROM resources rr, gantt_jobs_resources gg
                WHERE
                    gg.moldable_job_id = gr.moldable_job_id
                    AND rr.resource_id = gg.resource_id
                    AND (
                        rr.state IN (\'Dead\',\'Suspected\',\'Absent\')
                        OR rr.next_state IN (\'Dead\',\'Suspected\',\'Absent\')
                    )
            )
        )
        END
EOS
    } else {
        $req = <<EOS;
SELECT gp.moldable_job_id, gr.resource_id, j.job_id
FROM gantt_jobs_resources gr, gantt_jobs_predictions gp, jobs j, moldable_job_descriptions m, resources r
WHERE
    $moldable_index_current gr.moldable_job_id = gp.moldable_job_id
    AND m.moldable_id = gr.moldable_job_id
    AND j.job_id = m.moldable_job_id
    AND gp.start_time <= $date
    AND j.state = \'Waiting\'
    AND r.resource_id = gr.resource_id
    AND r.state = \'Alive\'
    AND NOT EXISTS ( 
        SELECT 1
        FROM resources rr, gantt_jobs_resources gg
        WHERE
            gg.moldable_job_id = gr.moldable_job_id
            AND rr.resource_id = gg.resource_id
            AND (
                rr.state IN (\'Dead\',\'Suspected\',\'Absent\')
                OR rr.next_state IN (\'Dead\',\'Suspected\',\'Absent\')
            )
    )
EOS
    }
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my %res ;
    while (my @ref = $sth->fetchrow_array()) {
        $res{$ref[2]}->[0] = $ref[0];
        push(@{$res{$ref[2]}->[1]}, $ref[1]);
    }
    $sth->finish();
    return(%res);
}


#Get hostname that we must wake up to launch jobs
#args : base, date in sql format, time to wait for the node to wake up
sub get_gantt_hostname_to_wake_up($$$){
    my $dbh = shift;
    my $date = shift;
	my $wakeup_time = shift;
    my $req = "SELECT resources.network_address
               FROM gantt_jobs_resources g1, gantt_jobs_predictions g2, jobs j, moldable_job_descriptions m, resources
               WHERE
                   m.moldable_index = \'CURRENT\'
                   AND g1.moldable_job_id= g2.moldable_job_id
                   AND m.moldable_id = g1.moldable_job_id
                   AND j.job_id = m.moldable_job_id
                   AND g2.start_time <= $date + $wakeup_time
                   AND j.state = \'Waiting\'
                   AND resources.resource_id = g1.resource_id
                   AND resources.state = \'Absent\'
                   AND resources.network_address != \'\'
                   AND resources.type = \'default\'
                   AND (g2.start_time + m.moldable_walltime) <= resources.available_upto
                   AND NOT EXISTS (
                       SELECT 1
                       FROM job_types t
                       WHERE 
                           m.moldable_job_id = t.job_id
                           AND t.type in (\'deploy=standby\', \'cosystem=standby\', \'noop=standby\')
                       )
               GROUP BY resources.network_address
              ";
    
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my @res ;
    while (my @ref = $sth->fetchrow_array()) {
        push(@res, $ref[0]);
    }
    $sth->finish();

    return(@res);
}


#Get informations about resources for jobs to launch at a given date
#args : base, date in sql format
sub get_gantt_resources_for_jobs_to_launch($$){
    my $dbh = shift;
    my $date = shift;

    my $req = "SELECT g1.resource_id, j.job_id
               FROM gantt_jobs_resources g1, gantt_jobs_predictions g2, jobs j, moldable_job_descriptions m
               WHERE
                  m.moldable_index = \'CURRENT\'
                  AND g1.moldable_job_id = m.moldable_id
                  AND m.moldable_job_id = j.job_id
                  AND g1.moldable_job_id = g2.moldable_job_id
                  AND g2.start_time <= $date
                  AND j.state = \'Waiting\'
              ";
    
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my %res ;
    while (my @ref = $sth->fetchrow_array()) {
        $res{$ref[0]} = $ref[1];
    }
    $sth->finish();

    return %res;
}


#Get resources for job in the gantt diagram
#args : base, moldable job id
sub get_gantt_resources_for_job($$){
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("SELECT g.resource_id
                             FROM gantt_jobs_resources g
                             WHERE
                                g.moldable_job_id = $moldable_job_id 
                            ");
    $sth->execute();
    my @res ;
    while (my @ref = $sth->fetchrow_array()) {
        push( @res, $ref[0]); 
    }
    $sth->finish();

    return @res;
}


#Get Alive resources for a job
#args : base, moldable job id
sub get_gantt_Alive_resources_for_job($$){
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("SELECT g.resource_id
                             FROM gantt_jobs_resources g, resources r
                             WHERE
                                g.moldable_job_id = $moldable_job_id 
                                AND r.resource_id = g.resource_id
                                AND r.state = \'Alive\'
                            ");
    $sth->execute();
    my @res ;
    while (my @ref = $sth->fetchrow_array()) {
        push( @res, $ref[0]); 
    }
    $sth->finish();

    return(@res);
}


#Get Alive or Standby resources for a job
#args : base, moldable job id
sub get_gantt_Alive_or_Standby_resources_for_job($$$){
    my $dbh = shift;
    my $moldable_job_id = shift;
    my $max_date = shift;
    
    $max_date = $max_date + $Cm_security_duration;
    my $sth = $dbh->prepare("SELECT g.resource_id
                             FROM gantt_jobs_resources g, resources r
                             WHERE
                                g.moldable_job_id = $moldable_job_id 
                                AND r.resource_id = g.resource_id
                                AND ( r.state = \'Alive\' 
                                    OR ( r.state = \'Absent\'
                                        AND r.available_upto > $max_date )
                                    )
                            ");
    $sth->execute();
    my @res ;
    while (my @ref = $sth->fetchrow_array()) {
        push( @res, $ref[0]); 
    }
    $sth->finish();

    return(@res);
}


#Get network_address allocated to a (waiting) reservation
#args : base, job id
sub get_gantt_visu_scheduled_job_resources($$){
    my $dbh = shift;
    my $moldable_job_id = shift;

    my $sth = $dbh->prepare("SELECT r.resource_id, r.network_address, r.state
                             FROM gantt_jobs_resources_visu g, moldable_job_descriptions m, resources r
                             WHERE
                                m.moldable_job_id = $moldable_job_id
                                AND m.moldable_id = g.moldable_job_id
                                AND g.resource_id = r.resource_id
                            ");
    $sth->execute();
    my %h;
    while (my @ref = $sth->fetchrow_array()) {
        $h{$ref[0]}->{'network_address'}=$ref[1];
        $h{$ref[0]}->{'current_state'}=$ref[2];
    }
    $sth->finish();

    return \%h;
}

# TIME CONVERSION

# ymdhms_to_sql
# converts a date specified as year, month, day, minutes, secondes to a string
# in the format used by the sql database
# parameters : year, month, day, hours, minutes, secondes
# return value : date string
# side effects : /
sub ymdhms_to_sql($$$$$$) {
    my ($year,$mon,$mday,$hour,$min,$sec)=@_;
    return ($year+1900)."-".($mon+1)."-".$mday." $hour:$min:$sec";
}



# sql_to_ymdhms
# converts a date specified in the format used by the sql database to year,
# month, day, minutes, secondes values
# parameters : date string
# return value : year, month, day, hours, minutes, secondes
# side effects : /
sub sql_to_ymdhms($) {
    my $date=shift;
    $date =~ tr/-:/  /;
    my ($year,$mon,$mday,$hour,$min,$sec) = split / /,$date;
    # adjustment for localtime (since 1st january 1900, month from 0 to 11)
    $year-=1900;
    $mon-=1;
    return ($year,$mon,$mday,$hour,$min,$sec);
}



# ymdhms_to_local
# converts a date specified as year, month, day, minutes, secondes into an
# integer local time format
# parameters : year, month, day, hours, minutes, secondes
# return value : date integer
# side effects : /
sub ymdhms_to_local($$$$$$) {
    my ($year,$mon,$mday,$hour,$min,$sec)=@_;
    return Time::Local::timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
}



# local_to_ymdhms
# converts a date specified into an integer local time format to year, month,
# day, minutes, secondes values
# parameters : date integer
# return value : year, month, day, hours, minutes, secondes
# side effects : /
sub local_to_ymdhms($) {
    my $date=shift;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date);
    $year += 1900;
    $mon += 1;
    return ($year,$mon,$mday,$hour,$min,$sec);
}



# sql_to_local
# converts a date specified in the format used by the sql database to an
# integer local time format
# parameters : date string
# return value : date integer
# side effects : /
sub sql_to_local($) {
    my $date=shift;
    my ($year,$mon,$mday,$hour,$min,$sec)=sql_to_ymdhms($date);
    #if ($year <= 1971){
    #    return(0);
    #}else{
        return ymdhms_to_local($year,$mon,$mday,$hour,$min,$sec);
    #}
}



# local_to_sql
# converts a date specified in an integer local time format to the format used
# by the sql database
# parameters : date integer
# return value : date string
# side effects : /
sub local_to_sql($) {
    my $local=shift;
    #my ($year,$mon,$mday,$hour,$min,$sec)=local_to_ymdhms($local);
    #return ymdhms_to_sql($year,$mon,$mday,$hour,$min,$sec);
    #return $year."-".$mon."-".$mday." $hour:$min:$sec";
    return(strftime("%F %T",localtime($local)));
}



# sql_to_hms
# converts a date specified in the format used by the sql database to hours,
# minutes, secondes values
# parameters : date string
# return value : hours, minutes, secondes
# side effects : /
sub sql_to_hms($) {
    my $date=shift;
    my ($hour,$min,$sec) = split /:/,$date;
    return ($hour,$min,$sec);
}



# hms_to_duration
# converts a date specified in hours, minutes, secondes values to a duration
# in seconds
# parameters : hours, minutes, secondes
# return value : duration
# side effects : /
sub hms_to_duration($$$) {
    my ($hour,$min,$sec) = @_;
    return $hour*3600 +$min*60 +$sec;
}



# hms_to_sql
# converts a date specified in hours, minutes, secondes values to the format
# used by the sql database
# parameters : hours, minutes, secondes
# return value : date string
# side effects : /
sub hms_to_sql($$$) {
    my ($hour,$min,$sec) = @_;
    return "$hour:$min:$sec";
}



# duration_to_hms
# converts a date specified as a duration in seconds to hours, minutes,
# secondes values
# parameters : duration
# return value : hours, minutes, secondes
# side effects : /
sub duration_to_hms($) {
    my $date=shift;
    my $sec=$date%60;
    $date/=60;
    my $min=$date%60;
    $date = int($date / 60);
    my $hour=$date;
    return ($hour,$min,$sec);
}



# duration_to_sql
# converts a date specified as a duration in seconds to the format used by the
# sql database
# parameters : duration
# return value : date string
# side effects : /
sub duration_to_sql($) {
    my $duration=shift;
    my ($hour,$min,$sec)=duration_to_hms($duration);
    return hms_to_sql($hour,$min,$sec);
}



# sql_to_duration
# converts a date specified in the format used by the sql database to a
# duration in seconds
# parameters : date string
# return value : duration
# side effects : /
sub sql_to_duration($) {
    my $date=shift;
    my ($hour,$min,$sec)=sql_to_hms($date);
    return hms_to_duration($hour,$min,$sec);
}



# get_date
# returns the current time in the format used by the sql database
# parameters : database
# return value : date string
# side effects : /
sub get_date($) {
    #my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
    #return ymdhms_to_sql($year,$mon,$mday,$hour,$min,$sec);

    my $dbh = shift;

    my $req;
    if ($Db_type eq "Pg"){
        $req = "select EXTRACT(EPOCH FROM current_timestamp)";
    }else{
        $req = "SELECT UNIX_TIMESTAMP()";
    }
    my $sth = $dbh->prepare($req);
    $sth->execute();
    my @ref = $sth->fetchrow_array();
    $sth->finish();

    return(int($ref[0]));
}


# MONITORING

sub register_monitoring_values($$$$){
    my $dbh = shift;
    my $table = shift;
    my $fields = shift;
    my $values = shift;

    if (! insert_monitoring_row($dbh,$table,$fields,$values)){
        my $create_str;
        $create_str = "CREATE TABLE monitoring_$table (";
        for (my $i=0; $i <= $#{$fields}; $i++){
            if ($values->[$i] =~ /^\d+$/){
                if ($Db_type eq "Pg"){
                    $create_str .= "$fields->[$i] integer,";
                }else{
                    $create_str .= "$fields->[$i] INT,";
                }
            }else{
                $create_str .= "$fields->[$i] varchar(255),"
            }
        }
        chop($create_str);
        $create_str .= ")";
        oar_debug("$create_str\n");
        if ($dbh->do($create_str)){
            if (! insert_monitoring_row($dbh,$table,$fields,$values)){
                return(2);
            }
        }else{
            return(1);
        }
    }
    
    return(0);
}

sub insert_monitoring_row($$$$){
    my $dbh = shift;
    my $table = shift;
    my $fields = shift;
    my $values = shift;

    my $value_str;
    foreach my $v (@{$values}){
        $value_str .= $dbh->quote($v);
        $value_str .= ',';
    }
    chop($value_str);
    return($dbh->do("   INSERT INTO monitoring_$table (".join(",",@{$fields}).")
                        VALUES (".$value_str.")
                    "));
}

# ACCOUNTING

# check jobs that are not treated in accounting table
# params : base, window size
sub check_accounting_update($$){
    my $dbh = shift;
    my $windowSize = shift;

    my $req = "SELECT jobs.start_time, jobs.stop_time, moldable_job_descriptions.moldable_walltime, jobs.job_id, jobs.job_user, jobs.queue_name, count(assigned_resources.resource_id), jobs.project

               FROM jobs, moldable_job_descriptions, assigned_resources, resources
               WHERE 
                   jobs.accounted = \'NO\' AND
                   (jobs.state = \'Terminated\' OR jobs.state = \'Error\') AND
                   jobs.stop_time >= jobs.start_time AND
                   jobs.start_time > 1 AND
                   jobs.assigned_moldable_job = moldable_job_descriptions.moldable_id AND
                   assigned_resources.moldable_job_id = moldable_job_descriptions.moldable_id AND
                   assigned_resources.resource_id = resources.resource_id AND
                   resources.type = 'default'
               GROUP BY jobs.start_time, jobs.stop_time, moldable_job_descriptions.moldable_walltime, jobs.job_id, jobs.project, jobs.job_user, jobs.queue_name
              "; 

    my $sth = $dbh->prepare("$req");
    $sth->execute();

    # Preparing the query that checks window existency
    # This is made here out of the main loop for performance optimization
    # This sth is used into the add_accounting_row function
    my $sth1 = $dbh->prepare("  SELECT consumption
                                FROM accounting
                                WHERE
                                    accounting_user = ? AND
                                    accounting_project = ? AND
                                    consumption_type = ? AND
                                    queue_name = ? AND
                                    window_start = ? AND
                                    window_stop = ?
                            ");

    while (my @ref = $sth->fetchrow_array()) {
        my $start = $ref[0];
        my $stop = $ref[1];
        my $theoricalStopTime = $ref[2] + $start;
        print("[ACCOUNTING] Treate job $ref[3]\n");
        update_accounting($dbh,$sth1,$start,$stop,$windowSize,$ref[4],$ref[7],$ref[5],"USED",$ref[6]);
        update_accounting($dbh,$sth1,$start,$theoricalStopTime,$windowSize,$ref[4],$ref[7],$ref[5],"ASKED",$ref[6]);
        $dbh->do("  UPDATE jobs
                    SET accounted = \'YES\'
                    WHERE
                        job_id = $ref[3]
                 ");
    }
}

# insert accounting data in table accounting
# params : base, start date in second, stop date in second, window size, user, queue, type(ASKED or USED)
sub update_accounting($$$$$$$$$$){
    my $dbh = shift;
    my $sth1 = shift;
    my $start = shift;
    my $stop = shift;
    my $windowSize = shift;
    my $user = shift;
    my $project = shift;
    my $queue = shift;
    my $type = shift;
    my $nb_resources = shift;

    use integer;

    my $nbWindows = $start / $windowSize;
    my $windowStart = $nbWindows * $windowSize;
    my $windowStop = $windowStart + $windowSize - 1;
   
    my $conso;
    # Accounting algo
    while ($stop > $start){
        if ($stop <= $windowStop){
            $conso = $stop - $start;
        }else{
            $conso = $windowStop - $start + 1;
        }
        $conso = $conso * $nb_resources;
        add_accounting_row($dbh,$sth1,$windowStart,$windowStop,$user,$project,$queue,$type,$conso);
        $windowStart = $windowStop + 1;
        $start = $windowStart;
        $windowStop += $windowSize;
    }
}

# start and stop in SQL syntax
sub add_accounting_row($$$$$$$$$){
    my $dbh = shift;
    my $sth1 = shift;
    my $start = shift;
    my $stop = shift;
    my $user = shift;
    my $project = shift;
    my $queue = shift;
    my $type = shift;
    my $conso = shift;

    # Test if the window exists
    $sth1->execute($user,$project,$type,$queue,$start,$stop);
    my @ref = $sth1->fetchrow_array();
    $sth1->finish();
    if (defined($ref[0])){
        # Update the existing window
        $conso += $ref[0];
        print("[ACCOUNTING] Update the existing window $start --> $stop , project $project, user $user, queue $queue, type $type with conso = $conso s\n");
        $dbh->do("  UPDATE accounting
                    SET consumption = $conso
                    WHERE
                        accounting_user = \'$user\' AND
                        accounting_project = \'$project\' AND
                        consumption_type = \'$type\' AND
                        queue_name = \'$queue\' AND
                        window_start = \'$start\' AND
                        window_stop = \'$stop\'
                ");
    }else{
        # Create the window
        print("[ACCOUNTING] Create new window $start --> $stop , project $project, user $user, queue $queue, type $type with conso = $conso s\n");
        $dbh->do("  INSERT INTO accounting (accounting_user,consumption_type,queue_name,window_start,window_stop,consumption,accounting_project)
                    VALUES (\'$user\',\'$type\',\'$queue\',\'$start\',\'$stop\',$conso,\'$project\')
                 ");
    }
}


sub get_sum_accounting_window($$$$){
    my $dbh = shift;
    my $queue = shift;
    my $start_window = shift;
    my $stop_window = shift;
    
    my $sth = $dbh->prepare("   SELECT consumption_type, SUM(consumption)
                                FROM accounting
                                WHERE
                                    queue_name = \'$queue\' AND
                                    window_start >= $start_window AND
                                    window_start < $stop_window
                                GROUP BY consumption_type
                            ");
    $sth->execute();

    my $results;
    while (my @r = $sth->fetchrow_array()) {
        $results->{$r[0]} = $r[1];
    }
    $sth->finish();

    return($results);
}


sub get_sum_accounting_for_param($$$$$){
    my $dbh = shift;
    my $queue = shift;
    my $param_name = shift;
    my $start_window = shift;
    my $stop_window = shift;
    
    my $sth = $dbh->prepare("   SELECT $param_name,consumption_type, SUM(consumption)
                                FROM accounting
                                WHERE
                                    queue_name = \'$queue\' AND
                                    window_start >= $start_window AND
                                    window_start < $stop_window
                                GROUP BY $param_name,consumption_type
                            ");
    $sth->execute();

    my $results;
    while (my @r = $sth->fetchrow_array()) {
        $results->{$r[0]}->{$r[1]} = $r[2];
    }
    $sth->finish();

    return($results);
}


# Get an array of consumptions by users 
# params: base, start date, ending date, optional user
sub get_accounting_summary($$$$$){
    my $dbh = shift;
    my $start = shift;
    my $stop = shift;
    my $user = shift;
    my $sql_property = shift;
    my $user_query="";
    my $property="";
    if (defined($user) && "$user" ne "") {
        $user_query="AND accounting_user = ". $dbh->quote($user);
    }
    if (defined($sql_property) && "$sql_property" ne "") {
      $property="AND ( $sql_property )";
    }else{
      $property="";
    }

    my $sth = $dbh->prepare("   SELECT accounting_user as user,
                                       consumption_type,
                                       sum(consumption) as seconds,
                                       floor(sum(consumption)/3600) as hours,
                                       min(window_start) as first_window_start,
                                       max(window_stop) as last_window_stop
                                FROM accounting
                                WHERE
                                    window_stop > $start AND
                                    window_start < $stop
                                    $user_query
                                    $property
                                GROUP BY accounting_user,consumption_type
                                ORDER BY seconds
                            ");
    $sth->execute();

    my $results;
    while (my @r = $sth->fetchrow_array()) {
        $results->{$r[0]}->{$r[1]} = $r[2];
        $results->{$r[0]}->{begin} = $r[4];
        $results->{$r[0]}->{end} = $r[5];
    }
    $sth->finish();

    return($results);
}


# Get an array of consumptions by project for a given user
# params: base, start date, ending date, user
sub get_accounting_summary_byproject($$$$$$){
    my $dbh = shift;
    my $start = shift;
    my $stop = shift;
    my $user = shift;
    my $limit = shift;
    my $offset = shift;
    my $user_query="";
    if (defined($user) && "$user" ne "") {
        $user_query="AND accounting_user = ". $dbh->quote($user);
    }
    my $limit_query="";
    if (defined($limit) && "$limit" ne "") {
        $limit_query="LIMIT $limit";
    }    
    if (defined($offset) && "$offset" ne "") {
        $limit_query.=" OFFSET $offset";
    }



    my $sth = $dbh->prepare("   SELECT accounting_user as user,
                                       consumption_type,
                                       sum(consumption) as seconds,
                                       accounting_project as project
                                FROM accounting
                                WHERE
                                    window_stop > $start AND
                                    window_start < $stop
                                    $user_query
                                GROUP BY accounting_user,project,consumption_type
                                ORDER BY project,consumption_type,seconds
                                $limit_query
                            ");
    $sth->execute();

    my $results;
    while (my @r = $sth->fetchrow_array()) {
        $results->{$r[3]}->{$r[1]}->{$r[0]} = $r[2];
    }
    $sth->finish();

    return($results);
}

# Empty the table accounting and update the jobs table
sub delete_all_from_accounting($){
    my $dbh = shift;

    $dbh->do("DELETE FROM accounting");
    $dbh->do("UPDATE jobs SET accounted = 'NO'");
}

# Remove windows from accounting
sub delete_accounting_windows_before($$){
    my $dbh = shift;
    my $duration = shift;

    $dbh->do("DELETE FROM accounting WHERE window_stop <= $duration");
}

# Get the last project Karma of user at a given date
# params: base,user,project,date
sub get_last_project_karma($$$$) {
    my $dbh = shift;
    my $user = $dbh->quote(shift);
    my $project = $dbh->quote(shift);
    my $date = shift;

    my $sth = $dbh->prepare("   SELECT message,project,start_time
                                FROM jobs
                                WHERE
                                      job_user = $user AND
                                      message like \'%Karma%\' AND
                                      project = $project AND
                                      start_time < $date
                                ORDER BY start_time desc
                                LIMIT 1
                          ");

    $sth->execute();

    return($sth->fetchrow_array());
}


#EVENTS LOG MANAGEMENT

#add a new entry in event_log table
#args : database ref, event type, job_id , description
sub add_new_event($$$$){
    my $dbh = shift;
    my $type = shift;
    my $job_id = shift;
    my $description = substr(shift,0,254);

    $description = $dbh->quote($description);
    my $date = get_date($dbh);
    $dbh->do("INSERT INTO event_logs (type,job_id,date,description) VALUES (\'$type\',$job_id,\'$date\',$description)");
}

#add a new entry in event_log_hosts table
#args : database ref, type, job id, description, ref of an array of resource ids
sub add_new_event_with_host($$$$$){
    my $dbh = shift;
    my $type = shift;
    my $job_id = shift;
    my $description = substr(shift,0,254);
    my $hostnames = shift;
    
    my $date = get_date($dbh);
    #lock_table($dbh,["event_logs"]);
    $dbh->do("  INSERT INTO event_logs (type,job_id,date,description)
                VALUES (\'$type\',$job_id,\'$date\',\'$description\')
             ");
    my $event_id = get_last_insert_id($dbh,"event_logs_event_id_seq");
    #unlock_table($dbh);

    my %tmp;
    foreach my $n (@{$hostnames}){
        if (!defined($tmp{$n})){
            $dbh->do("  INSERT INTO event_log_hostnames (event_id,hostname)
                        VALUES ($event_id,\'$n\')
                     ");
            $tmp{$n} = 1;
        }
    }
}


# Turn the field toCheck into NO
#args : database ref, event type, job_id
sub check_event($$$){
    my $dbh = shift;
    my $type = shift;
    my $job_id = shift;

    $dbh->do("  UPDATE event_logs
                SET to_check = \'NO\'
                WHERE
                    to_check = \'YES\'
                    AND type = \'$type\'
                    AND job_id = $job_id
             ");
}


# Get all events with toCheck field on YES
# args: database ref
sub get_to_check_events($){
    my $dbh = shift;
    my $sth = $dbh->prepare("   SELECT type, job_id, event_id, description
                                FROM event_logs
                                WHERE
                                    to_check = \'YES\'
                                ORDER BY event_id
                            ");
    $sth->execute();

    my @results;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@results, $ref);
    }
    $sth->finish();
    
    return(@results);
}

# Get hostnames corresponding to an event Id
# args: database ref, event id
sub get_hostname_event($$){
    my $dbh = shift;
    my $eventId = shift;

    my $sth = $dbh->prepare("   SELECT hostname
                                FROM event_log_hostnames
                                WHERE
                                    event_id = $eventId
                            ");
    $sth->execute();

    my @results;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@results, $ref->{hostname});
    }
    $sth->finish();

    return(@results);
}

# Get events for the hostname given as parameter
# If date is given, returns events since that date, else return the 30 last events.
# args: database ref, network_address, date
sub get_events_for_hostname($$$){
    my $dbh = shift;
    my $host = shift;
    my $date = shift;
    my $sth;
    if ($date eq "") {
        $sth = $dbh->prepare("SELECT *
                              FROM event_log_hostnames, event_logs 
                              WHERE
                                  event_log_hostnames.event_id = event_logs.event_id
                                  AND event_log_hostnames.hostname = '$host'
                              ORDER BY event_logs.date DESC
                              LIMIT 30");
    } else {
        $sth = $dbh->prepare("SELECT *
                              FROM event_log_hostnames, event_logs
                              WHERE
                                  event_log_hostnames.event_id = event_logs.event_id
                                  AND event_log_hostnames.hostname = '$host'
                                  AND event_logs.date >= " . 
                             sql_to_local($date) .
                             " ORDER BY event_logs.date DESC");
    }
    $sth->execute();

    my @results;
    while (my $ref = $sth->fetchrow_hashref()) {
        unshift(@results, $ref);
    }
    $sth->finish();

    return(@results);
}

# Get the last event for the given type
# args: database ref, event type
# returns: the requested event
sub get_last_event_from_type($$){
    my $dbh = shift;
    my $type = shift;
    my $sth = $dbh->prepare("SELECT *
                              FROM event_logs 
                              WHERE
                                  type = '$type'
                              ORDER BY event_id DESC
                              LIMIT 1");

    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    $sth->finish();

    return($ref);
}

# Get events for the specified job
# args: database ref, job id
sub get_job_events($$){
    my $dbh =shift;
    my $job_id = shift;

    my $sth = $dbh->prepare("   SELECT *
                                FROM event_logs
                                WHERE
                                    job_id = $job_id
                            ");
    $sth->execute();

    my @results;
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@results, $ref);
    }
    $sth->finish();

    return(@results);
}


sub is_an_event_exists($$$){
    my $dbh =shift;
    my $job_id = shift;
    my $event = shift;

    my $sth = $dbh->prepare("   SELECT COUNT(*)
                                FROM event_logs
                                WHERE
                                    job_id = $job_id AND
                                    type = \'$event\'
                                LIMIT 1
                            ");
    $sth->execute();
    my @r = $sth->fetchrow_array();
    $sth->finish();

    return($r[0]);
}


# LOCK FUNCTIONS:

# get_lock
# lock a mysql mutex variable
# parameters : base, mutex, timeout
# return value : 1 if the lock was obtained successfully, 0 if the attempt timed out or undef if an error occurred  
# side effects : a second get_lock of the same mutex will be blocked until release_lock is called on the mutex
sub get_lock($$$) {
    my $dbh = shift;
    my $mutex = shift;
    my $timeout = shift;

    if ($Db_type eq "Pg"){
        #$dbh->begin_work();
        #Cannot find the GET_LOCK function into postgres...
        return 1;
    }else{
        my $sth = $dbh->prepare("SELECT GET_LOCK(\"$mutex\",$timeout)");
        $sth->execute();
        my ($res) = $sth->fetchrow_array();
        $sth->finish();
	if ($res eq "0") {
            return 0;
        } elsif ($res eq "1") {
            return 1;
        }
    }
    return undef;
}

# release_lock
# unlock a mysql mutex variable
# parameters : base, mutex
# return value : 1 if the lock was released, 0 if the lock wasn't locked by this thread , and NULL if the named lock didn't exist
# side effects : unlock the mutex, a blocked get_lock may be unblocked
sub release_lock($$) {
    my $dbh = shift;
    my $mutex = shift;

    if ($Db_type eq "Pg"){
        #$dbh->commit();
        return 1;
    }else{
        my $sth = $dbh->prepare("SELECT RELEASE_LOCK(\"$mutex\")");
        $sth->execute();
        my ($res) = $sth->fetchrow_array();
        $sth->finish();
	if ($res eq "0") {
            return 0;
        } elsif ($res eq "1") {
            return 1;
        }
    }
    return undef;
}


sub lock_table($$){
    my $dbh = shift;
    my $tables= shift;

    if ($Db_type eq "Pg"){
        $dbh->begin_work();
    }else{
        my $str = "LOCK TABLE ";
        foreach my $t (@{$tables}){
            $str .= "$t WRITE,";
        }
        chop($str);
        $dbh->do($str);
    }
}


sub unlock_table($){
    my $dbh = shift;

    if ($Db_type eq "Pg"){
        $dbh->commit();
    }else{
        $dbh->do("UNLOCK TABLE");
    }
}


# check_end_job($$$){
sub check_end_of_job($$$$$$$$$$){
    my $base = shift;
    my $job_id = shift;
    my $exit_script_value = shift;
    my $error = shift;
    my $hosts = shift;
    my $remote_host = shift;
    my $remote_port = shift;
    my $user = shift;
    my $launchingDirectory = shift;
    my $server_epilogue_script = shift;

    #lock_table($base,["jobs","job_state_logs","resources","assigned_resources","resource_state_logs","event_logs","challenges","moldable_job_descriptions","job_types","job_dependencies","job_resource_groups","job_resource_descriptions"]);
    lock_table($base,["jobs","job_state_logs","assigned_resources"]);
    my $refJob = get_job($base,$job_id);
    if (($refJob->{'state'} eq "Running") or ($refJob->{'state'} eq "Launching") or ($refJob->{'state'} eq "Suspended") or ($refJob->{'state'} eq "Resuming")){
        OAR::Modules::Judas::oar_debug("[bipbip $job_id] Job $job_id is ended\n");
        set_finish_date($base,$job_id);
        set_job_state($base,$job_id,"Finishing");
        set_job_exit_code($base,$job_id,$exit_script_value) if ($exit_script_value =~ /^\d+$/);
        unlock_table($base);
        my @events;
        if($error == 0){
            OAR::Modules::Judas::oar_debug("[bipbip $job_id] User Launch completed OK\n");
            push(@events, {type => "SWITCH_INTO_TERMINATE_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
            OAR::Tools::notify_tcp_socket($remote_host,$remote_port,"Term");
        }elsif ($error == 1){
            #Prologue error
            my $strWARN = "[bipbip $job_id] error of oarexec prologue";
            push(@events, {type => "PROLOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 2){
            #Epilogue error
            my $strWARN = "[bipbip $job_id] error of oarexec epilogue (job_id = $job_id)";
            push(@events, {type => "EPILOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 3){
            #Oarexec is killed by Leon normaly
            push(@events, {type => "SWITCH_INTO_ERROR_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] the job $job_id was killed by Leon";
            OAR::Modules::Judas::oar_debug("$strWARN\n");
            my $types = OAR::IO::get_job_types_hash($base,$job_id);
            if ((defined($types->{besteffort})) and (defined($types->{idempotent}))){
                if (OAR::IO::is_an_event_exists($base,$job_id,"BESTEFFORT_KILL") > 0){
                    my $new_job_id = OAR::IO::resubmit_job($base,$job_id);
                    oar_warn("[bipbip] We resubmit the job $job_id (new id = $new_job_id) because it is a besteffort and idempotent job.\n");
                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY", string => "[bipbip $job_id] the job $job_id is a besteffort and idempotent job so we resubmit it (new id = $new_job_id)"});
                }
            }
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 4){
            #Oarexec was killed by Leon and epilogue of oarexec is in error
            push(@events, {type => "SWITCH_INTO_ERROR_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] The job $job_id was killed by Leon and oarexec epilogue was in error";
            my $types = OAR::IO::get_job_types_hash($base,$job_id);
            if ((defined($types->{besteffort})) and (defined($types->{idempotent}))){
                if (OAR::IO::is_an_event_exists($base,$job_id,"BESTEFFORT_KILL") > 0){
                    my $new_job_id = OAR::IO::resubmit_job($base,$job_id);
                    oar_warn("[bipbip] We resubmit the job $job_id (new id = $new_job_id) because it is a besteffort and idempotent job.\n");
                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY", string => "[bipbip $job_id] The job $job_id is a besteffort and idempotent job so we resubmit it (new id = $new_job_id)"});
                }
            }
            push(@events, {type => "EPILOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 5){
            #Oarexec is not able to write in the node file
            my $strWARN = "[bipbip $job_id] oarexec cannot create the node file";
            push(@events, {type => "CANNOT_WRITE_NODE_FILE", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 6){
            #Oarexec can not write its pid file
            my $strWARN = "[bipbip $job_id] oarexec cannot write its pid file";
            push(@events, {type => "CANNOT_WRITE_PID_FILE", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 7){
            #Can t get shell of user
            my $strWARN = "[bipbip $job_id] Cannot get shell of user $user, so I suspect node $hosts->[0]";
            push(@events, {type => "USER_SHELL", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 8){
            #Oarexec can not create tmp directory
            my $strWARN = "[bipbip $job_id] oarexec cannot create tmp directory on $hosts->[0] : ".OAR::Tools::get_default_oarexec_directory();
            push(@events, {type => "CANNOT_CREATE_TMP_DIRECTORY", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 10){
            #oarexecuser.sh can not go into working directory
            push(@events, {type => "SWITCH_INTO_ERROR_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] Cannot go into the working directory $launchingDirectory of the job on node $hosts->[0]";
            push(@events, {type => "WORKING_DIRECTORY", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 20){
            #oarexecuser.sh can not write stdout and stderr files
            push(@events, {type => "SWITCH_INTO_ERROR_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] Cannot create .stdout and .stderr files in $launchingDirectory on the node $hosts->[0]";
            push(@events, {type => "OUTPUT_FILES", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 12){
            #oarexecuser.sh can not go into working directory and epilogue is in error
            push(@events, {type => "SWITCH_INTO_ERROR_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] Cannot go into the working directory $launchingDirectory of the job on node $hosts->[0] AND epilogue is in error";
            oar_warn("$strWARN\n");
            push(@events, {type => "WORKING_DIRECTORY", string => $strWARN});
            push(@events, {type => "EPILOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 22){
            #oarexecuser.sh can not create STDOUT and STDERR files and epilogue is in error
            push(@events, {type => "SWITCH_INTO_ERROR_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] Cannot create STDOUT and STDERR files AND epilogue is in error";
            oar_warn("$strWARN\n");
            push(@events, {type => "OUTPUT_FILES", string => $strWARN});
            push(@events, {type => "EPILOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 30){
            #oarexec timeout on bipbip hashtable transfer via SSH
            my $strWARN = "[bipbip $job_id] Timeout SSH hashtable transfer on $hosts->[0]";
            push(@events, {type => "SSH_TRANSFER_TIMEOUT", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 31){
            #oarexec got a bad hashtable dump from bipbip
            my $strWARN = "[bipbip $job_id] Bad hashtable dump on $hosts->[0]";
            push(@events, {type => "BAD_HASHTABLE_DUMP", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 33){
            #oarexec received a SIGUSR1 signal and there was an epilogue error
            push(@events, {type => "SWITCH_INTO_TERMINATE_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] oarexec received a SIGUSR1 signal and there was an epilogue error";
            #add_new_event($base,"STOP_SIGNAL_RECEIVED",$job_id,"$strWARN");
            push(@events, {type => "EPILOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 34){
            #oarexec received a SIGUSR1 signal
            push(@events, {type => "SWITCH_INTO_TERMINATE_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] oarexec received a SIGUSR1 signal; so INTERACTIVE job is ended";
            OAR::Modules::Judas::oar_debug("$strWARN\n");
            #add_new_event($base,"STOP_SIGNAL_RECEIVED",$job_id,"$strWARN");
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
            OAR::Tools::notify_tcp_socket($remote_host,$remote_port,"Term");
        }elsif ($error == 50){
    	    # launching oarexec timeout
            my $strWARN = "[bipbip $job_id] launching oarexec timeout, exit value = $error; the job $job_id is in Error and the node $hosts->[0] is Suspected";
            push(@events, {type => "LAUNCHING_OAREXEC_TIMEOUT", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }elsif ($error == 40){
            #oarexec received a SIGUSR2 signal
            push(@events, {type => "SWITCH_INTO_TERMINATE_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] oarexec received a SIGUSR2 signal; so user process has received a checkpoint signal";
            OAR::Modules::Judas::oar_debug("$strWARN\n");
#            my $types = OAR::IO::get_job_types_hash($base,$job_id);
#            if ((defined($types->{idempotent})) and ($exit_script_value =~ /^\d+$/)){
#                if ($exit_script_value == 0){
#                    my $new_job_id = OAR::IO::resubmit_job($base,$job_id);
#                    oar_warn("[bipbip] We resubmit the job $job_id (new id = $new_job_id) because it was checkpointed and it is of the type 'idempotent'.\n");
#                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY", string => "[bipbip $job_id] The job $job_id was checkpointed and it is of the type 'idempotent' so we resubmit it (new id = $new_job_id)"});
#                }else{
#                    oar_warn("[bipbip] We cannot resubmit the job $job_id even if it was checkpointed and of the type 'idempotent' because its exit code was not 0 ($exit_script_value).\n");
#                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY_CANCELLED", string => "The job $job_id was checkpointed and it is of the type 'idempotent' but its exit code is $exit_script_value"});
#                }
#            }
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
            OAR::Tools::notify_tcp_socket($remote_host,$remote_port,"Term");
        }elsif ($error == 42){
            #oarexec received a user signal
            push(@events, {type => "SWITCH_INTO_TERMINATE_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] oarexec received a SIGURG signal; so user process has received the user defined signal";
            OAR::Modules::Judas::oar_debug("$strWARN\n");
#            my $types = OAR::IO::get_job_types_hash($base,$job_id);
#            if ((defined($types->{idempotent})) and ($exit_script_value =~ /^\d+$/)){
#                if ($exit_script_value == 0){
#                    my $new_job_id = OAR::IO::resubmit_job($base,$job_id);
#                    oar_warn("[bipbip] We resubmit the job $job_id (new id = $new_job_id) because it was signaled and it is of the type 'idempotent'.\n");
#                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY", string => "[bipbip $job_id] The job $job_id was signaled and it is of the type 'idempotent' so we resubmit it (new id = $new_job_id)"});
#                }else{
#                    oar_warn("[bipbip] We cannot resubmit the job $job_id even if it was signaled and of the type 'idempotent' because its exit code was not 0 ($exit_script_value).\n");
#                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY_CANCELLED", string => "The job $job_id was signaled and it is of the type 'idempotent' but its exit code is $exit_script_value"});
#                }
#            }
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
            OAR::Tools::notify_tcp_socket($remote_host,$remote_port,"Term");
	}elsif ($error == 41){
            #oarexec received a SIGUSR2 signal
            push(@events, {type => "SWITCH_INTO_TERMINATE_STATE", string => "[bipbip $job_id] Ask to change the job state"});
            my $strWARN = "[bipbip $job_id] oarexec received a SIGUSR2 signal and there was an epilogue error; so user process has received a checkpoint signal";
            OAR::Modules::Judas::oar_debug("$strWARN\n");
#            my $types = OAR::IO::get_job_types_hash($base,$job_id);
#            if ((defined($types->{idempotent})) and ($exit_script_value =~ /^\d+$/)){
#                if ($exit_script_value == 0){
#                    my $new_job_id = OAR::IO::resubmit_job($base,$job_id);
#                    oar_warn("[bipbip] We resubmit the job $job_id (new id = $new_job_id) because it was checkpointed and it is of the type 'idempotent'.\n");
#                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY", string => "[bipbip $job_id] The job $job_id was checkpointed and it is of the type 'idempotent' so we resubmit it (new id = $new_job_id)"});
#                }else{
#                    oar_warn("[bipbip] We cannot resubmit the job $job_id even if it was checkpointed and of the type 'idempotent' because its exit code was not 0 ($exit_script_value).\n");
#                    push(@events, {type => "RESUBMIT_JOB_AUTOMATICALLY_CANCELLED", string => "[bipbip $job_id] The job $job_id was checkpointed and it is of the type 'idempotent' but its exit code is $exit_script_value"});
#                }
#            }
            push(@events, {type => "EPILOGUE_ERROR", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
            OAR::Tools::notify_tcp_socket($remote_host,$remote_port,"Term");
        }else{
            my $strWARN = "[bipbip $job_id] error of oarexec, exit value = $error; the job $job_id is in Error and the node $hosts->[0] is Suspected; If this job is of type cosystem or deploy, check if the oar server is able to connect to the corresponding nodes, oar-node started";
            push(@events, {type => "EXIT_VALUE_OAREXEC", string => $strWARN});
            job_finishing_sequence($base,$server_epilogue_script,$remote_host,$remote_port,$job_id,\@events);
        }
    }else{
        OAR::Modules::Judas::oar_debug("[bipbip $job_id] I was previously killed or Terminated but I did not know that!!\n");
        unlock_table($base);
    }

    OAR::Tools::notify_tcp_socket($remote_host,$remote_port,"BipBip");
}


sub job_finishing_sequence($$$$$$){
    my ($dbh,
        $epilogue_script,
        $almighty_host,
        $almighty_port,
        $job_id,
        $events) = @_;

    if (defined($epilogue_script)){
        # launch server epilogue
        my $cmd = "$epilogue_script $job_id";
        OAR::Modules::Judas::oar_debug("[JOB FINISHING SEQUENCE] Launching command : $cmd\n");
        my $pid;
        my $exit_value;
        my $signal_num;
        my $dumped_core;
        my $timeout = OAR::Tools::get_default_server_prologue_epilogue_timeout();
        if (is_conf("SERVER_PROLOGUE_EPILOGUE_TIMEOUT")){
            $timeout = get_conf("SERVER_PROLOGUE_EPILOGUE_TIMEOUT"); 
        }
        eval{
            $SIG{PIPE} = 'IGNORE';
            $SIG{ALRM} = sub { die "alarm\n" };
            alarm($timeout);
            $pid = fork();
            if ($pid == 0){
                undef($dbh);
                exec($cmd);
                warn("[ERROR] Cannot find $cmd\n");
                exit(-1);
            }
            my $wait_res = 0;
            # Avaoid to be disrupted by a signal
            while ($wait_res != $pid){
                $wait_res = waitpid($pid,0);
            }
            alarm(0);
            $exit_value  = $? >> 8;
            $signal_num  = $? & 127;
            $dumped_core = $? & 128;
        };
        if ($@){
            if ($@ eq "alarm\n"){
                if (defined($pid)){
                    my ($children,$cmd_name) = OAR::Tools::get_one_process_children($pid);
                    kill(9,@{$children});
                }
                my $str = "[JOB FINISHING SEQUENCE] Server epilogue timeouted (cmd : $cmd)";
                oar_error("$str\n");
                push(@{$events}, {type => "SERVER_EPILOGUE_TIMEOUT", string => $str});
            }
        }elsif ($exit_value != 0){
            my $str = "[JOB FINISHING SEQUENCE] Server epilogue exit code $exit_value (!=0) (cmd : $cmd)";
            oar_error("$str\n");
            push(@{$events}, {type => "SERVER_EPILOGUE_EXIT_CODE_ERROR", string => $str});
        }
    }
    
   
    my $types = OAR::IO::get_job_types_hash($dbh,$job_id);
    if ((!defined($types->{deploy})) and (!defined($types->{cosystem})) and (!defined($types->{noop}))){
        ###############
        # CPUSET PART #
        ###############
        # Clean all CPUSETs if needed
        my $cpuset_field = get_conf("JOB_RESOURCE_MANAGER_PROPERTY_DB_FIELD");
        if (defined($cpuset_field)){
            my $cpuset_name = OAR::IO::get_job_cpuset_name($dbh, $job_id);
            my $openssh_cmd = get_conf("OPENSSH_CMD");
            $openssh_cmd = OAR::Tools::get_default_openssh_cmd() if (!defined($openssh_cmd));
            if (is_conf("OAR_SSH_CONNECTION_TIMEOUT")){
                OAR::Tools::set_ssh_timeout(get_conf("OAR_SSH_CONNECTION_TIMEOUT"));
            }
            my $cpuset_file = get_conf("JOB_RESOURCE_MANAGER_FILE");
            $cpuset_file = OAR::Tools::get_default_cpuset_file() if (!defined($cpuset_file));
            $cpuset_file = "$ENV{OARDIR}/$cpuset_file" if ($cpuset_file !~ /^\//);
            my $cpuset_path = get_conf("CPUSET_PATH");
            my $cpuset_full_path;
            if (defined($cpuset_path) and defined($cpuset_field)){
                $cpuset_full_path = $cpuset_path.'/'.$cpuset_name;
            }
            
            my $job = get_job($dbh, $job_id);
            my $cpuset_nodes = OAR::IO::get_cpuset_values_for_a_moldable_job($dbh,$cpuset_field,$job->{assigned_moldable_job});
            if (defined($cpuset_nodes) and (keys(%{$cpuset_nodes}) > 0)){
                OAR::Modules::Judas::oar_debug("[JOB FINISHING SEQUENCE] [CPUSET] [$job_id] Clean cpuset on each nodes\n");
                my $taktuk_cmd = get_conf("TAKTUK_CMD");
                my $job_user = $job->{job_user};
                my ($job_challenge,$ssh_private_key,$ssh_public_key) = OAR::IO::get_job_challenge($dbh,$job_id);
                $ssh_public_key = OAR::Tools::format_ssh_pub_key($ssh_public_key,$cpuset_full_path,$job->{job_user},$job_user);

                my $cpuset_data_hash = {
                    job_id => $job_id,
                    name => $cpuset_name,
                    nodes => $cpuset_nodes,
                    cpuset_path => $cpuset_path,
                    ssh_keys => {
                                    public => {
                                                file_name => OAR::Tools::get_default_oar_ssh_authorized_keys_file(),
                                                key => $ssh_public_key
                                              },
                                    private => {
                                                file_name => OAR::Tools::get_private_ssh_key_file_name($cpuset_name),
                                                key => $ssh_private_key
                                               }
                                },
                    oar_tmp_directory => OAR::Tools::get_default_oarexec_directory(),
                    user => $job->{job_user},
                    job_user => $job_user,
                    types => $types,
                    resources => undef,
                    node_file_db_fields => undef,
                    node_file_db_fields_distinct_values => undef,
                    array_id            => $job->{array_id},
                    array_index         => $job->{array_index},
                    stdout_file         => OAR::Tools::replace_jobid_tag_in_string($job->{stdout_file},$job_id),
                    stderr_file         => OAR::Tools::replace_jobid_tag_in_string($job->{stderr_file},$job_id),
                    launching_directory => $job->{launching_directory},
                    job_name            => $job->{job_name},
                    walltime_seconds    => undef,
                    walltime            => undef,
                    project             => $job->{project},
                    log_level => OAR::Modules::Judas::get_log_level()
                };
                my ($tag,@bad) = OAR::Tools::manage_remote_commands([keys(%{$cpuset_nodes})],$cpuset_data_hash,$cpuset_file,"clean",$openssh_cmd,$taktuk_cmd,$dbh);
                if ($tag == 0){
                    my $str = "[JOB FINISHING SEQUENCE] [CPUSET] [$job_id] Bad cpuset file : $cpuset_file\n";
                    oar_error($str);
                    push(@{$events}, {type => "CPUSET_MANAGER_FILE", string => $str});
                }elsif ($#bad >= 0){
                    oar_error("[job_finishing_sequence] [$job_id] Cpuset error and register event CPUSET_CLEAN_ERROR on nodes : @bad\n");
                    push(@{$events}, {type => "CPUSET_CLEAN_ERROR", string => "[job_finishing_sequence] OAR suspects nodes for the job $job_id : @bad", hosts => \@bad});
                }
            }
        }
        ####################
        # CPUSET PART, END #
        ####################
    }

    # Execute PING_CHECKER if asked
    if ((is_conf("ACTIVATE_PINGCHECKER_AT_JOB_END")) and (lc(get_conf("ACTIVATE_PINGCHECKER_AT_JOB_END")) eq "yes") and (!defined($types->{deploy})) and (!defined($types->{noop}))){
        my @hosts = OAR::IO::get_job_current_hostnames($dbh,$job_id);
        oar_debug("[job_finishing_sequence] [$job_id] Run pingchecker to test nodes at the end of the job on nodes: @hosts\n");
        my @bad_pingchecker = OAR::PingChecker::test_hosts(@hosts);
        if ($#bad_pingchecker >= 0){
            oar_error("[job_finishing_sequence] [$job_id] PING_CHECKER_NODE_SUSPECTED_END_JOB OAR suspects nodes for the job $job_id : @bad_pingchecker\n");
            push(@{$events}, {type => "PING_CHECKER_NODE_SUSPECTED_END_JOB", string => "[job_finishing_sequence] OAR suspects nodes for the job $job_id : @bad_pingchecker", hosts => \@bad_pingchecker});
        }
    }
    #

    foreach my $e (@{$events}){
        OAR::Modules::Judas::oar_debug("$e->{string}\n");
        if (defined($e->{hosts})){
            add_new_event_with_host($dbh,$e->{type},$job_id,$e->{string},$e->{hosts});
        }else{
            add_new_event($dbh,$e->{type},$job_id,$e->{string});
        }
    }

    if (!defined($types->{noop})){
        # Just to force commit
        lock_table($dbh,["accounting"]);
        unlock_table($dbh);
    }

    OAR::Tools::notify_tcp_socket($almighty_host,$almighty_port,"ChState") if ($#{$events} >= 0);
}

# Generic count of a select query
# args: database ref, query
sub sql_count($$){
    my $dbh = shift;
    my $query = shift;

    my $sth = $dbh->prepare("   SELECT count(*) $query");
    $sth->execute();
    my ($count) = $sth->fetchrow_array();
    return $count ;
}

# Generic select query
# args: database ref, query, limit and offset
sub sql_select($$$$){
    my $dbh = shift;
    my $query = shift;
    my $limit = shift;
    my $offset = shift;

    if ($offset != 0) {$offset = "OFFSET $offset";}
    else {$offset = ""};

    my $sth = $dbh->prepare("SELECT * $query LIMIT $limit $offset");
    $sth->execute();
    my @res = ();
    while (my $ref = $sth->fetchrow_hashref()) {
        push(@res, $ref);
    }
    return(\@res);
}

# inserts_from_file
# adds  to the table assigned_resources
# use insert from file to obtain better performance
# parameters : base, table, values,
# values is a string of values delimited by commas and row delimited by \n
# ex values: 1,5,yop\n5,6,poy\n
# return value : /
sub inserts_from_file($$$) {
  my $dbh = shift;
  my $table = shift;
  my $values = shift;
  my $query = "";
  my $filename = "/tmp/oar_insert_".$table.".req";
  open(INSERTOUTFILE, ">$filename");
  print INSERTOUTFILE $values;
  close(INSERTOUTFILE);
 
  if ($Db_type eq "mysql") {
    $query = "LOAD DATA LOCAL INFILE '$filename' INTO TABLE $table";
  } else {
    $query = "COPY $table FROM '$filename' WITH DELIMITER AS ','";
  }

  $dbh->do($query);
}

# END OF THE MODULE
return 1;