/
jobqueue_test.go
7394 lines (6433 loc) · 252 KB
/
jobqueue_test.go
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 © 2016-2021 Genome Research Limited
// Author: Sendu Bala <sb10@sanger.ac.uk>.
//
// This file is part of wr.
//
// wr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wr 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with wr. If not, see <http://www.gnu.org/licenses/>.
package jobqueue
import (
"context"
crand "crypto/rand"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"testing"
"time"
sync "github.com/sasha-s/go-deadlock"
"github.com/wtsi-ssg/wr/clog"
"github.com/VertebrateResequencing/wr/cloud"
"github.com/VertebrateResequencing/wr/internal"
jqs "github.com/VertebrateResequencing/wr/jobqueue/scheduler"
"github.com/shirou/gopsutil/process"
. "github.com/smartystreets/goconvey/convey"
)
const maxSpawnTime = 240 * time.Second
const serverRC = `echo %s %s %s %s %d %d`
var runnermode bool
var runnerfail bool
var runnerdebug bool
var schedgrp string
var runnermodetmpdir string
var rdeployment string
var rserver string
var rdomain string
var rtimeout int
var maxmins int
var envVars = os.Environ()
var servermode bool
var serverKeepDB bool
var serverEnableRunners bool
func init() {
clog.ToDefault()
sync.Opts.DeadlockTimeout = 5 * time.Minute // some openstack behaviour needs a pretty long timeout
flag.BoolVar(&runnermode, "runnermode", false, "enable to disable tests and act as a 'runner' client")
flag.BoolVar(&runnerfail, "runnerfail", false, "make the runner client fail")
flag.BoolVar(&runnerdebug, "runnerdebug", false, "make the runner create debug files")
flag.StringVar(&schedgrp, "schedgrp", "", "schedgrp for runnermode")
flag.StringVar(&rdeployment, "rdeployment", "", "deployment for runnermode")
flag.StringVar(&rserver, "rserver", "", "server for runnermode")
flag.StringVar(&rdomain, "rdomain", "", "domain for runnermode")
flag.IntVar(&rtimeout, "rtimeout", 1, "reserve timeout for runnermode")
flag.IntVar(&maxmins, "maxmins", 0, "maximum mins allowed for runnermode")
flag.StringVar(&runnermodetmpdir, "tmpdir", "", "tmp dir for runnermode")
flag.BoolVar(&servermode, "servermode", false, "enable to disable tests and act as a 'server'")
flag.BoolVar(&serverKeepDB, "keepdb", false, "have the server keep its database when it starts")
flag.BoolVar(&serverEnableRunners, "enablerunners", false, "have the server spawn runners for jobs")
ServerLogClientErrors = false
}
func serverShutDownTime() time.Duration {
// golang can't actually do exec.Command.Start() in parallel and has a
// global lock on them, so we have to allow the 500ms of time to any pending
// starts to resolve before we can shut down.
return ClientTouchInterval + httpServerShutdownTime + serverShutdownRunnerTickerTime + 500*time.Millisecond
}
func TestJobqueueUtils(t *testing.T) {
if runnermode || servermode {
return
}
Convey("CurrentIP() works", t, func() {
ip, err := internal.CurrentIP("")
So(err, ShouldBeNil)
So(ip, ShouldNotBeBlank)
ip, err = internal.CurrentIP("9.9.9.9/24")
So(err, ShouldBeNil)
So(ip, ShouldBeBlank)
ip, err = internal.CurrentIP(ip + "/16")
So(err, ShouldBeNil)
So(ip, ShouldEqual, ip)
})
Convey("generateToken() and tokenMatches() work", t, func() {
tokenFile, err := os.CreateTemp("", "wr.test.token")
So(err, ShouldBeNil)
tokenFile.Close()
tokenPath := tokenFile.Name()
defer func() {
err = os.Remove(tokenPath)
So(err, ShouldBeNil)
}()
err = os.Remove(tokenPath)
So(err, ShouldBeNil)
token, err := generateToken(tokenPath)
So(err, ShouldBeNil)
So(len(token), ShouldEqual, tokenLength)
token2, err := generateToken(tokenPath)
So(err, ShouldBeNil)
So(len(token2), ShouldEqual, tokenLength)
So(token, ShouldNotResemble, token2)
So(tokenMatches(token, token2), ShouldBeFalse)
So(tokenMatches(token, token), ShouldBeTrue)
// if tokenPath is a file that contains a token, generateToken doesn't
// generate a new token, but returns that one
err = os.WriteFile(tokenPath, token2, 0600)
So(err, ShouldBeNil)
token3, err := generateToken(tokenPath)
So(err, ShouldBeNil)
So(len(token3), ShouldEqual, tokenLength)
So(token3, ShouldResemble, token2)
So(tokenMatches(token2, token3), ShouldBeTrue)
})
Convey("GenerateCerts creates certificate files", t, func() {
certtmpdir, err := os.MkdirTemp("", "wr_jobqueue_cert_dir_")
So(err, ShouldBeNil)
defer os.RemoveAll(certtmpdir)
caFile := filepath.Join(certtmpdir, "ca.pem")
certFile := filepath.Join(certtmpdir, "cert.pem")
keyFile := filepath.Join(certtmpdir, "key.pem")
certDomain := "localhost"
err = internal.GenerateCerts(caFile, certFile, keyFile, certDomain, internal.DefaultBitsForRootRSAKey,
internal.DefualtBitsForServerRSAKey, crand.Reader,
internal.DefaultCertFileFlags)
So(err, ShouldBeNil)
_, err = os.Stat(caFile)
So(err, ShouldBeNil)
_, err = os.Stat(certFile)
So(err, ShouldBeNil)
_, err = os.Stat(keyFile)
So(err, ShouldBeNil)
Convey("CertExpiry shows they expire in a year", func() {
expiry, err := internal.CertExpiry(caFile)
So(err, ShouldBeNil)
So(expiry, ShouldHappenBetween, time.Now().Add(364*24*time.Hour), time.Now().Add(366*24*time.Hour))
})
})
Convey("currentDisk works recursively with ignores", t, func() {
dir, err := os.MkdirTemp("", "wr_currentDisk_test")
So(err, ShouldBeNil)
defer os.RemoveAll(dir)
subdir := filepath.Join(dir, ".mnt", "sub")
err = os.MkdirAll(subdir, fs.ModePerm)
So(err, ShouldBeNil)
createLargeFile := func(path string, size int64) error {
f, errc := os.Create(path)
if errc != nil {
return errc
}
errc = f.Truncate(size)
if errc != nil {
return errc
}
return f.Close()
}
err = createLargeFile(filepath.Join(dir, "a.txt"), 1024*1024)
So(err, ShouldBeNil)
err = createLargeFile(filepath.Join(subdir, "b.txt"), 1024*1024)
So(err, ShouldBeNil)
s, err := currentDisk(dir)
So(err, ShouldBeNil)
So(s, ShouldEqual, 2)
s, err = currentDisk(dir, map[string]bool{subdir: true})
So(err, ShouldBeNil)
So(s, ShouldEqual, 1)
})
Convey("calculateItemDelay works", t, func() {
d := calculateItemDelay(0)
So(d, ShouldBeGreaterThanOrEqualTo, 30*time.Second)
So(d, ShouldBeLessThan, 60*time.Second)
d = calculateItemDelay(1)
So(d, ShouldBeGreaterThanOrEqualTo, 60*time.Second)
So(d, ShouldBeLessThan, 90*time.Second)
d = calculateItemDelay(2)
So(d, ShouldBeGreaterThanOrEqualTo, 120*time.Second)
So(d, ShouldBeLessThan, 150*time.Second)
d = calculateItemDelay(6)
So(d, ShouldBeGreaterThanOrEqualTo, 1800*time.Second)
So(d, ShouldBeLessThan, 1830*time.Second)
d = calculateItemDelay(7)
So(d, ShouldBeGreaterThanOrEqualTo, 1800*time.Second)
So(d, ShouldBeLessThan, 1830*time.Second)
d = calculateItemDelay(999999999)
So(d, ShouldBeGreaterThanOrEqualTo, 1800*time.Second)
So(d, ShouldBeLessThan, 1830*time.Second)
d = calculateItemDelay(-999999999)
So(d, ShouldBeGreaterThanOrEqualTo, 30*time.Second)
So(d, ShouldBeLessThan, 60*time.Second)
})
}
func jobqueueTestInit(shortTTR bool) (internal.Config, ServerConfig, string, *jqs.Requirements, time.Duration) {
ctx := context.Background()
// load our config to know where our development manager port is supposed to
// be; we'll use that to test jobqueue
config := internal.ConfigLoadFromParentDir(ctx, "development")
managerDBBkFile := config.ManagerDBFile + "_bk" // not config.ManagerDBBkFile in case it is an s3 url
serverConfig := ServerConfig{
Port: config.ManagerPort,
WebPort: config.ManagerWeb,
SchedulerName: "local",
SchedulerConfig: &jqs.ConfigLocal{Shell: config.RunnerExecShell},
DBFile: config.ManagerDBFile,
DBFileBackup: managerDBBkFile,
TokenFile: config.ManagerTokenFile,
CAFile: config.ManagerCAFile,
CertFile: config.ManagerCertFile,
CertDomain: config.ManagerCertDomain,
KeyFile: config.ManagerKeyFile,
Deployment: config.Deployment,
}
addr := "localhost:" + config.ManagerPort
setDomainIP(config.ManagerCertDomain)
ServerInterruptTime = 10 * time.Millisecond
ServerReserveTicker = 10 * time.Millisecond
ClientReleaseDelayMin = 100 * time.Millisecond
clientConnectTime := 1500 * time.Millisecond
if shortTTR {
ServerItemTTR = 1 * time.Second
ClientTouchInterval = 500 * time.Millisecond
}
standardReqs := &jqs.Requirements{RAM: 10, Time: 10 * time.Second, Cores: 1, Disk: 0, Other: make(map[string]string)}
return *config, serverConfig, addr, standardReqs, clientConnectTime
}
// startServer runs the given exe with the --servermode arg. It is assumed that
// doing so starts a jobqueue server in another process that will kill itself
// after some time or when signalled. We return a client that is connected to
// that server, along with the client token and the server's pid. If keepDB is
// true, the exe will be run with --keepdb arg as well. Same idea with
// enableRunners. This also creates config.ManagerDir dir on disk if necessary,
// and does not delete it afterwards.
func startServer(serverExe string, keepDB, enableRunners bool, config internal.Config, addr string) (*Client, []byte, *exec.Cmd, error) {
err := os.MkdirAll(config.ManagerDir, 0700)
if err != nil {
log.Fatal(err)
}
preStart := time.Now()
args := []string{"--servermode"}
if keepDB {
args = append(args, "--keepdb")
}
if enableRunners {
args = append(args, "--enablerunners")
}
// run the server in the background
cmd := exec.Command(serverExe, args...)
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
// wait a while for our server cmd to actually start serving
mTimeout := 10 * time.Second
internal.WaitForFile(config.ManagerTokenFile, preStart, mTimeout)
token, err := os.ReadFile(config.ManagerTokenFile)
if err != nil || len(token) == 0 {
return nil, nil, cmd, err
}
jq, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, 2*time.Second)
return jq, token, cmd, err
}
// runServer starts a jobqueue server, and is what calling this test script in
// --servermode runs.
func runServer(ctx context.Context) {
// uncomment and set a log path to debug server issues in TestJobqueueSignal
// fh, err := log15.FileHandler("/log", log15.LogfmtFormat())
// if err != nil {
// log.Fatalf("error opening file: %v", err)
// }
// h := l15h.CallerInfoHandler(fh)
// testLogger.SetHandler(log15.LvlFilterHandler(log15.LvlDebug, h))
// pid := os.Getpid()
// testLogger = testLogger.New("pid", pid)
_, serverConfig, _, _, _ := jobqueueTestInit(false)
if serverKeepDB {
wipeDevDBOnInit = false
}
if serverEnableRunners {
self, err := os.Executable()
if err != nil {
clog.Crit(ctx, "os.Executable() failed", "err", err)
os.Exit(1)
}
// we can't use the --tmpdir option, since that means the runner cmds
// won't match between invocations, so recovery won't be complete. We
// don't need it anyway
serverConfig.RunnerCmd = self + " --runnermode --schedgrp '%s' --rdeployment %s --rserver '%s' --rdomain %s --rtimeout %d --maxmins %d"
}
ServerItemTTR = 200 * time.Millisecond
server, msg, _, err := serve(ctx, serverConfig)
if err != nil {
clog.Crit(ctx, "test daemon failed to start", "err", err)
os.Exit(1)
}
if msg != "" {
clog.Warn(ctx, msg)
}
// we'll Block() later, but just in case the parent tests bomb out
// without killing us, we'll stop after 20s
go func() {
<-time.After(20 * time.Second)
clog.Warn(ctx, "test daemon stopping after 20s")
server.Stop(ctx, true)
}()
clog.Warn(ctx, "test daemon up, will block")
// wait until we are killed
err = server.Block()
clog.Warn(ctx, "test daemon exiting", "reason", err)
os.Exit(0)
}
// serve calls Serve() but with a retry for 5s on failure. This allows time for
// a server that we recently stopped in a prior test to really not be listening
// on the ports any more.
func serve(ctx context.Context, config ServerConfig) (*Server, string, []byte, error) {
server, msg, token, err := Serve(ctx, config)
if err != nil {
limit := time.After(5 * time.Second)
ticker := time.NewTicker(500 * time.Millisecond)
RETRY:
for {
select {
case <-ticker.C:
server, msg, token, err = Serve(ctx, config)
if err != nil {
continue
}
ticker.Stop()
break RETRY
case <-limit:
ticker.Stop()
break RETRY
}
}
}
return server, msg, token, err
}
// waitUntilPidsAreGone waits up to the given number of seconds for the pids in
// the map to not exist. The pids are deleted from the map when they no longer
// exist. Returns true if all pids gone (and the map will be empty).
func waitUntilPidsAreGone(pids map[int]bool, seconds int) bool {
for i := 0; i < seconds; i++ {
for pid := range pids {
process, errf := os.FindProcess(pid)
if errf != nil && process == nil {
delete(pids, pid)
}
errs := process.Signal(syscall.Signal(0))
if errs != nil {
delete(pids, pid)
}
}
if len(pids) == 0 {
break
}
<-time.After(1 * time.Second)
}
return len(pids) == 0
}
func TestJobqueueSignal(t *testing.T) {
ctx := context.Background()
if runnermode {
return
}
if servermode {
runServer(ctx)
return
}
defer os.RemoveAll(filepath.Join(os.TempDir(), AppName+"_cwd"))
config, _, addr, _, clientConnectTime := jobqueueTestInit(false)
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
servertmpdir, err := os.MkdirTemp(pwd, "wr_jobqueue_test_server_dir_")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(servertmpdir)
// these tests need the server running in it's own pid so we can test signal
// handling in the client. Our server will be ourself in --servermode, so
// first we'll compile ourselves to the tmpdir
serverExe := filepath.Join(servertmpdir, "server")
cmd := exec.Command("go", "test", "-tags", "netgo", "-run", "TestJobqueue", "-c", "-o", serverExe)
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
errr := os.Remove(config.ManagerTokenFile)
if errr != nil && !os.IsNotExist(errr) {
t.Fatalf("failed to delete token file before test: %s\n", errr)
}
defer func() {
errr := os.Remove(config.ManagerTokenFile)
if errr != nil && !os.IsNotExist(errr) {
t.Fatalf("failed to delete token file after test: %s\n", errr)
}
}()
ClientTouchInterval = 50 * time.Millisecond
ClientRetryWait = 1 * time.Second
alreadyKilled := make(map[int]bool)
killServer := func(jq *Client, serverPid int, serverCmd *exec.Cmd) {
if alreadyKilled[serverPid] {
return
}
errd := jq.Disconnect()
if errd != nil && !strings.HasSuffix(errd.Error(), "connection closed") {
fmt.Printf("failed to disconnect: %s\n", errd)
}
waited := make(chan bool)
go func() {
errw := serverCmd.Wait()
if errw != nil {
fmt.Printf("failed to reap server pid: %s\n", errw)
}
waited <- true
}()
<-time.After(500 * time.Millisecond)
errk := syscall.Kill(serverPid, syscall.SIGTERM)
if errk != nil {
fmt.Printf("failed to send SIGTERM to server: %s\n", errk)
}
<-waited
alreadyKilled[serverPid] = true
}
Convey("Once a jobqueue server is up as a daemon", t, func() {
jq, token, serverCmd, errf := startServer(serverExe, false, false, config, addr)
serverPid := serverCmd.Process.Pid
So(errf, ShouldBeNil)
defer killServer(jq, serverPid, serverCmd)
So(jq.ServerInfo.PID, ShouldEqual, serverPid)
Convey("You can set up a long-running job for execution", func() {
cmd := "perl -e 'for (1..3) { sleep(1) }'"
cmd2 := "perl -e 'for (2..4) { sleep(1) }'"
var jobs []*Job
jobs = append(jobs, &Job{Cmd: cmd, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 10, Time: 4 * time.Second, Cores: 1}, Retries: uint8(0), RepGroup: "3secs_pass"})
jobs = append(jobs, &Job{Cmd: cmd2, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 10, Time: 1 * time.Second, Cores: 1}, Retries: uint8(0), RepGroup: "3secs_fail"})
RecSecRound = 1
defer func() {
// revert back to normal
RecSecRound = 1800
}()
inserts, already, err := jq.Add(jobs, envVars, true)
So(err, ShouldBeNil)
So(inserts, ShouldEqual, 2)
So(already, ShouldEqual, 0)
job, err := jq.Reserve(50 * time.Millisecond)
So(err, ShouldBeNil)
So(job.Cmd, ShouldEqual, cmd)
So(job.State, ShouldEqual, JobStateReserved)
job2, err := jq.Reserve(50 * time.Millisecond)
So(err, ShouldBeNil)
So(job2.Cmd, ShouldEqual, cmd2)
So(job2.State, ShouldEqual, JobStateReserved)
Convey("Signals are handled during execution, and we can see when jobs take too long", func() {
go func() {
<-time.After(2 * time.Second)
errk := syscall.Kill(os.Getpid(), syscall.SIGTERM)
if errk != nil {
fmt.Printf("failed to send SIGTERM: %s\n", errk)
}
}()
j1worked := make(chan bool)
go func() {
err := jq.Execute(ctx, job, config.RunnerExecShell)
if err != nil {
if jqerr, ok := err.(Error); ok && jqerr.Err == FailReasonSignal && job.State == JobStateBuried && job.Exited && job.Exitcode == -1 && job.FailReason == FailReasonSignal {
j1worked <- true
}
}
j1worked <- false
}()
j2worked := make(chan bool)
go func() {
err := jq.Execute(ctx, job2, config.RunnerExecShell)
if err != nil {
if jqerr, ok := err.(Error); ok && jqerr.Err == FailReasonTime && job2.State == JobStateBuried && job2.Exited && job2.Exitcode == -1 && job2.FailReason == FailReasonTime {
j2worked <- true
}
}
j2worked <- false
}()
So(<-j1worked, ShouldBeTrue)
So(<-j2worked, ShouldBeTrue)
jq2, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, clientConnectTime)
So(err, ShouldBeNil)
defer disconnect(jq2)
job, err = jq2.GetByEssence(&JobEssence{Cmd: cmd}, false, false)
So(err, ShouldBeNil)
So(job, ShouldNotBeNil)
So(job.Cmd, ShouldEqual, cmd)
So(job.State, ShouldEqual, JobStateBuried)
So(job.FailReason, ShouldEqual, FailReasonSignal)
job2, err = jq2.GetByEssence(&JobEssence{Cmd: cmd2}, false, false)
So(err, ShouldBeNil)
So(job2, ShouldNotBeNil)
So(job2.Cmd, ShouldEqual, cmd2)
So(job2.State, ShouldEqual, JobStateBuried)
So(job2.FailReason, ShouldEqual, FailReasonTime)
So(job2.Requirements.Time.Seconds(), ShouldEqual, 1)
// requirements only change on becoming ready
kicked, err := jq.Kick([]*JobEssence{job2.ToEssense()})
So(err, ShouldBeNil)
So(kicked, ShouldEqual, 1)
job2, err = jq.Reserve(50 * time.Millisecond)
So(err, ShouldBeNil)
So(job2, ShouldNotBeNil)
So(job2.Cmd, ShouldEqual, cmd2)
So(job2.State, ShouldEqual, JobStateReserved)
So(job2.FailReason, ShouldEqual, FailReasonTime)
So(job2.Requirements.Time.Seconds(), ShouldBeBetweenOrEqual, 3601, 3604)
// all signals handled the same way, so no need for further
// tests
})
})
Convey("Running jobs are recovered after a hard server crash", func() {
cmd := "sleep 10"
cmd2 := "perl -e 'for (1..10) { sleep(1) }'" // we want to kill this part way, but `sleep` processes don't seem to die straight away when killed
var jobs []*Job
jobs = append(jobs, &Job{Cmd: cmd, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 100, Time: 10 * time.Second, Cores: 0}, Retries: uint8(0), RepGroup: "recover"})
jobs = append(jobs, &Job{Cmd: cmd2, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 100, Time: 10 * time.Second, Cores: 0}, Retries: uint8(0), RepGroup: "buried"})
inserts, already, err := jq.Add(jobs, envVars, true)
So(err, ShouldBeNil)
So(inserts, ShouldEqual, 2)
So(already, ShouldEqual, 0)
job, err := jq.Reserve(50 * time.Millisecond)
So(err, ShouldBeNil)
So(job.Cmd, ShouldEqual, cmd)
So(job.State, ShouldEqual, JobStateReserved)
job2, err := jq.Reserve(50 * time.Millisecond)
So(err, ShouldBeNil)
So(job2.Cmd, ShouldEqual, cmd2)
So(job2.State, ShouldEqual, JobStateReserved)
serverCmdCh := make(chan *exec.Cmd)
go func() {
<-time.After(2 * time.Second)
gotJob, errg := jq.GetByEssence(&JobEssence{Cmd: cmd2}, false, false)
killServer(jq, serverPid, serverCmd)
if errg == nil && gotJob != nil {
<-time.After(2 * time.Second)
errk := syscall.Kill(gotJob.Pid, syscall.SIGKILL)
if errk != nil {
fmt.Printf("failed to send SIGKILL to job: %s\n", errk)
}
} else {
log.Printf("failed to get job: %s\n", errg)
}
<-time.After(4 * time.Second)
newJQ, _, newServerCmd, errf := startServer(serverExe, true, false, config, addr)
if errf != nil {
log.Printf("failed to start new server: %s\n", errf)
} else if newJQ != nil {
errd := newJQ.Disconnect()
if errd != nil {
fmt.Printf("failed to disconnect after making a new server: %s\n", errd)
}
}
serverCmdCh <- newServerCmd
}()
j1worked := make(chan bool)
giveUp1 := time.After(30 * time.Second)
go func() {
errch := make(chan error)
go func() {
errch <- jq.Execute(ctx, job, config.RunnerExecShell)
}()
select {
case erre := <-errch:
if erre != nil {
// we expect that we lost the connection when we killed
// the server, then reconnected to the new server and
// therefore got ErrStopReserving, but otherwise
// everything was fine
jqerr, ok := erre.(Error)
if !ok || jqerr.Err != ErrStopReserving {
fmt.Printf("\nexecute had err: %s\n", erre)
j1worked <- false
return
}
} // though sometimes we manage to not lose the connection
j1worked <- true
return
case <-giveUp1:
fmt.Printf("\ngave up waiting for job to finish\n")
j1worked <- false
}
}()
j2worked := make(chan bool)
giveUp2 := time.After(30 * time.Second)
go func() {
errch := make(chan error)
go func() {
errch <- jq.Execute(ctx, job2, config.RunnerExecShell)
}()
select {
case erre := <-errch:
if erre != nil && strings.Contains(erre.Error(), "exited with code -1") {
j2worked <- true
return
}
fmt.Printf("\njob2 had err %s\n", erre)
j2worked <- false
return
case <-giveUp2:
j2worked <- false
}
}()
serverCmd = <-serverCmdCh
serverPid = serverCmd.Process.Pid
So(<-j1worked, ShouldBeTrue)
So(<-j2worked, ShouldBeTrue)
jq2, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, clientConnectTime)
So(err, ShouldBeNil)
defer func() {
errd := jq2.Disconnect()
if errd != nil {
fmt.Printf("failed to disconnect: %s\n", errd)
}
}()
job, err = jq2.GetByEssence(&JobEssence{Cmd: cmd}, false, false)
So(err, ShouldBeNil)
So(job, ShouldNotBeNil)
So(job.Cmd, ShouldEqual, cmd)
So(job.State, ShouldEqual, JobStateComplete)
job2, err = jq2.GetByEssence(&JobEssence{Cmd: cmd2}, false, false)
So(err, ShouldBeNil)
So(job2, ShouldNotBeNil)
So(job2.Cmd, ShouldEqual, cmd2)
So(job2.State, ShouldEqual, JobStateBuried)
})
Reset(func() {
killServer(jq, serverPid, serverCmd)
})
})
// the next tests will have runners enabled so that we can see what happens
// when we force kill both the server and a runner
Convey("Once a jobqueue server using local scheduler is up as a daemon", t, func() {
jq, token, serverCmd, errf := startServer(serverExe, false, true, config, addr)
serverPid := serverCmd.Process.Pid
So(errf, ShouldBeNil)
defer killServer(jq, serverPid, serverCmd)
So(jq.ServerInfo.PID, ShouldEqual, serverPid)
Convey("Killed runners after a hard server crash come up lost, and new runners don't overcommit resources due to existing runners", func() {
cmd := "sleep 10"
cmd2 := "perl -e 'for (1..10) { sleep(1) }'"
var jobs []*Job
jobs = append(jobs, &Job{Cmd: cmd, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 1, Time: 10 * time.Second, Cores: float64(runtime.NumCPU())}, Retries: uint8(0), RepGroup: "recover"})
jobs = append(jobs, &Job{Cmd: cmd2, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 1, Time: 10 * time.Second, Cores: 0}, Retries: uint8(0), RepGroup: "lost"})
inserts, already, erra := jq.Add(jobs, envVars, true)
So(erra, ShouldBeNil)
So(inserts, ShouldEqual, 2)
So(already, ShouldEqual, 0)
// get pids of the runners the server spawned
<-time.After(2 * time.Second)
processes, err := process.Processes()
So(err, ShouldBeNil)
runnerPids := make(map[int]bool)
var runnerPidToKill int
for _, p := range processes {
thisCmd, errc := p.Cmdline()
if errc != nil {
continue
}
if strings.Contains(thisCmd, "sleep") {
parent, errp := p.Parent()
if errp != nil {
continue
}
parentCmd, errp := parent.Cmdline()
if errp != nil {
continue
}
if strings.Contains(parentCmd, serverExe) {
pid := int(parent.Pid)
if strings.Contains(thisCmd, "perl") {
runnerPidToKill = pid
}
runnerPids[pid] = true
if len(runnerPids) == 2 {
break
}
}
}
}
So(len(runnerPids), ShouldEqual, 2)
So(runnerPidToKill, ShouldNotEqual, 0)
So(runnerPidToKill, ShouldNotEqual, serverPid)
// kill server and then second runner, then wait before starting new
// server. We don't use killServer here because we don't want to
// jq.Disconnect and reap before killing the runner
errk := syscall.Kill(serverPid, syscall.SIGKILL)
if errk != nil {
fmt.Printf("failed to send SIGKILL to server: %s\n", errk)
}
<-time.After(2 * time.Second)
errk = syscall.Kill(runnerPidToKill, syscall.SIGKILL)
if errk != nil {
fmt.Printf("failed to send SIGKILL to runner: %s\n", errk)
}
errd := jq.Disconnect()
if errd != nil && !strings.HasSuffix(errd.Error(), "connection closed") {
fmt.Printf("failed to disconnect: %s\n", errd)
}
errw := serverCmd.Wait()
if errw != nil && !strings.Contains(errw.Error(), "signal: killed") {
fmt.Printf("failed to reap server pid: %s\n", errw)
}
alreadyKilled[serverPid] = true
<-time.After(4 * time.Second)
var errf error
jq, _, serverCmd, errf = startServer(serverExe, true, true, config, addr)
serverPid = serverCmd.Process.Pid
So(errf, ShouldBeNil)
So(jq, ShouldNotBeNil)
// add a new job which should wait until job 1 completes, since it
// uses all CPUs
cmd3 := "echo 1"
jobs = []*Job{{Cmd: cmd3, Cwd: "/tmp", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 1, Time: 10 * time.Second, Cores: 1}, Retries: uint8(0), RepGroup: "wait"}}
inserts, already, err = jq.Add(jobs, envVars, true)
errd = jq.Disconnect()
if errd != nil {
fmt.Printf("failed to disconnect: %s\n", errd)
}
So(err, ShouldBeNil)
So(inserts, ShouldEqual, 1)
So(already, ShouldEqual, 0)
// wait for runner pids to no longer exist
waitUntilPidsAreGone(runnerPids, 16)
So(len(runnerPids), ShouldEqual, 0)
jq2, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, clientConnectTime)
So(err, ShouldBeNil)
defer func() {
errd := jq2.Disconnect()
if errd != nil {
fmt.Printf("failed to disconnect: %s\n", errd)
}
}()
job, err := jq2.GetByEssence(&JobEssence{Cmd: cmd}, false, false)
So(err, ShouldBeNil)
So(job, ShouldNotBeNil)
So(job.Cmd, ShouldEqual, cmd)
So(job.State, ShouldEqual, JobStateComplete)
So(job.EndTime, ShouldHappenOnOrAfter, job.StartTime.Add(9900*time.Millisecond))
job2, err := jq2.GetByEssence(&JobEssence{Cmd: cmd2}, false, false)
So(err, ShouldBeNil)
So(job2, ShouldNotBeNil)
So(job2.Cmd, ShouldEqual, cmd2)
So(job2.State, ShouldEqual, JobStateLost)
// now allow 2 secs for job3 to start and complete
var job3 *Job
for i := 0; i < 8; i++ {
job3, err = jq2.GetByEssence(&JobEssence{Cmd: cmd3}, false, false)
if job3 != nil && job3.State == JobStateComplete {
break
}
<-time.After(250 * time.Millisecond)
}
So(err, ShouldBeNil)
So(job3, ShouldNotBeNil)
So(job3.Cmd, ShouldEqual, cmd3)
So(job3.State, ShouldEqual, JobStateComplete)
So(job3.StartTime, ShouldHappenAfter, job.EndTime)
// for subsequent tests to work, we need to wait for the server to
// really be gone
killServer(jq, serverPid, serverCmd)
So(waitUntilPidsAreGone(map[int]bool{serverPid: true}, 5), ShouldBeTrue)
})
Reset(func() {
killServer(jq, serverPid, serverCmd)
})
})
}
func TestJobqueueBasics(t *testing.T) {
ctx := context.Background()
if runnermode || servermode {
return
}
config, serverConfig, addr, standardReqs, clientConnectTime := jobqueueTestInit(true)
defer os.RemoveAll(filepath.Join(os.TempDir(), AppName+"_cwd"))
var server *Server
var token []byte
var errs error
Convey("Without the jobserver being up, clients can't connect and time out", t, func() {
os.Remove(config.ManagerTokenFile)
_, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, clientConnectTime)
So(err, ShouldNotBeNil)
jqerr, ok := err.(Error)
So(ok, ShouldBeTrue)
So(jqerr.Err, ShouldEqual, ErrNoServer)
jq, err := ConnectUsingConfig(ctx, "development", clientConnectTime)
So(jq, ShouldBeNil)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldContainSubstring, "could not read token file")
})
Convey("Once the jobqueue server is up", t, func() {
server, _, token, errs = serve(ctx, serverConfig)
So(errs, ShouldBeNil)
server.rc = serverRC // ReserveScheduled() only works if we have an rc
Convey("You can connect to the server using config", func() {
jq, err := ConnectUsingConfig(ctx, "development", clientConnectTime)
So(err, ShouldBeNil)
defer disconnect(jq)
})
Convey("You can connect to the server and add jobs and get back their IDs", func() {
jq, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, clientConnectTime)
So(err, ShouldBeNil)
defer disconnect(jq)
var jobs []*Job
req := &jqs.Requirements{RAM: 10, Time: 1 * time.Second, Cores: 1}
jobs = append(jobs, &Job{Cmd: "echo 1", Cwd: "/tmp", ReqGroup: "fake_group", Requirements: req, Retries: uint8(0), RepGroup: "test"})
jobs = append(jobs, &Job{Cmd: "echo 2", Cwd: "/tmp", ReqGroup: "fake_group", Requirements: req, Retries: uint8(0), RepGroup: "test"})
ids, err := jq.AddAndReturnIDs(jobs, envVars, true)
So(err, ShouldBeNil)
So(len(ids), ShouldEqual, 2)
So(ids[0], ShouldEqual, "9a456dee1e351f82e3d562769c27d803")
So(ids[1], ShouldEqual, "2bb7055e49e21ea85066899a5ba38d8e")
})
Convey("You can connect to the server and add jobs to the queue", func() {
jq, err := Connect(addr, config.ManagerCAFile, config.ManagerCertDomain, token, clientConnectTime)
So(err, ShouldBeNil)
defer disconnect(jq)
So(jq.ServerInfo.Port, ShouldEqual, serverConfig.Port)
So(jq.ServerInfo.PID, ShouldBeGreaterThan, 0)
So(jq.ServerInfo.Deployment, ShouldEqual, "development")
var jobs []*Job
for i := 0; i < 10; i++ {
pri := i
if i == 7 {
pri = 4
} else if i == 4 {
pri = 7
}
jobs = append(jobs, &Job{Cmd: fmt.Sprintf("test cmd %d", i), Cwd: "/fake/cwd", ReqGroup: "fake_group", Requirements: &jqs.Requirements{RAM: 1024, Time: 4 * time.Hour, Cores: 1}, Priority: uint8(pri), Retries: uint8(3), RepGroup: "manually_added"})
}
inserts, already, err := jq.Add(jobs, envVars, true)
So(err, ShouldBeNil)
So(inserts, ShouldEqual, 10)
So(already, ShouldEqual, 0)
Convey("You can't add the same jobs to the queue again", func() {
inserts, already, err := jq.Add(jobs, envVars, true)
So(err, ShouldBeNil)
So(inserts, ShouldEqual, 0)
So(already, ShouldEqual, 10)
})
Convey("You can get back jobs you've just added", func() {
job, err := jq.GetByEssence(&JobEssence{Cmd: "test cmd 3"}, false, false)
So(err, ShouldBeNil)
So(job, ShouldNotBeNil)
So(job.Cmd, ShouldEqual, "test cmd 3")
So(job.State, ShouldEqual, JobStateReady)
job, err = jq.GetByEssence(&JobEssence{Cmd: "test cmd x"}, false, false)
So(err, ShouldBeNil)
So(job, ShouldBeNil)
var jes []*JobEssence
for i := 0; i < 10; i++ {
jes = append(jes, &JobEssence{Cmd: fmt.Sprintf("test cmd %d", i)})
}
jobs, err = jq.GetByEssences(jes)
So(err, ShouldBeNil)
So(len(jobs), ShouldEqual, 10)
for i, job := range jobs {
So(job.Cmd, ShouldEqual, fmt.Sprintf("test cmd %d", i))