-
Notifications
You must be signed in to change notification settings - Fork 4
/
sqlog-db-util
executable file
·1705 lines (1457 loc) · 55.4 KB
/
sqlog-db-util
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
###############################################################################
# $Id$
#******************************************************************************
# Copyright (C) 2007-2009 Lawrence Livermore National Security, LLC.
# Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
# Written by Adam Moody <[email protected]> and
# Mark Grondona <[email protected]>
#
# UCRL-CODE-235340.
#
# This file is part of sqlog.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
###############################################################################
#
# sqlog-db-util - SQLOG job database maintenance.
#
###############################################################################
use strict;
use lib qw(); # Required for _perl_libpaths RPM option
use DBI;
use Digest::SHA1 qw/ sha1_hex /;
use Getopt::Long qw/ :config gnu_getopt ignore_case /;
use File::Basename;
use Hostlist;
use Time::HiRes qw( gettimeofday );
# This file contains the SQL statements needed
# to set up a 'slurm_job_log' table in a 'slurm' DB
# on a MySQL server.
#
# It can also be used to backfill the database by
# inserting records from a list of slurm job completion
# logfiles.
#
# Adam Moody <[email protected]>
# Required for _path_env_var RPM option
$ENV{PATH} = '/bin:/usr/bin:/usr/sbin';
my %conf = ();
##############################
# Usage:
#############################
my $progname = basename $0;
$conf{usage} = <<EOF
Usage: $progname [OPTIONS]... [FILES]...
Create SLURM job completion log database along with user accounts to
access it, and/or backfill the database from SLURM job completion
logfiles.
-h, --help Display this message.
-i, --info Print information about current DB.
-v, --verbose Be verbose.
-d, --drop=V Drop tables for version V={1,2} of database schema.
-c, --create Create slurm database, users, and latest version
of database tables.
-b, --backfill Backfill database from all SLURM joblog files in ARGV.
-x, --convert Convert data from database schema version 1 to version 2.
-B, --backup=RANGE Copy data from tables over RANGE to a file in a format
readable by the --backfill option. RANGE can be
specified as "all" or a date range in the form
DATE..DATE. DATE must be in a format of
'yyyy-mm-dd hh:mm:ss'.
-o, --obfuscate Obfuscates usernames, userids, and jobnames during
backup operations, which is useful for sharing system
joblogs with offsite collaborators.
-p, --prune=DATE Prune database of all jobs with start times older
than DATE; write such records to a file. DATE must
be in format of 'yyyy-mm-dd hh:mm:ss'
-C, --cores-per-node=N
During --backfill, --convert, --backup, or --prune,
specify the number of cores per node used to compute
corecount field on clusters that allocate whole
nodes to jobs.
--notrack Disable per-job node tracking for jobs inserted during
--convert or --backfill operations.
--delay-index Temporarily disable node tracking indicies for jobs
inserted during convert of backfill operations.
--recalc-nodecnt When backfilling, do not use NodeCnt as stored in the
joblog file. Instead recalculate based on nodelist.
-L, --localhost Connect to DB over localhost instead of configured
SQL host.
EOF
;
sub usage { print STDERR $conf{usage}; exit 0; }
#############################
# Read Config File.
#############################
# Config Defaults
$conf{confdir} = "/etc/slurm";
$conf{db} = "slurm";
$conf{sqlhost} = "sqlhost";
$conf{ro}{sqluser} = "slurm_read";
$conf{ro}{sqlpass} = "";
$conf{rw}{sqluser} = "slurm";
$conf{rw}{sqlpass} = "";
$conf{rw}{sqlnetwork} = "192.168.%.%";
# enables / disables node tracking per job in version 2 schema
$conf{track} = 1;
read_config ();
##############################
# Parse Command-line
#############################
# set defaults and read in command-line options
$conf{verbose} = 0;
$conf{info} = 0;
$conf{drop} = 0;
$conf{create} = 0;
$conf{backfill} = "";
$conf{convert} = 0; # convert data in version 1 table to version 2
$conf{backup} = 0;
$conf{obfuscate} = 0;
$conf{prune} = undef;
# used to set corecount field during convert or backfill
# for machines which allocate whole nodes
$conf{cores} = undef;
# if set to 0, remove node-tracking indicies, insert nodes,
# and renable indicies
$conf{indicies} = 1;
$conf{localhost} = 0;
GetOptions (
"help|h" => \$conf{help},
"verbose|v+" => \$conf{verbose},
"info|i" => \$conf{info},
"drop|d=i" => \$conf{drop},
"create|c" => \$conf{create},
"backfill|b" => \$conf{backfill},
"convert|x" => \$conf{convert},
"backup|B=s" => \$conf{backup},
"obfuscate|o" => \$conf{obfuscate},
"prune|p=s" => \$conf{prune},
"cores-per-node|C=i" => \$conf{cores},
"notrack" => sub { $conf{track} = 0; },
"delay-index" => sub { $conf{indicies} = 0; },
"localhost|L" => \$conf{localhost},
"recalc-nodecnt" => \$conf{recalculate_nodecount},
) or usage ();
if (!$conf{create} && !$conf{convert} && !$conf{drop} &&
!$conf{backfill} && !$conf{backup} && !$conf{prune} &&
!$conf{info} && !$conf{help}) {
log_error ("Specify at least one of " .
"--{create,convert,drop,backfill,backup,prune,info}.\n");
usage ();
}
if ($conf{help}) {
usage ();
}
#############################
# Attempt to connect to slurm database
#############################
# test whether slurm db already exists by trying to connect
my $dbh = connect_db_rw ();
# backup table data -- writes records to a file readable by backfill
# global variables to help obfuscate user and jobnames
my %obfuscate = ();
my $num_users = 0;
my $num_jobs = 0;
if ($conf{backup} or defined $conf{prune}) {
# check that we have a db connection
if (!$dbh) {
log_fatal ("Data dump requested, but connection to database failed!\n")
}
# check that user gave us exactly one file name
if (@ARGV != 1) {
log_fatal ("You must specify a date range and" .
" a filename to append data to.\n");
}
my $joblog = shift @ARGV;
# dump data to joblog file
if (table_exists ($dbh, "slurm_job_log")) {
dump_slurm_joblog_table (1, $dbh, $joblog);
}
if (table_exists ($dbh, "jobs")) {
dump_slurm_joblog_table (2, $dbh, $joblog);
}
}
#
# Drop existing tables
#
if ($conf{drop}) {
if ($dbh) {
if ($conf{drop} == 1) {
log_verbose ("drop: Dropping version 1 tables\n");
drop_slurm_joblog_table_v1 ($dbh);
} elsif ($conf{drop} == 2) {
log_verbose ("drop: Dropping version 2 tables\n");
drop_slurm_joblog_table_v2 ($dbh);
} else {
log_verbose ("drop: Unknown schema version: $conf{drop}\n");
}
$dbh = disconnect_db_rw ();
} else {
log_verbose ("drop: No existing slurm DB to drop\n");
}
# TODO: should we also delete the slurm db and users
# (i.e., undo everything create does?)
}
#
# Create database
#
if ($conf{create} && $dbh) {
# if version 2 tables do not exist, create them
if (not table_exists ($dbh, "jobs")) {
log_verbose ("create: Creating version 2 tables.\n");
create_slurm_joblog_table_v2 ($dbh);
} else {
log_verbose ("create: SLURM database already exists.\n");
}
} elsif ($conf{create} && !$dbh) {
# the db may not exist (couldn't connect), try to create it
create_db_and_slurm_users ();
# try to connect again
$dbh = connect_db_rw()
or log_fatal ("create: Failed to connect to SLURM DB after create!\n");
# create version 2 from the beginning on a brand new install
log_verbose ("create: Creating version 2 tables.\n");
create_slurm_joblog_table_v2 ($dbh);
}
#
# Convert slurm_job_log table to version 2
# (add corecount and extend nodelist columns)
#
if ($conf{convert}) {
#
# Attempt to convert table to version 2, if conversion fails
# print an error.
#
# If the table has already been converted, a message is printed
# and no action is taken
#
if (!$dbh) {
log_fatal ("convert: Conversion requested," .
" but connection to database failed.\n")
}
log_verbose ("convert: Initiating conversion from" .
" version 1 to version 2 tables.\n");
if (!convert_slurm_joblog_table_from_v1_to_v2 ($dbh)) {
log_fatal ("convert: SLURM job log table conversion failed.\n");
}
}
#
# Backfill from logfiles
#
if ($conf{backfill}) {
if (!$dbh) {
log_fatal ("backfill: Backfill requested," .
" but connection to database failed!\n")
}
# if we find the version 2 schema, backfill to it
# otherwise, if we find the version 1 schema, backfill to it
# if we find neither, throw an error
if (table_exists ($dbh, "jobs")) {
backfill_slurm_joblog_table_to_v2 ($dbh, @ARGV);
} elsif (table_exists ($dbh, "slurm_job_log")) {
backfill_slurm_joblog_table_to_v1 ($dbh, @ARGV);
} else {
log_fatal ("backfill: Unknown schema version.\n");
}
}
if ($conf{info}) {
show_info ();
}
disconnect_db_rw ();
exit 0;
#############################
# Support functions
#############################
sub db_host_string
{
return $conf{localhost} ? "localhost" : $conf{sqlhost};
}
sub connect_db_rw
{
my $host = db_host_string ();
my $cstr = "DBI:mysql(PrintError=>0):" .
"database=$conf{db};host=$host:";
my $dbh = DBI->connect($cstr, $conf{rw}{sqluser}, $conf{rw}{sqlpass})
or log_verbose ("Unable to connect to MySQL DB as ",
"$conf{rw}{sqluser}\@$conf{sqlhost}: ", $DBI::errstr, "\n");
$conf{dbh}{rw} = $dbh;
return ($dbh);
}
sub disconnect_db_rw
{
return if !$conf{dbh}{rw};
$conf{dbh}{rw}->disconnect;
return $conf{dbh}{rw} = undef;
}
sub connect_db_root
{
my $host = db_host_string ();
my $str = "DBI:mysql(PrintError=>0):host=$host;";
$conf{dbh}{root} = DBI->connect ($str, "root", $conf{rw}{rootpass})
or log_fatal ("Unable to connect to MySQL DB as root\@$host: ",
$DBI::errstr, "\n");
return ($conf{dbh}{root});
}
# returns 1 if table exists, 0 otherwise
sub table_exists
{
my $dbh = shift @_;
my $table = shift @_;
# check whether our database has a table by the proper name
my $sth = $dbh->prepare("SHOW TABLES;");
if ($sth->execute()) {
while (my ($name) = $sth->fetchrow_array()) {
if ($name eq $table) { return 1; }
}
}
# didn't find it
return 0;
}
sub read_config
{
my $ro = "$conf{confdir}/sqlog.conf";
my $rw = "$conf{confdir}/slurm-joblog.conf";
# First read sqlog config to get SQLHOST and SQLDB
# (ignore SQLUSER/SQLPASS)
unless (my $rc = do $ro) {
log_fatal ("Couldn't parse $ro: $@\n") if $@;
log_fatal ("couldn't run $ro\n") if (defined $rc && !$rc);
}
$conf{db} = $conf::SQLDB if (defined $conf::SQLDB);
$conf{sqlhost} = $conf::SQLHOST if (defined $conf::SQLHOST);
$conf{ro}{sqluser} = $conf::SQLUSER if (defined $conf::SQLUSER);
$conf{ro}{sqlpass} = $conf::SQLPASS if (defined $conf::SQLPASS);
# enable / disable per job node tracking
$conf{track} = $conf::TRACKNODES if (defined $conf::TRACKNODES);
undef $conf::SQLUSER;
undef $conf::SQLPASS;
# Now read slurm-joblog.conf
-r $rw || log_fatal ("Unable to read required config file: $rw.\n");
unless (my $rc = do $rw) {
log_fatal ("Couldn't parse $rw: $@\n") if $@;
log_fatal ("couldn't run $rw\n") if (defined $rc && !$rc);
}
$conf{rw}{sqluser} = $conf::SQLUSER if (defined $conf::SQLUSER);
$conf{rw}{sqlpass} = $conf::SQLPASS if (defined $conf::SQLPASS);
$conf{rw}{rootpass} = $conf::SQLROOTPASS if (defined $conf::SQLROOTPASS);
$conf{rw}{sqlnetwork} = $conf::SQLNETWORK if (defined $conf::SQLNETWORK);
@{$conf{rw}{hosts}} = @conf::SQLRWHOSTS if (@conf::SQLRWHOSTS);
my %seen;
@{$conf{rw}{hosts}} = grep {$_ && !$seen{$_}++} @{$conf{rw}{hosts}};
}
# Connect to MySQL as root user to build slurm db
# and insert slurm and slurm_read users
sub create_db_and_slurm_users
{
my $dbh = connect_db_root ()
or log_fatal ("Couldn't connect to database as root\n");
#
# Abort if slurm_job_log table already exists.
if (table_exists ($dbh, "slurm_job_log") or table_exists ($dbh, "jobs")) {
log_msg ("create: SLURM job log table exists. No create necessary.\n");
return;
}
#############################
# Create slurm db / table
#############################
log_verbose ("Creating slurm DB\n");
do_sql ($dbh, "CREATE DATABASE IF NOT EXISTS $conf{db};");
#############################
# Set up slurm (r/w) and slurm_read (r/o) access
#############################
# Switch to management databases
do_sql($dbh, "USE mysql;");
log_verbose ("Dropping previous slurm joblog db users and privileges.\n");
drop_slurm_users ($dbh);
# set up permissions for different users of slurm database
for my $host (@{$conf{rw}{hosts}}, "localhost") {
my $user = $conf{rw}{sqluser};
log_verbose ("Granting rw privileges to $user on $host\n");
do_sql ($dbh,
"GRANT ALL ON $conf{db}.* TO" .
" '$user'\@'$host'" .
" IDENTIFIED BY '$conf{rw}{sqlpass}'");
}
log_verbose ("Granting readonly privs to $conf{ro}{sqluser} " .
"on $conf{rw}{sqlnetwork}.\n");
do_sql ($dbh,
"GRANT SELECT ON $conf{db}.* TO" .
" $conf{ro}{sqluser}\@'$conf{rw}{sqlnetwork}'" .
" IDENTIFIED BY ''");
# flush privileges to make our changes current
log_verbose ("FLUSH PRIVILEGES\n");
do_sql($dbh, "FLUSH PRIVILEGES;");
# we're done
log_verbose ("Done creating slurm joblog DB.\n");
}
sub show_info
{
my $dbh = connect_db_rw () or return;
# determine what schema version we're at
my $version = "UKNOWN";
if (table_exists ($dbh, "jobs")) {
$version = 2;
} elsif (table_exists ($dbh, "slurm_job_log")) {
$version = 1;
}
&log_verbose ("Connected to joblog database version $version\n");
# count the number of jobs in version 1
my $count_v1 = 0;
my $stmt = "SELECT COUNT(*) FROM `$conf{db}`.`slurm_job_log`;";
my $sth = $dbh->prepare ($stmt) or return;
if ($sth->execute ()) { ($count_v1) = $sth->fetchrow_array; }
# count the number of jobs in version 2
my $count_v2 = 0;
$stmt = "SELECT COUNT(*) FROM `$conf{db}`.`jobs`;";
$sth = $dbh->prepare ($stmt) or return;
if ($sth->execute ()) { ($count_v2) = $sth->fetchrow_array; }
# add the job counts to get the total
my $count = $count_v1 + $count_v2;
# now we're ready to print
log_msg ("Information for SLURM job log DB:\n");
print "DB Host: $conf{sqlhost}\n";
print "DB User: $conf{ro}{sqluser}\n";
print "RW User: $conf{rw}{sqluser}\n";
print "SLURM DB: $conf{db}\n";
print "Version: $version\n";
print "Job count: $count\n";
return;
}
sub drop_slurm_users
{
my $dbh = shift @_;
my $stmt = "SELECT user,host from mysql.user;";
my @oldusers = ();
my $sth = $dbh->prepare ($stmt) or return;
$sth->execute () or return;
while ((my $a = $sth->fetchrow_arrayref)) {
if ($a->[0] ne "$conf{ro}{sqluser}" &&
$a->[0] ne "$conf{rw}{sqluser}" ) {
next;
}
push (@oldusers, "$a->[0]\@'$a->[1]'");
}
do_sql ($dbh, "DROP USER " . join (", ", @oldusers)) if @oldusers;
}
# execute (do) sql statement on dbh
sub do_sql {
my ($dbh, $stmt) = @_;
log_debug ("SQL: [$stmt]\n");
$dbh->do ($stmt);
if (not $dbh->do ($stmt)) {
log_error ("FAILED SQL: $stmt ERROR: " . $dbh->errstr . "\n");
return 0;
}
return 1;
}
####################
# Schema version 1 functions
####################
# drop the table
sub drop_slurm_joblog_table_v1
{
my $dbh = shift @_;
my $success = 1;
# switch to the slurm db
if (not do_sql ($dbh, "USE $conf{db};")) { $success = 0; }
# now drop the tables
log_verbose ("drop: Dropping existing 'slurm_job_log' table\n");
my $sql = "DROP TABLE `slurm_job_log`;";
if (not do_sql ($dbh, $sql)) { $success = 0; }
return $success;
}
# build the table
sub create_slurm_joblog_table_v1
{
my $dbh = shift @_;
my $success = 1;
# switch to the slurm db
if (not do_sql ($dbh, "USE $conf{db};")) { $success = 0; }
# keep this schema around for historical record
# (could enable one to build a v1 table if so desired)
my $sql = "CREATE TABLE IF NOT EXISTS slurm_job_log (
id int(10) NOT NULL AUTO_INCREMENT,
jobid int(10) NOT NULL,
username char(100) NOT NULL,
userid int(10) NOT NULL,
jobname char(100) NOT NULL,
jobstate char(25) NOT NULL,
partition char(25) NOT NULL,
timelimit int(10) NOT NULL,
starttime datetime NOT NULL,
endtime datetime NOT NULL,
nodelist varchar(1024) NOT NULL,
nodecount int(10) NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX jobid (jobid,starttime),
INDEX username (username)
) ENGINE=MyISAM;";
if (not do_sql ($dbh, $sql)) { $success = 0; }
return $success;
}
# given hash of values, create mysql values string for insert statement
sub value_string_v1
{
my $dbh = shift @_;
my $h = shift @_;
my @parts = ();
push @parts, "NULL";
push @parts, $dbh->quote($h->{JobId});
push @parts, $dbh->quote($h->{UserName});
push @parts, $dbh->quote($h->{UserNumb});
push @parts, $dbh->quote($h->{Name});
push @parts, $dbh->quote($h->{JobState});
push @parts, $dbh->quote($h->{Partition});
push @parts, $dbh->quote($h->{TimeLimit});
push @parts, $dbh->quote($h->{StartTime});
push @parts, $dbh->quote($h->{EndTime});
push @parts, $dbh->quote($h->{NodeList});
push @parts, $dbh->quote($h->{NodeCnt});
return "(" . join(',', @parts) . ")";
}
# do a batch insert to be more efficient
sub insert_values_v1
{
my $dbh = shift @_;
my @values = @_;
while (@values) {
my @subvalues = ();
for (my $i = 0; $i < 50 and @values; $i++) {
push @subvalues, shift @values;
}
my $sql = "INSERT IGNORE INTO `$conf{db}`.`slurm_job_log` VALUES " .
join(",", @subvalues) . ";";
#log_debug ("SQL: $sql\n");
$dbh->do($sql);
}
}
# given a dbh and list of slurm job completion logfiles,
# insert them into the dbh
sub backfill_slurm_joblog_table_to_v1
{
my $dbh = shift @_;
my @files = @_;
my $success = 1;
# switch to the slurm db
if (not do_sql ($dbh, "USE $conf{db};")) { $success = 0; }
# if our new table does not exist, create it
if (not table_exists ($dbh, "slurm_job_log")) {
if (not create_slurm_joblog_table_v1($dbh)) {
return 0;
}
}
log_error ("No files to backfill!\n") if (!@files);
foreach my $file (@files) {
my @values = ();
my $count = 0;
my $skipped = 0;
my $f = $file;
$f = "gzip -dc $f | " if ($f =~ /\.gz$/);
open (IN, $f) or log_error ("Failed to open \"$file\":$!\n"), next;
while (my $line = <IN>) {
chomp $line;
my @parts = split(" ", $line);
my %h = ();
foreach my $part (@parts) {
my ($key, $value) = split("=", $part);
$h{$key} = $value;
}
# Some very old joblog files may have the incorrect
# datetime format. Unfortunately, the year wasn't
# included in these, so we have to drop these entries :-(
if (defined $h{StartTime} and $h{StartTime} =~ m{^\d\d/\d\d-}) {
$skipped++;
next;
}
# convert from slurm log to format for MySQL
if (defined $h{"UserId"}) {
my $userid = $h{"UserId"};
my ($username, $usernumb) = ($userid =~ /(.+)\((\d+)\)/);
if (defined $username and defined $usernumb) {
$h{"UserName"} = $username;
$h{"UserNumb"} = $usernumb;
}
}
if (defined $h{"StartTime"}) {
$h{"StartTime"} =~ s/T/ /;
}
if (defined $h{"EndTime"}) {
$h{"EndTime"} =~ s/T/ /;
}
push @values, value_string_v1($dbh, \%h);
if (@values > 100) {
insert_values_v1($dbh, @values);
@values = ();
}
$count++;
}
insert_values_v1($dbh, @values);
log_verbose ("Backfilled $count jobs from file $file\n");
log_error ("Skipped $skipped job(s) from file $file because of ",
"old date format\n") if $skipped;
close(IN);
}
return $success;
}
####################
# Schema version 2 functions
####################
# cache for name ids, saves us from hitting the database
# over and over at the cost of more memory
my %IDcache = ();
%{$IDcache{nodes}} = ();
# return the auto increment value for the last inserted record
sub get_last_insert_id
{
my $dbh = shift @_;
my $id = undef;
my $sql = "SELECT LAST_INSERT_ID();";
my $sth = $dbh->prepare($sql);
if ($sth->execute()) {
($id) = $sth->fetchrow_array();
} else {
log_error ("Fetching last id: $sql\n");
}
return $id;
}
# given a table and name, read id for name from table
# and add to id cache if found
sub read_id
{
my $dbh = shift @_;
my $table = shift @_;
my $name = shift @_;
my $id = undef;
# if name is not set, don't try to look it up in hash, just return undef
if (not defined $name) { return $id; }
if (not defined $IDcache{$table}) { %{$IDcache{$table}} = (); }
if (not defined $IDcache{$table}{$name}) {
my $q_name = $dbh->quote($name);
my $sql = "SELECT * FROM `$table` WHERE `name` = $q_name;";
my $sth = $dbh->prepare($sql);
if ($sth->execute ()) {
my ($table_id, $table_name) = $sth->fetchrow_array ();
if (defined $table_id and defined $table_name) {
$IDcache{$table}{$name} = $table_id;
$id = $table_id;
}
} else {
log_error ("Reading record: $sql --> " . $dbh->errstr . "\n");
}
} else {
$id = $IDcache{$table}{$name};
}
return $id;
}
# insert name into table if it does not exist, and return its id
sub read_write_id
{
my $dbh = shift @_;
my $table = shift @_;
my $name = shift @_;
# if name isn't set, set it to the empty string
# DON'T do this in slurm-joblog, it will fail and
# write to the joblog instead
if (not defined $name) { $name = ""; }
# attempt to read the id first, if not found,
# insert it and return the last insert id
my $id = read_id($dbh, $table, $name);
if (not defined $id) {
my $q_name = $dbh->quote($name);
my $sql = "INSERT IGNORE INTO `$table` (`id`,`name`)" .
" VALUES (NULL,$q_name);";
my $sth = $dbh->prepare($sql);
if ($sth->execute ()) {
# user read_id here instead of get_last_insert_id
# to avoid race conditions
$id = read_id ($dbh, $table, $name);
if (not defined $id) {
log_error ("Error inserting new record (id undefined): $sql\n");
$id = 0;
} elsif ($id == 0) {
log_error ("Error inserting new record (id=0): $sql\n");
$id = 0;
}
} else {
log_error ("Error inserting new record: $sql --> " .
$dbh->errstr . "\n");
$id = 0;
}
}
return $id;
}
# given a reference to a list of nodes,
# read their ids from the nodes table and add them to the id cache
sub read_node_ids
{
my $dbh = shift @_;
my $nodes_ref = shift @_;
my $success = 1;
# build list of nodes not in our cache
my @missing_nodes = ();
foreach my $node (@$nodes_ref) {
if (not defined $IDcache{nodes}{$node}) { push @missing_nodes, $node; }
}
# if any missing nodes, try to look up their values
if (@missing_nodes > 0) {
my @q_nodes = map $dbh->quote($_), @missing_nodes;
my $in_nodes = join(",", @q_nodes);
my $sql = "SELECT * FROM `nodes` WHERE `name` IN ($in_nodes);";
my $sth = $dbh->prepare($sql);
if ($sth->execute ()) {
while (my ($table_id, $table_name) = $sth->fetchrow_array ()) {
$IDcache{nodes}{$table_name} = $table_id;
}
} else {
log_error ("Reading nodes: $sql --> " . $dbh->errstr . "\n");
$success = 0;
}
}
return $success;
}
# given a reference to a list of nodes,
# insert them into the nodes table and add their ids to the id cache
sub read_write_node_ids
{
my $dbh = shift @_;
my $nodes_ref = shift @_;
my $success = 1;
# read node_ids for these nodes into our cache
read_node_ids($dbh, $nodes_ref);
# if still missing nodes, we need to insert them
my @missing_nodes = ();
foreach my $node (@$nodes_ref) {
if (not defined $IDcache{nodes}{$node}) { push @missing_nodes, $node; }
}
if (@missing_nodes > 0) {
my @q_nodes = map $dbh->quote($_), @missing_nodes;
my $values = join("),(", @q_nodes);
my $sql = "INSERT IGNORE INTO `nodes` (`name`) VALUES ($values);";
my $sth = $dbh->prepare($sql);
if (not $sth->execute ()) {
log_error ("Inserting nodes: $sql --> " . $dbh->errstr . "\n");
$success = 0;
}
# fetch ids for just inserted nodes
read_node_ids($dbh, $nodes_ref);
}
return $success;
}
# given a job_id and a nodelist,
# insert jobs_nodes records for each node used in job_id
sub insert_job_nodes
{
my $dbh = shift @_;
my $job_id = shift @_;
my $nodelist = shift @_;
my $success = 1;
if (defined $job_id and defined $nodelist and $nodelist ne "") {
my $q_job_id = $dbh->quote($job_id);
# clean up potentially bad nodelist
if ($nodelist =~ /\[/ and $nodelist !~ /\]/) {
# found an opening bracket, but no closing bracket,
# nodelist is probably incomplete
# chop back to last ',' or '-' and replace with a ']'
$nodelist =~ s/[,-]\d+$/\]/;
}
# get our nodeset
my @nodes = Hostlist::expand($nodelist);
# this will fill our node_id cache
read_write_node_ids($dbh, \@nodes);
# get the node_id for each node
my @values = ();
foreach my $node (@nodes) {
if (defined $IDcache{nodes}{$node}) {
my $q_node_id = $dbh->quote($IDcache{nodes}{$node});
push @values, "($q_job_id,$q_node_id)";
}
}
# if we have any nodes for this job, insert them
if (@values > 0) {
my $sql = "INSERT DELAYED IGNORE INTO `jobs_nodes`" .
" (`job_id`,`node_id`)" .
" VALUES " . join(",", @values) . ";";
my $sth = $dbh->prepare($sql);
if (not $sth->execute ()) {
log_error ("Inserting jobs_nodes records for job id" .
" $job_id: $sql --> " . $dbh->errstr . "\n");
$success = 0;
}
}
}
return $success;
}
# compute time since epoch, attempt to account for DST changes via timelocal
sub get_seconds
{
my ($date) = @_;
use Time::Local;
my ($y, $m, $d, $H, $M, $S) = ($date =~ /(\d\d\d\d)\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)/);
$y -= 1900;
$m -= 1;
return timelocal ($S, $M, $H, $d, $m, $y);
}
# given hash of values, create mysql values string for insert statement
sub value_string_v2
{
my $dbh = shift @_;
my $h = shift @_;
# given start and end times, compute the number of seconds
# the job ran for
# TODO: unsure whether this correctly handles jobs that
# straddle DST changes
my $seconds = 0;
if (defined $h->{StartTime} and $h->{StartTime} !~ /^\s*$/ and
defined $h->{EndTime} and $h->{EndTime} !~ /^\s*$/)
{
my $start = get_seconds($h->{StartTime});
my $end = get_seconds($h->{EndTime});
$seconds = $end - $start;
if ($seconds < 0) { $seconds = 0; }
}
# if Procs is not set, but cores is specified and NodeCnt is set,
# compute Procs
# (assumes all processors on the node were allocated to the job,
# only use for clusters which use whole-node allocation)
if (not defined $h->{Procs} and defined $conf{cores} and
defined $h->{NodeCnt}
)
{
$h->{Procs} = $h->{NodeCnt} * $conf{cores};
}
# get id values
my $username_id = read_write_id($dbh, "usernames", $h->{UserName});
my $jobname_id = read_write_id($dbh, "jobnames", $h->{Name});
my $jobstate_id = read_write_id($dbh, "jobstates", $h->{JobState});
my $partition_id = read_write_id($dbh, "partitions", $h->{Partition});
if (not defined $username_id or
not defined $jobname_id or
not defined $jobstate_id or