/
client.go
1948 lines (1804 loc) · 63.2 KB
/
client.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
// This file contains the functions needed to implement a jobqueue client.
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/VertebrateResequencing/wr/internal"
"github.com/docker/docker/client"
"github.com/gofrs/uuid"
"github.com/ugorji/go/codec"
"github.com/wtsi-ssg/wr/clog"
"github.com/wtsi-ssg/wr/container"
"github.com/wtsi-ssg/wr/container/docker"
"github.com/wtsi-ssg/wr/fs/local"
"nanomsg.org/go-mangos"
"nanomsg.org/go-mangos/protocol/req"
"nanomsg.org/go-mangos/transport/tlstcp"
)
// FailReason* are the reasons for cmd line failure stored on Jobs
const (
FailReasonEnv = "failed to get environment variables"
FailReasonCwd = "working directory does not exist"
FailReasonStart = "command failed to start"
FailReasonCPerm = "command permission problem"
FailReasonCFound = "command not found"
FailReasonCExit = "command invalid exit code"
FailReasonExit = "command exited non-zero"
FailReasonRAM = "command used too much RAM"
FailReasonDisk = "ran out of disk space"
FailReasonTime = "command used too much time"
FailReasonDocker = "could not interact with docker"
FailReasonAbnormal = "command failed to complete normally"
FailReasonLost = "lost contact with runner"
FailReasonSignal = "runner received a signal to stop"
FailReasonResource = "resource requirements cannot be met"
FailReasonMount = "mounting of remote file system(s) failed"
FailReasonUpload = "failed to upload files to remote file system"
FailReasonKilled = "killed by user request"
)
// lsfEmulationDir is the name of the directory we store our LSF emulation
// symlinks in
const lsfEmulationDir = ".wr_lsf_emulation"
// localhost is the name of host we're running on
const localhost = "localhost"
// these global variables are primarily exported for testing purposes; you
// probably shouldn't change them (*** and they should probably be re-factored
// as fields of a config struct...)
var (
ClientTouchInterval = 15 * time.Second
ClientReleaseDelayMin = 30 * time.Second
ClientReleaseDelayMax = 1800 * time.Second
ClientReleaseDelayStepFactor float64 = 2
ClientPercentMemoryKill = 90
ClientRetryWait = 15 * time.Second
ClientRetryTime = 24 * time.Hour
ClientShutdownTimeout = 120 * time.Second
ClientShutdownTestInterval = 100 * time.Millisecond
ClientSuggestedPingTimeout = 10 * time.Millisecond
RAMIncreaseMin float64 = 1000
RAMIncreaseMultLow = 2.0
RAMIncreaseMultHigh = 1.3
RAMIncreaseMultBreakpoint float64 = 8192
)
// clientRequest is the struct that clients send to the server over the network
// to request it do something. (The properties are only exported so the
// encoder doesn't ignore them.)
type clientRequest struct {
Env []byte // compressed binc encoding of []string
Jobs []*Job
Keys []string
File []byte // compressed bytes of file content
Token []byte
LimitGroup string
Method string
SchedulerGroup string
State JobState
Path string // desired path File should be stored at, can be blank
CloudServerID string
Job *Job
JobEndState *JobEndState
Modifier *JobModifier
Limit int
Timeout time.Duration
ClientID uuid.UUID
FirstReserve bool
GetEnv bool
GetStd bool
IgnoreComplete bool
Search bool
ConfirmDeadCloudServers bool
DestroyCloudHost string
ReturnIDs bool // when adding jobs, return the IDs of the added jobs
}
// Client represents the client side of the socket that the jobqueue server is
// Serve()ing, specific to a particular queue.
type Client struct {
ch codec.Handle
clientid uuid.UUID
hasReserved bool
sock mangos.Socket
sync.Mutex
teMutex sync.Mutex // to protect Touch() from other methods during Execute()
token []byte
ServerInfo *ServerInfo
host string
port string
args []string // allowing internal reconnects
}
// envStr holds the []string from os.Environ(), for codec compatibility.
type envStr struct {
Environ []string
}
// Connect creates a connection to the jobqueue server.
//
// addr is the host or IP of the machine running the server, suffixed with a
// colon and the port it is listening on, eg localhost:1234
//
// caFile is a path to the PEM encoded CA certificate that was used to sign the
// server's certificate. If set as a blank string, or if the file doesn't exist,
// the server's certificate will be trusted based on the CAs installed in the
// normal location on the system.
//
// certDomain is a domain that the server's certificate is supposed to be valid
// for.
//
// token is the authentication token that Serve() returned when the server was
// started.
//
// Timeout determines how long to wait for a response from the server, not only
// while connecting, but for all subsequent interactions with it using the
// returned Client.
func Connect(addr, caFile, certDomain string, token []byte, timeout time.Duration) (*Client, error) {
expiry, err := internal.CertExpiry(caFile)
if err != nil {
return nil, err
}
if time.Now().After(expiry) {
return nil, internal.CertError{Type: internal.ErrExpiredCert, Path: caFile}
}
sock, err := req.NewSocket()
if err != nil {
return nil, err
}
if err = sock.SetOption(mangos.OptionMaxRecvSize, 0); err != nil {
return nil, err
}
err = sock.SetOption(mangos.OptionRecvDeadline, timeout)
if err != nil {
return nil, err
}
sock.AddTransport(tlstcp.NewTransport())
tlsConfig := &tls.Config{ServerName: certDomain}
caCert, err := os.ReadFile(caFile)
if err == nil {
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = certPool
}
dialOpts := make(map[string]interface{})
dialOpts[mangos.OptionTLSConfig] = tlsConfig
if err = sock.DialOptions("tls+tcp://"+addr, dialOpts); err != nil {
return nil, err
}
// clients identify themselves (only for the purpose of calling methods that
// require the client has previously used Reserve()) with a UUID; v4 is used
// since speed doesn't matter: a typical client executable will only
// Connect() once; on the other hand, we avoid any possible problem with
// running on machines with low time resolution
u, err := uuid.NewV4()
if err != nil {
return nil, err
}
addrParts := strings.Split(addr, ":")
c := &Client{
sock: sock,
ch: new(codec.BincHandle),
token: token,
clientid: u,
host: addrParts[0],
port: addrParts[1],
args: []string{addr, caFile, certDomain},
}
// Dial succeeds even when there's no server up, so we test the connection
// works with a Ping()
si, err := c.Ping(timeout)
if err != nil {
errc := sock.Close()
if errc != nil {
return c, errc
}
msg := ErrNoServer
if jqerr, ok := err.(Error); ok && jqerr.Err == ErrPermissionDenied {
msg = ErrPermissionDenied
}
return nil, Error{"Connect", "", msg}
}
c.ServerInfo = si
return c, err
}
// ConnectUsingConfig calls Connect(), supplying values from user configuration
// available in the environment (config files and environment variables). To
// load the correct config, a deployment must be provided ('production' or
// 'development', whichever was used when starting the server).
func ConnectUsingConfig(ctx context.Context, deployment string, timeout time.Duration) (*Client, error) {
config := internal.ConfigLoadFromCurrentDir(ctx, deployment)
token, err := os.ReadFile(config.ManagerTokenFile)
if err != nil {
return nil, fmt.Errorf("could not read token file; has the manager been started? [%w]", err)
}
return Connect(config.ManagerHost+":"+config.ManagerPort, config.ManagerCAFile, config.ManagerCertDomain, token, timeout)
}
// Disconnect closes the connection to the jobqueue server. It is CRITICAL that
// you call Disconnect() before calling Connect() again in the same process.
func (c *Client) Disconnect() error {
c.Lock()
defer c.Unlock()
return c.sock.Close()
}
// Ping tells you if your connection to the server is working, returning static
// information about the server. If err is nil, it works. This is the only
// command that interacts with the server that works if a blank or invalid
// token had been supplied to Connect().
func (c *Client) Ping(timeout time.Duration) (*ServerInfo, error) {
resp, err := c.request(&clientRequest{Method: "ping", Timeout: timeout})
if err != nil {
return nil, err
}
return resp.SInfo, err
}
// DrainServer tells the server to stop spawning new runners, stop letting
// existing runners reserve new jobs, and exit once existing runners stop
// running. You get back a count of existing runners and and an estimated time
// until completion for the last of those runners.
func (c *Client) DrainServer() (running int, etc time.Duration, err error) {
return c.drainOrPauseServer("drain")
}
// drainOrPauseServer handles the response from drain or pause.
func (c *Client) drainOrPauseServer(method string) (running int, etc time.Duration, err error) {
resp, err := c.request(&clientRequest{Method: method})
if err != nil {
return running, etc, err
}
s := resp.SStats
running = s.Running
etc = s.ETC
return running, etc, err
}
// PauseServer tells the server to stop spawning new runners and stop letting
// existing runners reserve new jobs. (It is like DrainServer(), without
// stopping the server). You get back a count of existing runners and and an
// estimated time until completion for the last of those runners.
func (c *Client) PauseServer() (running int, etc time.Duration, err error) {
return c.drainOrPauseServer("pause")
}
// ResumeServer tells the server to start spawning new runners and start letting
// existing runners reserve new jobs. Use this after a PauseServer() call to
// resume normal operation.
func (c *Client) ResumeServer() error {
_, err := c.request(&clientRequest{Method: "resume"})
return err
}
// ShutdownServer tells the server to immediately cease all operations. Its last
// act will be to backup its internal database. Any existing runners will fail.
// Because the server gets shut down it can't respond with success/failure, so
// we indirectly report if the server was shut down successfully.
func (c *Client) ShutdownServer() bool {
_, err := c.request(&clientRequest{Method: "shutdown"})
if err != nil {
return false
}
// wait a while for the server to stop responding to Pings
limit := time.After(ClientShutdownTimeout)
ticker := time.NewTicker(ClientShutdownTestInterval)
for {
select {
case <-ticker.C:
_, err = c.Ping(ClientSuggestedPingTimeout)
if err != nil {
ticker.Stop()
return true
}
case <-limit:
return false
}
}
}
// BackupDB backs up the server's database to the given path. Note that
// automatic backups occur to the configured location without calling this.
func (c *Client) BackupDB(path string) error {
resp, err := c.request(&clientRequest{Method: "backup"})
if err != nil {
return err
}
tmpPath := path + ".tmp"
err = os.WriteFile(tmpPath, resp.DB, dbFilePermission)
if err != nil {
rerr := os.Remove(tmpPath)
if rerr != nil {
err = fmt.Errorf("%s\n%s", err.Error(), rerr.Error())
}
return err
}
return os.Rename(tmpPath, path)
}
// Add adds new jobs to the job queue, but only if those jobs aren't already in
// there.
//
// If any were already there, you will not get an error, but the returned
// 'existed' count will be > 0. Note that no cross-queue checking is done, so
// you need to be careful not to add the same job to different queues.
//
// Note that if you add jobs to the queue that were previously added, Execute()d
// and were successfully Archive()d, the existed count will be 0 and the jobs
// will be treated like new ones, though when Archive()d again, the new Job will
// replace the old one in the database. To have such jobs skipped as "existed"
// instead, supply ignoreComplete as true.
//
// The envVars argument is a slice of ("key=value") strings with the environment
// variables you want to be set when the job's Cmd actually runs. Typically you
// would pass in os.Environ().
func (c *Client) Add(jobs []*Job, envVars []string, ignoreComplete bool) (added, existed int, err error) {
compressed, err := c.CompressEnv(envVars)
if err != nil {
return 0, 0, err
}
resp, err := c.request(&clientRequest{Method: "add", Jobs: jobs, Env: compressed, IgnoreComplete: ignoreComplete})
if err != nil {
return 0, 0, err
}
return resp.Added, resp.Existed, err
}
// AddAndReturnIDs is like Add(), except that the internal IDs of jobs that are
// now in the queue are returned (including dups, excluding complete jobs). This
// is potentially expensive, so use Add() if you don't need these.
func (c *Client) AddAndReturnIDs(jobs []*Job, envVars []string, ignoreComplete bool) ([]string, error) {
compressed, err := c.CompressEnv(envVars)
if err != nil {
return nil, err
}
resp, err := c.request(&clientRequest{Method: "add", Jobs: jobs, Env: compressed, IgnoreComplete: ignoreComplete, ReturnIDs: true})
if err != nil {
return nil, err
}
return resp.AddedIDs, err
}
// Modify modifies previously Add()ed jobs that are incomplete and not currently
// running.
//
// The first argument lets you choose which jobs to modify. The second argument
// lets you define what you want to change in them all. If you want to change
// the actual command line of a job, you can only modify 1 job (and you can't
// change it to match another job in the queue or that has completed; those
// requests will be silently ignored).
//
// For each modified job, returns a mapping of new internal job id to the old
// internal job id (which will typically be the same, unless something critical
// like the command line was changed).
func (c *Client) Modify(jes []*JobEssence, modifier *JobModifier) (modified map[string]string, err error) {
keys := c.jesToKeys(jes)
resp, err := c.request(&clientRequest{Method: "jmod", Keys: keys, Modifier: modifier})
if err != nil {
return nil, err
}
return resp.Modified, err
}
// Reserve takes a job off the jobqueue. If you process the job successfully you
// should Archive() it. If you can't deal with it right now you should Release()
// it. If you think it can never be dealt with you should Bury() it. If you die
// unexpectedly, the job will automatically be released back to the queue after
// some time.
//
// If no job was available in the queue for as long as the timeout argument, nil
// is returned for both job and error. If your timeout is 0, you will wait
// indefinitely for a job.
//
// NB: if your jobs have schedulerGroups (and they will if you added them to a
// server configured with a RunnerCmd), this will most likely not return any
// jobs; use ReserveScheduled() instead.
func (c *Client) Reserve(timeout time.Duration) (*Job, error) {
fr := false
if !c.hasReserved {
fr = true
c.hasReserved = true
}
resp, err := c.request(&clientRequest{Method: "reserve", Timeout: timeout, FirstReserve: fr})
if err != nil {
return nil, err
}
return resp.Job, err
}
// ReserveScheduled is like Reserve(), except that it will only return jobs from
// the specified schedulerGroup.
//
// Based on the scheduler the server was configured with, it will group jobs
// based on their resource requirements and then submit runners to handle them
// to your system's job scheduler (such as LSF), possibly in different scheduler
// queues. These runners are told the group they are a part of, and that same
// group name is applied internally to the Jobs as the "schedulerGroup", so that
// the runners can reserve only Jobs that they're supposed to. Therefore, it
// does not make sense for you to call this yourself; it is only for use by
// runners spawned by the server.
func (c *Client) ReserveScheduled(timeout time.Duration, schedulerGroup string) (*Job, error) {
fr := false
if !c.hasReserved {
fr = true
c.hasReserved = true
}
resp, err := c.request(&clientRequest{Method: "reserve", Timeout: timeout, SchedulerGroup: schedulerGroup, FirstReserve: fr})
if err != nil {
return nil, err
}
return resp.Job, err
}
// Execute runs the given Job's Cmd and blocks until it exits. Then any Job
// Behaviours get triggered as appropriate for the exit status.
//
// The Cmd is run using the environment variables set when the Job was Add()ed,
// or the current environment is used if none were set.
//
// The Cmd is also run within the Job's Cwd. If CwdMatters is false, a unique
// subdirectory is created within Cwd, and that is used as the actual working
// directory. When creating these unique subdirectories, directory hashing is
// used to allow the safe running of 100s of thousands of Jobs all using the
// same Cwd (that is, we will not break the directory listing of Cwd).
// Furthermore, a sister folder will be created in the unique location for this
// Job, the path to which will become the value of the TMPDIR environment
// variable. Once the Cmd exits, this temp directory will be deleted and the
// path to the actual working directory created will be in the Job's ActualCwd
// property. The unique folder structure itself can be wholly deleted through
// the Job behaviour "cleanup".
//
// If any remote file system mounts have been configured for the Job, these are
// mounted prior to running the Cmd, and unmounted afterwards.
//
// If WithDocker or WithSingularity has been set, the Cmd is run within the
// corresponding container image, with any additional ContainerMounts mounted.
//
// Internally, Execute() calls Mount() and Started() and keeps track of peak RAM
// and disk used. It regularly calls Touch() on the Job so that the server knows
// we are still alive and handling the Job successfully. It also intercepts
// SIGTERM, SIGINT, SIGQUIT, SIGUSR1 and SIGUSR2, sending SIGKILL to the running
// Cmd and returning Error.Err(FailReasonSignal); you should check for this and
// exit your process. Finally it calls Unmount() and TriggerBehaviours().
//
// If Kill() is called while executing the Cmd, the next internal Touch() call
// will result in the Cmd being killed and the job being Bury()ied.
//
// If no error is returned, the Cmd will have run OK, exited with status 0, and
// been Archive()d from the queue while being placed in the permanent store.
// Otherwise, it will have been Release()d or Bury()ied as appropriate.
//
// The supplied shell is the shell to execute the Cmd under, ideally bash
// (something that understands the command "set -o pipefail").
//
// You have to have been the one to Reserve() the supplied Job, or this will
// immediately return an error. NB: the peak RAM tracking assumes we are running
// on a modern linux system with /proc/*/smaps.
func (c *Client) Execute(ctx context.Context, job *Job, shell string) error {
ctx = clog.ContextWithJobKey(ctx, job.Key())
// quickly check upfront that we Reserve()d the job; this isn't required
// for other methods since the server does this check and returns an error,
// but in this case we want to avoid starting to execute the command before
// finding out about this problem
if c.clientid != job.ReservedBy {
return Error{"Execute", job.Key(), ErrMustReserve}
}
// we have a convienience feature that can run Cmd in a container, so get
// possibly modified Cmd
jc, cmdLineCleanup, err := job.CmdLine(ctx)
if err != nil {
return fmt.Errorf("failed to set up cmd file: %w", err)
}
defer cmdLineCleanup()
// we support arbitrary shell commands that may include semi-colons,
// quoted stuff and pipes, so it's best if we just pass it to bash
if strings.Contains(jc, " | ") {
jc = "set -o pipefail; " + jc
}
cmd := exec.Command(shell, "-c", jc) // #nosec Our whole purpose is to allow users to run arbitrary commands via us...
// we'll filter STDERR/OUT of the cmd to keep only the first and last line
// of any contiguous block of \r terminated lines (to mostly eliminate
// progress bars), and we'll store only up to 4kb of their head and tail
errReader, err := cmd.StderrPipe()
if err != nil {
return fmt.Errorf("failed to create a pipe for STDERR from cmd [%s]: %w", jc, err)
}
stderr := &prefixSuffixSaver{N: 4096}
stderrWait := stdFilter(errReader, stderr)
outReader, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("failed to create a pipe for STDOUT from cmd [%s]: %w", jc, err)
}
stdout := &prefixSuffixSaver{N: 4096}
stdoutWait := stdFilter(outReader, stdout)
// we'll run the command from the desired directory, which must exist or
// it will fail
if fi, errf := os.Stat(job.Cwd); errf != nil || !fi.Mode().IsDir() {
errm := os.MkdirAll(job.Cwd, os.ModePerm)
if _, errs := os.Stat(job.Cwd); errs != nil {
errb := c.Bury(job, nil, FailReasonCwd)
extra := ""
if errb != nil {
extra = fmt.Sprintf(" (and burying the job failed: %s)", errb)
}
return fmt.Errorf("working directory [%s] does not exist%s: %w", job.Cwd, extra, errm)
}
}
var actualCwd, tmpDir string
var dirsToCheckDiskSpace []string
if job.CwdMatters {
cmd.Dir = job.Cwd
} else {
// we'll create a unique location to work in
actualCwd, tmpDir, err = mkHashedDir(job.Cwd, job.Key())
if err != nil {
buryErr := fmt.Errorf("could not create working directory: %w", err)
errb := c.Bury(job, nil, FailReasonCwd, buryErr)
if errb != nil {
buryErr = fmt.Errorf("%v (and burying the job failed: %w)", buryErr, errb)
}
return buryErr
}
cmd.Dir = actualCwd
job.Lock()
job.ActualCwd = actualCwd
job.Unlock()
dirsToCheckDiskSpace = append(dirsToCheckDiskSpace, tmpDir)
}
// before doing any other pre-start tasks, which might take time, start
// touching the job, and keep doing so until after we've run the job and
// carried out post-exit tasks
touchTicker := time.NewTicker(ClientTouchInterval) //*** this should be less than the ServerItemTTR set when the server started, not a fixed value
var wkbsMutex sync.RWMutex
whenKilledByServer := func() {}
stopTouching := make(chan bool, 2)
stopChecking := make(chan bool, 2)
go func() {
for {
select {
case <-touchTicker.C:
kc, errf := c.Touch(job)
if kc {
wkbsMutex.RLock()
defer wkbsMutex.RUnlock()
whenKilledByServer()
touchTicker.Stop()
clog.Warn(ctx, "kill requested externally")
stopChecking <- true
return
}
if errf != nil {
// we may have lost contact with the manager; this is OK. We
// will keep trying to touch until it works
clog.Warn(ctx, "could not touch", "err", errf)
continue
}
case <-stopTouching:
touchTicker.Stop()
return
}
}
}()
defer func() {
stopTouching <- true
}()
var myerr error
var onCwd bool
var prependPath string
if job.BsubMode != "" {
// create our bsub symlinks in a tmp dir
prependPath, err = os.MkdirTemp("", lsfEmulationDir)
if err != nil {
stopTouching <- true
buryErr := fmt.Errorf("could not create lsf emulation directory: %w", err)
errb := c.Bury(job, nil, FailReasonCwd, buryErr)
if errb != nil {
buryErr = fmt.Errorf("%v (and burying the job failed: %w)", buryErr, errb)
}
return buryErr
}
defer func() {
errr := os.RemoveAll(prependPath)
if errr != nil {
if myerr == nil {
myerr = errr
} else {
myerr = fmt.Errorf("%v (and removing the lsf emulation dir failed: %w)", myerr, errr)
}
}
}()
err = c.createLSFSymlinks(prependPath, job)
if err != nil {
return err
}
onCwd = job.CwdMatters
}
// if we are a child job of another running on the same host, we expect
// mounting to fail since we're running in the same directory as our
// parent
var mountCouldFail bool
host, err := os.Hostname()
if err != nil {
host = localhost
}
if jsonStr := job.Getenv("WR_BSUB_CONFIG"); jsonStr != "" {
configJob := &Job{}
if erru := json.Unmarshal([]byte(jsonStr), configJob); erru == nil && configJob.Host == host {
mountCouldFail = true
// *** but the problem with this is, the parent job could finish
// while we're still running, and unmount!...
}
}
// we'll mount any configured remote file systems
uniqueCacheDirs, uniqueMountedDirs, err := job.Mount(onCwd)
if err != nil && !mountCouldFail {
if strings.Contains(err.Error(), "fusermount exited with code 256") {
// *** not sure what causes this, but perhaps trying again after a
// few seconds will help?
<-time.After(5 * time.Second)
uniqueCacheDirs, uniqueMountedDirs, err = job.Mount()
}
if err != nil {
stopTouching <- true
buryErr := fmt.Errorf("failed to mount remote file system(s): %w (%s)", err, os.Environ())
errb := c.Bury(job, nil, FailReasonMount, buryErr)
if errb != nil {
buryErr = fmt.Errorf("%v (and burying the job failed: %w)", buryErr, errb)
}
return buryErr
}
}
// later, check mount cache dirs for disk usage
if len(uniqueCacheDirs) > 0 {
dirsToCheckDiskSpace = append(dirsToCheckDiskSpace, uniqueCacheDirs...)
}
// later, check unmounted parts of unique cwd for disk usage, or mounted
// parts that start off empty
dontCheckDirs := make(map[string]bool)
if actualCwd != "" {
if len(uniqueMountedDirs) > 0 {
noCheck := false
for _, dir := range uniqueMountedDirs {
d, erro := os.Open(dir)
if erro == nil {
files, errr := d.Readdir(1)
if errc := d.Close(); errc != nil {
if myerr == nil {
myerr = errc
} else {
myerr = fmt.Errorf("%v (and closing dir failed: %w)", myerr, errc)
}
}
if (errr == nil || errr == io.EOF) && len(files) == 0 {
continue
}
}
if dir == cmd.Dir {
noCheck = true
break
}
if strings.HasPrefix(dir, actualCwd) {
dontCheckDirs[dir] = true
}
}
if !noCheck {
dirsToCheckDiskSpace = append(dirsToCheckDiskSpace, actualCwd)
}
} else {
dirsToCheckDiskSpace = append(dirsToCheckDiskSpace, actualCwd)
}
}
// and we'll run it with the environment variables that were present when
// the command was first added to the queue (or if none, current env vars,
// and in either case, including any overrides) *** we need a way for users
// to update a job with new env vars
env, err := job.Env()
if err != nil {
stopTouching <- true
errb := c.Bury(job, nil, FailReasonEnv)
extra := ""
if errb != nil {
extra = fmt.Sprintf(" (and burying the job failed: %s)", errb)
}
_, erru := job.Unmount(true)
if erru != nil {
extra += fmt.Sprintf(" (and unmounting the job failed: %s)", erru)
}
return fmt.Errorf("failed to extract environment variables for job [%s]: %w%s", job.Key(), err, extra)
}
if tmpDir != "" {
// (this works fine even if tmpDir has a space in one of the dir names)
env = envOverride(env, []string{"TMPDIR=" + tmpDir})
defer func() {
errr := os.RemoveAll(tmpDir)
if errr != nil {
if myerr == nil {
myerr = errr
} else {
myerr = fmt.Errorf("%v (and removing the tmpdir failed: %w)", myerr, errr)
}
}
}()
if job.ChangeHome {
env = envOverride(env, []string{"HOME=" + actualCwd})
}
}
if prependPath != "" {
// alter env PATH to have prependPath come first
override := []string{"PATH=" + prependPath}
for _, envvar := range env {
pair := strings.Split(envvar, "=")
if pair[0] == "PATH" {
override[0] += ":" + pair[1]
break
}
}
env = envOverride(env, override)
// add an environment variable of this job as JSON, so that any cloud_*
// or mount options can be copied to child jobs created via our bsub
// symlink. (It will also need to know our deployment, stored in
// BsubMode, and to know the host we're running on in case our children
// run on the same host as us and therefore any mounts are expected to
// fail)
simplified := &Job{
Requirements: job.Requirements,
BsubMode: job.BsubMode,
Host: host,
}
if _, exists := job.Requirements.Other["cloud_shared"]; !exists {
simplified.MountConfigs = job.MountConfigs
}
jobJSON, errm := json.Marshal(simplified)
if errm != nil {
errb := c.Bury(job, nil, fmt.Sprintf("could not convert job to JSON: %s", errm))
extra := ""
if errb != nil {
extra = fmt.Sprintf(" (and burying the job failed: %s)", errb)
}
return fmt.Errorf("could not convert job to JSON: %w%s", errm, extra)
}
env = envOverride(env, []string{
"WR_BSUB_CONFIG=" + string(jobJSON),
"WR_MANAGER_HOST=" + c.host,
"WR_MANAGER_PORT=" + c.port,
"LSF_SERVERDIR=/dev/null",
"LSF_LIBDIR=/dev/null",
"LSF_ENVDIR=/dev/null",
"LSF_BINDIR=" + prependPath,
})
}
cmd.Env = env
// if docker monitoring has been requested, try and get the docker client
// now and fail early if we can't
var dockerClient *container.Operator
var dockerInterator *docker.Interactor
var cli *client.Client
var monitorDocker, getFirstDockerContainer bool
if job.MonitorDocker != "" {
monitorDocker = true
cli, err = client.NewEnvClient()
if err != nil {
stopTouching <- true
buryErr := fmt.Errorf("failed to create docker client: %w", err)
errb := c.Bury(job, nil, FailReasonDocker, buryErr)
if errb != nil {
buryErr = fmt.Errorf("%v (and burying the job failed: %w)", buryErr, errb)
}
return buryErr
}
dockerInterator = docker.NewInteractor(cli)
dockerClient = container.NewOperator(dockerInterator)
// if we've been asked to monitor the first container that appears,
// remember existing containers
if job.MonitorDocker == "?" {
getFirstDockerContainer = true
errc := dockerClient.RememberCurrentContainers(ctx)
if errc != nil {
stopTouching <- true
buryErr := fmt.Errorf("failed to get docker containers: %w", errc)
errb := c.Bury(job, nil, FailReasonDocker, buryErr)
if errb != nil {
buryErr = fmt.Errorf("%v (and burying the job failed: %w)", buryErr, errb)
}
return buryErr
}
}
}
// intercept certain signals (under LSF and SGE, SIGUSR2 may mean out-of-
// time, but there's no reliable way of knowing out-of-memory, so we will
// just treat them all the same)
sigs := make(chan os.Signal, 5)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2)
defer signal.Stop(sigs)
// start running the command
endT := time.Now().Add(job.Requirements.Time)
err = cmd.Start()
if err != nil {
// some obscure internal error about setting things up
stopTouching <- true
errr := c.Release(job, nil, FailReasonStart)
extra := ""
if errr != nil {
extra = fmt.Sprintf(" (and releasing the job failed: %s)", errr)
}
_, erru := job.Unmount(true)
if erru != nil {
extra += fmt.Sprintf(" (and unmounting the job failed: %s)", erru)
}
return fmt.Errorf("could not start command [%s]: %w%s", jc, err, extra)
}
// update the server that we've started the job
err = c.Started(job, cmd.Process.Pid)
if err != nil {
// if we can't access the server, may as well bail out now - kill the
// command (and don't bother trying to Release(); it will auto-Release)
errk := cmd.Process.Kill()
extra := ""
if errk != nil {
extra = fmt.Sprintf(" (and killing the cmd failed: %s)", errk)
}
errt := job.TriggerBehaviours(false)
if errt != nil {
extra += fmt.Sprintf(" (and triggering behaviours failed: %s)", errt)
}
_, erru := job.Unmount(true)
if erru != nil {
extra += fmt.Sprintf(" (and unmounting the job failed: %s)", erru)
}
return fmt.Errorf("command [%s] started running, but I killed it due to a jobqueue server error: %w%s", job.Cmd, err, extra)
}
// update peak mem and disk used by command, and check if we use too much
// resources, every second. Also check for signals
peakmem := 0
var peakdisk int64
dockerCPU := 0
resourceTicker := time.NewTicker(1 * time.Second)
machineRAM := 0
ranoutMem := false
ranoutTime := false
ranoutDisk := false
signalled := false
killCalled := false
var killErr error
var closeErr error
var stateMutex sync.Mutex
diskUsageCheck := func() (int64, error) {
var used int64
for _, dir := range dirsToCheckDiskSpace {
var thisUsed int64
var thisErr error
if dir == actualCwd {
thisUsed, thisErr = currentDisk(dir, dontCheckDirs)
} else {
thisUsed, thisErr = currentDisk(dir)
}
if thisErr != nil {
return 0, thisErr
}
used += thisUsed
}
return used, nil
}
finishedChecking := make(chan bool)
go func() {
var dockerContainerID string
killCmd := func() error {
// get children first
children, errc := getChildProcesses(int32(cmd.Process.Pid))
// then kill *** race condition if cmd spawns more children...
errk := cmd.Process.Kill()
if errc != nil {
if errk == nil {
errk = errc
} else {
errk = fmt.Errorf("%v, and getting child processes failed: %w", errk, errc)
}
}
if dockerContainerID != "" {
// kill the docker container as well
errd := dockerClient.KillContainer(ctx, dockerContainerID)
if errk == nil {
errk = errd
} else {
errk = fmt.Errorf("%v, and killing the docker container failed: %w", errk, errd)
}
}
for _, child := range children {
// try and kill any children in case the above didn't already
// result in their death
errc = child.Kill()
if errk == nil {
errk = errc
} else {
errk = fmt.Errorf("%v, and killing its child process failed: %w", errk, errc)
}
}
return errk