-
Notifications
You must be signed in to change notification settings - Fork 203
/
Jobs.pm
2372 lines (2065 loc) · 91.9 KB
/
Jobs.pm
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
# Copyright 2015-2021 SUSE LLC
# SPDX-License-Identifier: GPL-2.0-or-later
package OpenQA::Schema::Result::Jobs;
use Mojo::Base 'DBIx::Class::Core', -signatures;
use Try::Tiny;
use Mojo::JSON 'encode_json';
use Fcntl;
use DateTime;
use OpenQA::Constants qw(WORKER_COMMAND_ABORT WORKER_COMMAND_CANCEL);
use OpenQA::Log qw(log_trace log_debug log_info log_warning log_error);
use OpenQA::Utils (
qw(parse_assets_from_settings locate_asset),
qw(resultdir assetdir read_test_modules find_bugref random_string),
qw(run_cmd_with_log_return_error needledir testcasedir gitrepodir find_video_files)
);
use OpenQA::App;
use OpenQA::Jobs::Constants;
use OpenQA::JobDependencies::Constants;
use OpenQA::Markdown 'markdown_to_html';
use OpenQA::Setup;
use OpenQA::ScreenshotDeletion;
use File::Basename qw(basename dirname);
use File::Copy::Recursive qw();
use File::Spec::Functions 'catfile';
use DBI qw(:sql_types);
use File::Path ();
use DBIx::Class::Timestamps 'now';
use File::Temp 'tempdir';
use Mojo::Collection;
use Mojo::File qw(tempfile path);
use Mojo::JSON 'decode_json';
use Data::Dump 'dump';
use Text::Diff;
use OpenQA::File;
use OpenQA::Parser 'parser';
use OpenQA::WebSockets::Client;
use List::Util qw(any);
use Scalar::Util qw(looks_like_number);
# The state and results constants are duplicated in the Python client:
# if you change them or add any, please also update const.py.
# scenario keys w/o MACHINE. Add MACHINE when desired, commonly joined on
# other keys with the '@' character
use constant SCENARIO_KEYS => (qw(DISTRI VERSION FLAVOR ARCH TEST));
use constant SCENARIO_WITH_MACHINE_KEYS => (SCENARIO_KEYS, 'MACHINE');
# job settings which are defined directly as column of the jobs table
use constant MAIN_SETTINGS => qw(DISTRI VERSION FLAVOR ARCH TEST MACHINE BUILD);
__PACKAGE__->table('jobs');
__PACKAGE__->load_components(qw(InflateColumn::DateTime FilterColumn Timestamps));
__PACKAGE__->add_columns(
id => {
data_type => 'bigint',
is_auto_increment => 1,
},
result_dir => { # this is the directory below testresults
data_type => 'text',
is_nullable => 1
},
archived => {
data_type => 'boolean',
default_value => 0,
},
state => {
data_type => 'varchar',
default_value => SCHEDULED,
},
priority => {
data_type => 'integer',
default_value => DEFAULT_JOB_PRIORITY,
},
result => {
data_type => 'varchar',
default_value => NONE,
},
reason => {
data_type => 'varchar',
is_nullable => 1,
},
clone_id => {
data_type => 'bigint',
is_foreign_key => 1,
is_nullable => 1
},
blocked_by_id => {
data_type => 'bigint',
is_foreign_key => 1,
is_nullable => 1
},
TEST => {
data_type => 'text'
},
DISTRI => {
data_type => 'text',
default_value => ''
},
VERSION => {
data_type => 'text',
default_value => ''
},
FLAVOR => {
data_type => 'text',
default_value => ''
},
ARCH => {
data_type => 'text',
default_value => ''
},
BUILD => {
data_type => 'text',
default_value => ''
},
MACHINE => {
data_type => 'text',
is_nullable => 1
},
group_id => {
data_type => 'bigint',
is_foreign_key => 1,
is_nullable => 1
},
assigned_worker_id => {
data_type => 'bigint',
is_foreign_key => 1,
is_nullable => 1
},
t_started => {
data_type => 'timestamp',
is_nullable => 1,
},
t_finished => {
data_type => 'timestamp',
is_nullable => 1,
},
logs_present => {
data_type => 'boolean',
default_value => 1,
},
passed_module_count => {
data_type => 'integer',
default_value => 0,
},
failed_module_count => {
data_type => 'integer',
default_value => 0,
},
softfailed_module_count => {
data_type => 'integer',
default_value => 0,
},
skipped_module_count => {
data_type => 'integer',
default_value => 0,
},
externally_skipped_module_count => {
data_type => 'integer',
default_value => 0,
},
scheduled_product_id => {
data_type => 'bigint',
is_foreign_key => 1,
is_nullable => 1,
},
result_size => {
data_type => 'bigint',
is_foreign_key => 1,
is_nullable => 1,
},
);
__PACKAGE__->add_timestamps;
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(settings => 'OpenQA::Schema::Result::JobSettings', 'job_id');
__PACKAGE__->has_one(worker => 'OpenQA::Schema::Result::Workers', 'job_id', {cascade_delete => 0});
__PACKAGE__->belongs_to(
assigned_worker => 'OpenQA::Schema::Result::Workers',
'assigned_worker_id', {join_type => 'left', on_delete => 'SET NULL'});
__PACKAGE__->belongs_to(
clone => 'OpenQA::Schema::Result::Jobs',
'clone_id', {join_type => 'left', on_delete => 'SET NULL'});
__PACKAGE__->belongs_to(
blocked_by => 'OpenQA::Schema::Result::Jobs',
'blocked_by_id', {join_type => 'left'});
__PACKAGE__->has_many(
blocking => 'OpenQA::Schema::Result::Jobs',
'blocked_by_id'
);
__PACKAGE__->belongs_to(
group => 'OpenQA::Schema::Result::JobGroups',
'group_id', {join_type => 'left', on_delete => 'SET NULL'});
__PACKAGE__->might_have(origin => 'OpenQA::Schema::Result::Jobs', 'clone_id', {cascade_delete => 0});
__PACKAGE__->might_have(
developer_session => 'OpenQA::Schema::Result::DeveloperSessions',
'job_id', {cascade_delete => 1});
__PACKAGE__->has_many(jobs_assets => 'OpenQA::Schema::Result::JobsAssets', 'job_id');
__PACKAGE__->many_to_many(assets => 'jobs_assets', 'asset');
__PACKAGE__->has_many(last_use_assets => 'OpenQA::Schema::Result::Assets', 'last_use_job_id', {cascade_delete => 0});
__PACKAGE__->has_many(children => 'OpenQA::Schema::Result::JobDependencies', 'parent_job_id');
__PACKAGE__->has_many(parents => 'OpenQA::Schema::Result::JobDependencies', 'child_job_id');
__PACKAGE__->has_many(
modules => 'OpenQA::Schema::Result::JobModules',
'job_id', {cascade_delete => 0, order_by => 'id'});
# Locks
__PACKAGE__->has_many(owned_locks => 'OpenQA::Schema::Result::JobLocks', 'owner');
__PACKAGE__->has_many(locked_locks => 'OpenQA::Schema::Result::JobLocks', 'locked_by');
__PACKAGE__->has_many(comments => 'OpenQA::Schema::Result::Comments', 'job_id', {order_by => 'id'});
__PACKAGE__->has_many(networks => 'OpenQA::Schema::Result::JobNetworks', 'job_id');
__PACKAGE__->has_many(gru_dependencies => 'OpenQA::Schema::Result::GruDependencies', 'job_id');
__PACKAGE__->has_many(screenshot_links => 'OpenQA::Schema::Result::ScreenshotLinks', 'job_id');
__PACKAGE__->belongs_to(
scheduled_product => 'OpenQA::Schema::Result::ScheduledProducts',
'scheduled_product_id', {join_type => 'left', on_delete => 'SET NULL'});
__PACKAGE__->filter_column(
result_dir => {
filter_to_storage => 'remove_result_dir_prefix',
filter_from_storage => 'add_result_dir_prefix',
});
sub sqlt_deploy_hook ($self, $sqlt_table) {
$sqlt_table->add_index(name => 'idx_jobs_state', fields => ['state']);
$sqlt_table->add_index(name => 'idx_jobs_result', fields => ['result']);
$sqlt_table->add_index(name => 'idx_jobs_build_group', fields => [qw(BUILD group_id)]);
$sqlt_table->add_index(name => 'idx_jobs_scenario', fields => [qw(VERSION DISTRI FLAVOR TEST MACHINE ARCH)]);
}
# override to straighten out job modules and screenshot references
sub delete ($self) {
$self->modules->delete;
# delete all screenshot references (screenshots left unused are deleted later in the job limit task)
$self->screenshot_links->delete;
my $ret = $self->SUPER::delete;
# last step: remove result directory if already existent
# This must be executed after $self->SUPER::delete because it might fail and result_dir should not be
# deleted in the error case
my $res_dir = $self->result_dir();
File::Path::rmtree($res_dir) if $res_dir && -d $res_dir;
return $ret;
}
sub is_final ($self) { OpenQA::Jobs::Constants::meta_state($self->state) eq OpenQA::Jobs::Constants::FINAL }
sub archivable_result_dir ($self) {
return undef if $self->archived || !$self->is_final;
my $result_dir = $self->result_dir;
return $result_dir && -d $result_dir ? $result_dir : undef;
}
sub archive ($self, $signal_guard = undef) {
return undef unless my $normal_result_dir = $self->archivable_result_dir;
my $archived_result_dir = $self->add_result_dir_prefix($self->remove_result_dir_prefix($normal_result_dir), 1);
# create destination directory manually because directory creation of File::Copy::Recursive has a race condition
# and therefore might fail when running archiving jobs using the same prefix-directory in parallel
path($archived_result_dir)->make_path;
if (!File::Copy::Recursive::dircopy($normal_result_dir, $archived_result_dir)) {
my $error = $!;
File::Path::rmtree($archived_result_dir); # avoid leftovers
die "Unable to copy '$normal_result_dir' to '$archived_result_dir': $error";
}
$signal_guard->retry(0) if $signal_guard;
$self->update({archived => 1});
$self->discard_changes;
File::Path::remove_tree($normal_result_dir);
return $archived_result_dir;
}
sub name ($self) {
return $self->{_name} if $self->{_name};
my %formats = (BUILD => 'Build%s',);
my @name_keys = qw(DISTRI VERSION FLAVOR ARCH BUILD TEST);
my @a = map { my $c = $self->get_column($_); $c ? sprintf(($formats{$_} || '%s'), $c) : () } @name_keys;
my $name = join('-', @a);
my $machine = $self->MACHINE;
$name .= ('@' . $machine) if $machine;
$name =~ s/[^a-zA-Z0-9@._+:-]/_/g;
$self->{_name} = $name;
return $self->{_name};
}
sub label ($self) {
my $test = $self->TEST;
my $machine = $self->MACHINE;
return $machine ? "$test\@$machine" : $test;
}
sub scenario ($self) {
my $test_suite_name = $self->settings_hash->{TEST_SUITE_NAME} || $self->TEST;
return $self->result_source->schema->resultset('TestSuites')->find({name => $test_suite_name});
}
sub scenario_hash ($self) {
my %scenario = map { lc $_ => $self->get_column($_) } SCENARIO_WITH_MACHINE_KEYS;
return \%scenario;
}
sub scenario_name ($self) {
my $scenario = join('-', map { $self->get_column($_) } SCENARIO_KEYS);
if (my $machine = $self->MACHINE) { $scenario .= "@" . $machine }
return $scenario;
}
sub scenario_description ($self) {
my $description = $self->settings_hash->{JOB_DESCRIPTION};
return $description if defined $description;
my $scenario = $self->scenario or return undef;
return $scenario->description;
}
sub rendered_scenario_description ($self) {
return undef unless my $desc = $self->scenario_description;
return Mojo::ByteStream->new(markdown_to_html($desc));
}
# return 0 if we have no worker
sub worker_id ($self) { $self->worker ? $self->worker->id : 0 }
sub reschedule_state ($self, $state = OpenQA::Jobs::Constants::SCHEDULED) {
# set job to $state/SCHEDULED if it is still just ASSIGNED (not SETUP/RUNNING yet)
# note: As this function is invoked as part of the stale job detection the job might
# already be SETUP/RUNNING after all. In this case we need to abort.
my $jobs = $self->result_source->schema->resultset('Jobs');
my %cond = (id => $self->id, state => {-in => [SCHEDULED, ASSIGNED]});
my %update = (state => $state, result => NONE, t_started => undef, assigned_worker_id => undef);
return 0 if $jobs->search(\%cond)->update(\%update) == 0;
# cleanup
$self->set_property('JOBTOKEN');
$self->release_networks();
$self->owned_locks->delete;
$self->locked_locks->update({locked_by => undef});
log_debug('Job ' . $self->id . " reset to state $state");
# free the worker
if (my $worker = $self->worker) { $worker->update({job_id => undef}) }
return 1;
}
sub log_debug_job ($self, $msg) { log_debug('[Job#' . $self->id . '] ' . $msg) }
sub set_assigned_worker ($self, $worker) {
my $job_id = $self->id;
my $worker_id = $worker->id;
$self->update(
{
state => ASSIGNED,
t_started => undef,
assigned_worker_id => $worker_id,
});
log_debug("Assigned job '$job_id' to worker ID '$worker_id'");
}
sub prepare_for_work ($self, $worker = undef, $worker_properties = {}) {
return undef unless $worker;
$self->log_debug_job('Prepare for being processed by worker ' . $worker->id);
my $job_hashref = {};
$job_hashref = $self->to_hash(assets => 1);
# set JOBTOKEN for test access to API
my $job_token = $worker_properties->{JOBTOKEN} // random_string();
$worker->set_property(JOBTOKEN => $job_token);
$job_hashref->{settings}->{JOBTOKEN} = $job_token;
my $updated_settings = $self->register_assets_from_settings();
@{$job_hashref->{settings}}{keys %$updated_settings} = values %$updated_settings
if $updated_settings;
if ( $job_hashref->{settings}->{NICTYPE}
&& !defined $job_hashref->{settings}->{NICVLAN}
&& $job_hashref->{settings}->{NICTYPE} ne 'user')
{
my @networks = ('fixed');
@networks = split /\s*,\s*/, $job_hashref->{settings}->{NETWORKS} if $job_hashref->{settings}->{NETWORKS};
my @vlans = map { $self->allocate_network($_) } @networks;
$job_hashref->{settings}->{NICVLAN} = join(',', @vlans);
}
unless ($worker_properties->{WORKER_TMPDIR}) {
# assign new tmpdir, clean previous one
if (my $tmpdir = $worker->get_property('WORKER_TMPDIR')) {
File::Path::rmtree($tmpdir);
}
$worker->set_property(WORKER_TMPDIR => tempdir(sprintf('webui.worker-%d.XXXXXXXX', $worker->id), TMPDIR => 1));
}
return $job_hashref;
}
sub ws_send ($self, $worker = undef) {
return undef unless $worker;
my $hashref = $self->prepare_for_work($worker);
$hashref->{assigned_worker_id} = $worker->id;
return OpenQA::WebSockets::Client->singleton->send_job($hashref);
}
sub settings_hash ($self, $prefetched = undef) {
return $self->{_settings} if defined $self->{_settings};
my $settings = $self->{_settings} = {};
my $all = $prefetched || [$self->settings->all];
for (@$all) {
# handle multi-value WORKER_CLASS
if (defined $settings->{$_->key}) {
$settings->{$_->key} .= ',' . $_->value;
}
else {
$settings->{$_->key} = $_->value;
}
}
for my $column (qw(DISTRI VERSION FLAVOR MACHINE ARCH BUILD TEST)) {
if (my $value = $self->$column) { $settings->{$column} = $value }
}
$settings->{NAME} = sprintf '%08d-%s', $self->id, $self->name;
if ($settings->{JOB_TEMPLATE_NAME}) {
my $test = $settings->{TEST};
my $job_template_name = $settings->{JOB_TEMPLATE_NAME};
$settings->{NAME} =~ s/$test/$job_template_name/e;
}
return $settings;
}
sub add_result_dir_prefix ($self, $result_dir, $archived = undef) {
return $result_dir ? catfile($self->num_prefix_dir($archived), $result_dir) : undef;
}
sub remove_result_dir_prefix ($self, $result_dir) {
return $result_dir ? basename($result_dir) : undef;
}
sub set_prio ($self, $prio) { $self->update({priority => $prio}) }
sub _hashref ($obj, @fields) {
my %hashref = ();
foreach my $field (@fields) {
my $ref = ref($obj->$field);
if ($ref =~ /HASH|ARRAY|SCALAR|^$/) {
$hashref{$field} = $obj->$field;
}
elsif ($ref eq 'DateTime') {
# non standard ref, try to stringify
$hashref{$field} = $obj->$field->datetime();
}
else {
die "unknown field type: $ref";
}
}
return \%hashref;
}
sub to_hash ($job, %args) {
my $dependencies = delete $args{dependencies}; # prefetched
my $settings = delete $args{settings}; # prefetched
my $j = _hashref($job, qw(id name priority state result clone_id t_started t_finished group_id blocked_by_id));
my $job_group;
if ($j->{group_id}) {
$job_group = $job->group;
$j->{group} = $job_group->name;
}
if ($job->assigned_worker_id) {
$j->{assigned_worker_id} = $job->assigned_worker_id;
}
if (exists $args{origin}) {
$j->{origin_id} = $args{origin} if $args{origin};
}
elsif (my $origin = $job->origin) {
$j->{origin_id} = $origin->id;
}
if (my $reason = $job->reason) {
$j->{reason} = $reason;
}
$j->{settings} = $job->settings_hash($settings);
# hashes are left for script compatibility with schema version 38
$j->{test} = $job->TEST;
if ($args{assets}) {
my $assets = $job->{_assets} // [map { $_->asset } $job->jobs_assets->all];
push @{$j->{assets}->{$_->type}}, $_->name for @$assets;
}
if ($args{deps}) {
my @args = $dependencies ? ($dependencies->{children} || [], $dependencies->{parents} || []) : ();
$j = {%$j, %{$job->dependencies(@args)}};
}
if ($args{details}) {
my $test_modules = read_test_modules($job);
$j->{testresults} = ($test_modules ? $test_modules->{modules} : []);
$j->{logs} = $job->test_resultfile_list;
$j->{ulogs} = $job->test_uploadlog_list;
}
if ($args{parent_group} && $job_group) {
if (my $parent_group = $job_group->parent) {
$j->{parent_group_id} = $parent_group->id;
$j->{parent_group} = $parent_group->name;
}
}
$j->{missing_assets} = $job->missing_assets if $args{check_assets};
return $j;
}
=head2 can_be_duplicated
=over
=item Arguments: none
=item Return value: 1 if a new clone can be created. undef otherwise.
=back
Checks if a given job can be duplicated - not cloned yet and in correct state.
=cut
sub can_be_duplicated ($self) { (!defined $self->clone_id) && !$self->is_pristine }
sub is_pristine ($self) {
any { $self->state eq $_ } PRISTINE_STATES;
}
sub _compute_asset_names_considering_parent_jobs ($parent_job_ids, $asset_name) {
[$asset_name, map { sprintf('%08d-%s', $_, $asset_name) } @$parent_job_ids]
}
sub _strip_parent_job_id ($parent_job_ids, $asset_name) {
return $asset_name unless $asset_name =~ m/^(\d{8})-/;
$asset_name =~ s/^\d{8}-// if grep { $_ == $1 } @$parent_job_ids;
return $asset_name;
}
sub missing_assets ($self) {
my $assets_settings = parse_assets_from_settings($self->settings_hash);
return [] unless keys %$assets_settings;
# ignore UEFI_PFLASH_VARS; to keep scheduling simple it is present in lots of jobs which actually don't need it
delete $assets_settings->{UEFI_PFLASH_VARS};
my $parent_job_ids = $self->_parent_job_ids;
# ignore repos, as they're not really clonable: see
# https://github.com/os-autoinst/openQA/pull/2676#issuecomment-616312026
my @relevant_assets
= grep { $_->{name} ne '' && $_->{type} ne 'repo' } values %$assets_settings;
my @assets_query = map {
{
type => $_->{type},
name => {-in => _compute_asset_names_considering_parent_jobs($parent_job_ids, $_->{name})},
}
} @relevant_assets;
return [] unless @assets_query;
my $assets = $self->result_source->schema->resultset('Assets');
my @undetermined_assets = $assets->search({-or => \@assets_query, size => \'is null'}, {order_by => 'id'});
$_->ensure_size for @undetermined_assets;
my @existing_assets = $assets->search({-or => \@assets_query, size => \'is not null'});
return [] if scalar @$parent_job_ids == 0 && scalar @assets_query == scalar @existing_assets;
my %missing_assets = map { ("$_->{type}/$_->{name}" => 1) } @relevant_assets;
delete $missing_assets{$_->type . '/' . _strip_parent_job_id($parent_job_ids, $_->name)} for @existing_assets;
return [sort keys %missing_assets];
}
sub is_ok ($self) {
return 0 unless my $result = $self->result;
return 1 if grep { $_ eq $result } OK_RESULTS;
return 0;
}
sub is_ok_to_retry ($self) {
return 1 unless my $result = $self->result;
return 0 if grep { $_ eq $result } OK_RESULTS; # retry is not needed if job is ok
return 0 if $result eq USER_CANCELLED; # retry is not needed if job is user-cancelled
return 1;
}
sub extract_group_args_from_settings ($settings) {
my ($group, %group_args);
if (exists $settings->{_GROUP_ID}) {
if (my $id = delete $settings->{_GROUP_ID}) { $group_args{id} = $id }
else { $group = 0 }
}
if (exists $settings->{_GROUP}) {
if (my $name = delete $settings->{_GROUP}) { $group_args{name} //= $name }
else { $group = 0 }
}
$group = OpenQA::Schema->singleton->resultset('JobGroups')->find(\%group_args) if keys %group_args;
return (\%group_args, $group);
}
=head2 _create_clone
=over
=item Arguments: none
=item Return value: new job
=back
Internal function, needs to be executed in a transaction to perform
optimistic locking on clone_id
=cut
sub _create_clone ($self, $cluster_job_info, $clone, $prio, $skip_ok_result_children, $settings) {
# Skip cloning 'ok' jobs which are only pulled in as children if that flag is set
return ()
if $skip_ok_result_children
&& !$cluster_job_info->{is_parent_or_initial_job}
&& $cluster_job_info->{ok};
# Duplicate settings (with exceptions)
my %spec_settings = %$settings;
my %main_settings = map { $_ => (delete $spec_settings{$_}) // $self->$_ } MAIN_SETTINGS;
if (my $test_suffix = delete $spec_settings{'TEST+'}) { $main_settings{TEST} .= $test_suffix }
my ($group_args, $group) = extract_group_args_from_settings(\%spec_settings);
die "Specified _GROUP/_GROUP_ID settings are invalid\n" if keys %$group_args && !$group;
my @settings = grep { $_->key !~ /^(NAME|TEST|JOBTOKEN)$/ } $self->settings->all;
my @new_settings = map {
my $key = $_->key;
my $value = (delete $spec_settings{$key}) // $_->value;
{key => $key, value => $value}
} @settings;
push @new_settings, {key => $_, value => $spec_settings{$_}} for keys %spec_settings;
my $rset = $self->result_source->resultset;
$main_settings{group_id} = defined $group ? ($group ? $group->id : undef) : ($self->group_id);
$main_settings{settings} = \@new_settings;
$main_settings{priority} = $prio || $self->priority;
my $new_job = $rset->create(\%main_settings); # assets are re-created in job_grab
# Perform optimistic locking on clone_id. If the job is not longer there
# or it already has a clone, rollback the transaction (new_job should
# not be created, somebody else was faster at cloning)
my $orig_id = $self->id;
if ($clone) {
my $affected_rows = $rset->search({id => $orig_id, clone_id => undef})->update({clone_id => $new_job->id});
die "Job $orig_id already has clone " . $rset->find($orig_id)->clone_id . "\n" unless $affected_rows == 1;
}
# Needed to load default values from DB
$new_job->discard_changes;
return ($orig_id => $new_job);
}
sub _create_clone_with_parent ($res, $clones, $p, $dependency) {
$p = $clones->{$p}->id if defined $clones->{$p};
$res->parents->find_or_create({parent_job_id => $p, dependency => $dependency});
}
sub _create_clone_with_child ($res, $clones, $c, $dependency) {
return undef unless exists $clones->{$c};
$c = $clones->{$c}->id if defined $clones->{$c};
$res->children->find_or_create({child_job_id => $c, dependency => $dependency});
}
sub _create_clones ($self, $jobs, @clone_args) {
# create the clones
my $rset = $self->result_source->resultset;
my %clones = map { $rset->find($_)->_create_clone($jobs->{$_}, @clone_args) } sort keys %$jobs;
# create dependencies
for my $job (sort keys %clones) {
my $info = $jobs->{$job};
my $res = $clones{$job};
# recreate dependencies if exists for cloned parents/children
for my $p (@{$info->{parallel_parents}}) {
$p = $clones{$p}->id if defined $clones{$p};
$res->parents->find_or_create(
{
parent_job_id => $p,
dependency => OpenQA::JobDependencies::Constants::PARALLEL,
});
}
_create_clone_with_parent($res, \%clones, $_, OpenQA::JobDependencies::Constants::CHAINED)
for @{$info->{chained_parents}};
_create_clone_with_parent($res, \%clones, $_, OpenQA::JobDependencies::Constants::DIRECTLY_CHAINED)
for @{$info->{directly_chained_parents}};
_create_clone_with_child($res, \%clones, $_, OpenQA::JobDependencies::Constants::PARALLEL)
for @{$info->{parallel_children}};
_create_clone_with_child($res, \%clones, $_, OpenQA::JobDependencies::Constants::CHAINED)
for @{$info->{chained_children}};
_create_clone_with_child($res, \%clones, $_, OpenQA::JobDependencies::Constants::DIRECTLY_CHAINED)
for @{$info->{directly_chained_children}};
# when dependency network is recreated, associate assets
$res->register_assets_from_settings;
}
# calculate blocked_by
$clones{$_}->calculate_blocked_by for keys %clones;
# add a reference to the clone within $jobs
for my $job (keys %clones) {
my $clone = $clones{$job};
$jobs->{$job}->{clone} = $clone->id if $clone;
}
}
# internal (recursive) function for duplicate - returns hash of all jobs in the
# cluster of the current job (in no order but with relations)
sub cluster_jobs ($self, @args) {
my %args = (
jobs => {},
# set to 1 when called on a cluster job being cancelled or failing;
# affects whether we include parallel parents with
# PARALLEL_CANCEL_WHOLE_CLUSTER set if they have other pending children
cancelmode => 0,
@args
);
my $jobs = $args{jobs};
my $job_id = $self->id;
my $job = $jobs->{$job_id};
my $skip_children = $args{skip_children};
my $skip_parents = $args{skip_parents};
my $no_directly_chained_parent = $args{no_directly_chained_parent};
my $cancelmode = $args{cancelmode};
# handle re-visiting job
if (defined $job) {
# checkout the children after all when revisiting this job without $skip_children but children
# have previously been skipped
return $self->_cluster_children($jobs, $cancelmode) if !$skip_children && delete $job->{children_skipped};
# otherwise skip the already visisted job
return $jobs;
}
# make empty dependency data for the job
$job = $jobs->{$job_id} = {
# IDs of dependent jobs; one array per dependency type
parallel_parents => [],
chained_parents => [],
directly_chained_parents => [],
parallel_children => [],
chained_children => [],
directly_chained_children => [],
# additional information for skip_ok_result_children
is_parent_or_initial_job => ($args{added_as_child} ? 0 : 1),
ok => $self->is_ok,
state => $self->state,
};
# fill dependency data; go up recursively if we have a directly chained or parallel parent
my $parents = $self->parents;
PARENT: while (my $pd = $parents->next) {
my $p = $pd->parent;
my $parent_id = $p->id;
my $dep_type = $pd->dependency;
if ($dep_type eq OpenQA::JobDependencies::Constants::CHAINED) {
push(@{$job->{chained_parents}}, $parent_id);
# duplicate only up the chain if the parent job wasn't ok
# notes: - We skip the children here to avoid considering "direct siblings".
# - Going up the chain is not required/wanted when cancelling.
unless ($skip_parents || $cancelmode) {
my $parent_result = $p->result;
$p->cluster_jobs(jobs => $jobs, skip_children => 1, cancelmode => $cancelmode)
if !$parent_result || grep { $parent_result eq $_ } NOT_OK_RESULTS;
}
next;
}
elsif ($dep_type eq OpenQA::JobDependencies::Constants::DIRECTLY_CHAINED) {
push(@{$job->{directly_chained_parents}}, $parent_id);
# duplicate always up the chain to ensure this job ran directly after its directly chained parent
# notes: same as for CHAINED dependencies
unless ($skip_parents || $cancelmode) {
next if exists $jobs->{$parent_id};
die "Direct parent $parent_id needs to be cloned as well for the directly chained dependency "
. 'to work correctly. It is generally better to restart the parent which will restart all children '
. 'as well. Checkout the '
. '<a href="https://open.qa/docs/#_handling_of_related_jobs_on_failure_cancellation_restart">'
. "documentation</a> for more information.\n"
if $no_directly_chained_parent;
$p->cluster_jobs(jobs => $jobs, skip_children => 1, cancelmode => $cancelmode);
}
next;
}
elsif ($dep_type eq OpenQA::JobDependencies::Constants::PARALLEL) {
push(@{$job->{parallel_parents}}, $parent_id);
my $cancelwhole = 1;
# check if the setting to disable cancelwhole is set: the var
# must exist and be set to something false-y
my $settings = $p->settings_hash;
my $cwset = $settings->{PARALLEL_CANCEL_WHOLE_CLUSTER};
$job->{one_host_only} = 1 if $settings->{PARALLEL_ONE_HOST_ONLY};
$cancelwhole = 0 if (defined $cwset && !$cwset);
if ($args{cancelmode} && !$cancelwhole) {
# skip calling cluster_jobs (so cancelling it and its other
# related jobs) if job has pending children we are not
# cancelling
my $otherchildren = $p->children;
CHILD: while (my $childr = $otherchildren->next) {
my $child = $childr->child;
next CHILD unless grep { $child->state eq $_ } PENDING_STATES;
next PARENT unless $jobs->{$child->id};
}
}
$p->cluster_jobs(
jobs => $jobs,
no_directly_chained_parent => $no_directly_chained_parent,
cancelmode => $cancelmode
) unless $skip_parents;
}
}
return $self->_cluster_children($jobs, $cancelmode, $skip_parents, $no_directly_chained_parent)
unless $skip_children;
# flag this job as "children_skipped" to be able to distinguish when re-visiting the job
$job->{children_skipped} = 1;
return $jobs;
}
# internal (recursive) function used by cluster_jobs to invoke itself for all children
sub _cluster_children ($self, $jobs, $cancelmode, $skip_parents = undef, $no_directly_chained_parent = undef) {
my $schema = $self->result_source->schema;
my $current_job_info = $jobs->{$self->id};
my $children = $self->children;
while (my $cd = $children->next) {
my $c = $cd->child;
# if this is already cloned, ignore it (mostly chained children)
next if $c->clone_id;
# do not fear the recursion
$c->cluster_jobs(
jobs => $jobs,
skip_parents => $skip_parents,
no_directly_chained_parent => $no_directly_chained_parent,
added_as_child => 1,
cancelmode => $cancelmode,
);
# add the child's ID to the current job info
my $child_id = $c->id;
my $child_job_info = $jobs->{$child_id};
my $relation = OpenQA::JobDependencies::Constants::job_info_relation(children => $cd->dependency);
push(@{$current_job_info->{$relation}}, $child_id);
# consider the current job itself not ok if any children were not ok
# note: Let's assume we have a simple graph where only C failed: A -> B -> C
# If one restarts A with the 'skip_ok_result_children' flag we must also restart B to avoid a weird
# gap in the new dependency tree and for directly chained dependencies this is even unavoidable.
$current_job_info->{ok} = 0 unless $child_job_info->{ok};
}
return $jobs;
}
=head2 duplicate
=over
=item Arguments: optional hash reference containing the key 'prio'
=item Return value: hash of duplicated jobs if duplication succeeded,
an error message otherwise
=back
Clones the job creating a new one with the same settings and linked through
the 'clone' relationship. This method uses optimistic locking and database
transactions to ensure that only one clone is created per job. If the job
already have a job or the creation fails (most likely due to a concurrent
duplication detected by the optimistic locking), the method returns undef.
Rules for dependencies cloning are:
for PARALLEL dependencies:
- clone parents
+ if parent is clone, find the latest clone and clone it
- clone children
+ if child is clone, find the latest clone and clone it
for CHAINED dependencies:
- only clone failed parents, ignoring their children (our siblings, but also potentially our cousins from other child groups)
+ create new dependency - duplicit cloning is prevented by ignorelist, webui will show multiple chained deps though
- clone children
+ if child is clone, find the latest clone and clone it
for DIRECTLY_CHAINED dependencies:
- clone parents recursively but ignore their children (our siblings, but also potentially our cousins from other child groups)
+ if parent is clone, find the latest clone and clone it
- clone children
+ if child is clone, find the latest clone and clone it
=cut
sub duplicate ($self, $args = {}) {
# If the job already has a clone, none is created
my ($orig_id, $clone_id) = ($self->id, $self->clone_id);
my $state = $self->state;
return "Job $orig_id is still $state" if grep { $state eq $_ } PRISTINE_STATES;
return "Specified job $orig_id has already been cloned as $clone_id" if defined $clone_id;
my $jobs = eval {
$self->cluster_jobs(
skip_parents => $args->{skip_parents},
skip_children => $args->{skip_children},
no_directly_chained_parent => $args->{no_directly_chained_parent});
};
if (my $error = $@) {
return "An internal error occurred when computing cluster of $orig_id" if $error =~ qr/ at .* line \d*$/;
chomp $error;
return $error;
}
log_debug('Duplicating jobs: ' . dump($jobs));
my @args = ($jobs, $args->{clone} // 1, $args->{prio}, $args->{skip_ok_result_children}, $args->{settings} // {});
eval {
$self->result_source->schema->txn_do(sub { $self->_create_clones(@args) });
};
if (my $error = $@) {
chomp $error;
$error =~ s/ at .* line \d*$// if $error =~ s/^\{UNKNOWN\}\: //;
if ($error =~ /Rollback failed/) {
log_error("Unable to roll back after duplication error: $error");
return "Rollback failed after failure to clone cluster of job $orig_id";
}
return $error if $error =~ /already has clone/;
log_warning("Duplication rolled back after error: $error");
return "An internal error occurred when cloning cluster of job $orig_id";
}
return $jobs;
}
=head2 auto_duplicate
=over
=item Return value: DBIx object of cloned job with information about the cloned cluster accessible
as `$clone->{cluster_cloned}` or an error message.
=back
Handle individual job restart including dependent jobs and asset dependencies. Note that
the caller is responsible to notify the workers about the new job.
=cut
sub auto_duplicate ($self, $args = {}) {
my $clones = $self->duplicate($args);
return $clones unless ref $clones eq 'HASH';
# abort running jobs and skip scheduled jobs in the old cluster excluding $self
my $job_id = $self->id;
my $rsource = $self->result_source;
my %cluster_cond = ('!=' => $job_id, '-in' => [keys %$clones]);
my @states = (PRE_EXECUTION_STATES, EXECUTION_STATES);
my $jobs = $rsource->resultset->search({id => \%cluster_cond, state => \@states});
$jobs->search({state => [PRE_EXECUTION_STATES], result => NONE})->update({result => SKIPPED});
$jobs->search({state => [EXECUTION_STATES], result => NONE})->update({result => PARALLEL_RESTARTED});
my %related_scheduled_product_ids;
if (my $sp_id = $self->related_scheduled_product_id) { $related_scheduled_product_ids{$sp_id} = 1 }
while (my $j = $jobs->next) {
if (my $sp_id = $j->related_scheduled_product_id) { $related_scheduled_product_ids{$sp_id} = 1 }
next if $j->abort;
next unless $j->state eq SCHEDULED || $j->state eq ASSIGNED;
$j->release_networks;
$j->update({state => CANCELLED});
}
# report status back to GitHub for affected scheduled products
my $scheduled_products = $rsource->schema->resultset('ScheduledProducts');
my %related_scheduled_products = (id => {-in => [keys %related_scheduled_product_ids]});
$_->report_status_to_github for $scheduled_products->search(\%related_scheduled_products);
my $clone_id = $clones->{$job_id}->{clone};
my $dup = $rsource->resultset->find($clone_id);
$dup->{cluster_cloned} = {map { $_ => $clones->{$_}->{clone} } keys %$clones};
log_debug("Job $job_id duplicated as $clone_id");
return $dup;
}
sub abort ($self) {
my $worker = $self->worker;
return 0 unless $worker;
my ($job_id, $worker_id) = ($self->id, $worker->id);
log_debug("Sending abort command to worker $worker_id for job $job_id");
$worker->send_command(command => WORKER_COMMAND_ABORT, job_id => $job_id);
return 1;
}
sub set_property ($self, $key, $value = undef) {
my $r = $self->settings->find({key => $key});
if (defined $value) {
if ($r) {
$r->update({value => $value});
}
else {
$self->settings->create(
{
job_id => $self->id,
key => $key,
value => $value