/
server.go
2859 lines (2562 loc) · 86.9 KB
/
server.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 to implement a jobqueue server.
import (
"context"
crand "crypto/rand"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"math"
"net"
"net/http"
"os"
"os/signal"
"path"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
sync "github.com/sasha-s/go-deadlock"
"github.com/wtsi-ssg/wr/clog"
"github.com/VertebrateResequencing/wr/cloud"
"github.com/VertebrateResequencing/wr/internal"
"github.com/VertebrateResequencing/wr/jobqueue/scheduler"
"github.com/VertebrateResequencing/wr/limiter"
"github.com/VertebrateResequencing/wr/queue"
"github.com/gorilla/websocket"
"github.com/grafov/bcast" // *** must be commit e9affb593f6c871f9b4c3ee6a3c77d421fe953df or status web page updates break in certain cases
"github.com/inconshreveable/log15"
logext "github.com/inconshreveable/log15/ext"
"github.com/sb10/waitgroup"
"github.com/ugorji/go/codec"
mangos "nanomsg.org/go-mangos"
"nanomsg.org/go-mangos/protocol/rep"
"nanomsg.org/go-mangos/transport/tlstcp"
)
// Err* constants are found in our returned Errors under err.Err, so you can
// cast and check if it's a certain type of error. ServerMode* constants are
// used to report on the status of the server, found inside ServerInfo.
const (
ErrInternalError = "internal error"
ErrUnknownCommand = "unknown command"
ErrBadRequest = "bad request (missing arguments?)"
ErrBadJob = "bad job (not in queue or correct sub-queue)"
ErrMissingJob = "corresponding job not found"
ErrUnknown = "unknown error"
ErrClosedInt = "queues closed due to SIGINT"
ErrClosedTerm = "queues closed due to SIGTERM"
ErrClosedCert = "queues closed due to certificate expiry"
ErrClosedStop = "queues closed due to manual Stop()"
ErrQueueClosed = "queue closed"
ErrNoHost = "could not determine the non-loopback ip address of this host"
ErrNoServer = "could not reach the server"
ErrMustReserve = "you must Reserve() a Job before passing it to other methods"
ErrDBError = "failed to use database"
ErrS3DBBackupPath = "invalid S3 database backup path"
ErrPermissionDenied = "bad token: permission denied"
ErrBeingDrained = "server is being drained"
ErrStopReserving = "recovered on a new server; you should stop reserving"
ErrBadLimitGroup = "colons in limit group names must be followed by integers"
ServerModeNormal = "started"
ServerModePause = "paused"
ServerModeDrain = "draining"
)
// ServerVersion gets set during build:
// go build -ldflags "-X github.com/VertebrateResequencing/wr/jobqueue.ServerVersion=`git describe --tags --always --long --dirty`"
var ServerVersion string
// 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 (
ServerInterruptTime = 1 * time.Second
ServerItemTTR = 60 * time.Second
ServerReserveTicker = 1 * time.Second
ServerCheckRunnerTime = 1 * time.Minute
ServerShutdownWaitTime = 5 * time.Second
ServerLostJobCheckTimeout = 15 * time.Second
ServerLostJobCheckRetryTime = 30 * time.Minute
ServerMaximumRunForResourceRecommendation = 100
ServerMinimumScheduledForResourceRecommendation = 10
ServerLogClientErrors = true
serverShutdownRunnerTickerTime = 50 * time.Millisecond
// httpServerShutdownTime is the time we'll wait before forcing
// http.Server{}.Shutdown() to complete, otherwise it takes 500ms if there
// were listeners.
httpServerShutdownTime = 1 * time.Millisecond
)
// BsubID is used to give added jobs a unique (atomically incremented) id when
// pretending to be bsub.
var BsubID uint64
// Error records an error and the operation and item that caused it.
type Error struct {
Op string // name of the method
Item string // the item's key
Err string // one of our Err* vars
}
func (e Error) Error() string {
return "jobqueue " + e.Op + "(" + e.Item + "): " + e.Err
}
// serverResponse is the struct that the server sends to clients over the
// network in response to their clientRequest.
type serverResponse struct {
Err string // string instead of error so we can decode on the client side
Added int
Existed int
AddedIDs []string
Modified map[string]string
KillCalled bool
Job *Job
Jobs []*Job
Limit int
LimitGroups map[string]int
SInfo *ServerInfo
SStats *ServerStats
DB []byte
Path string
BadServers []*BadServer
}
// ServerInfo holds basic addressing info about the server.
type ServerInfo struct {
Addr string // ip:port
Host string // hostname
Port string // port
WebPort string // port of the web interface
PID int // process id of server
Deployment string // deployment the server is running under
Scheduler string // the name of the scheduler that jobs are being submitted to
Mode string // ServerModeNormal if the server is running normally, or ServerModeDrain|Paused if draining or paused
}
// ServerVersions holds the server version (git tag) and API version supported.
type ServerVersions struct {
Version string
API string
}
// ServerStats holds information about the jobqueue server for sending to
// clients.
type ServerStats struct {
Delayed int // how many jobs are waiting following a possibly transient error
Ready int // how many jobs are ready to begin running
Running int // how many jobs are currently running
Buried int // how many jobs are no longer being processed because of seemingly permanent errors
ETC time.Duration // how long until the the slowest of the currently running jobs is expected to complete
}
type rgToKeys struct {
sync.RWMutex
lookup map[string]map[string]bool
}
// jstateCount is the state count change we send to the status webpage; we are
// representing the jobs moving from one state to another.
type jstateCount struct {
RepGroup string // "+all+" is the special group representing all live jobs across all RepGroups
FromState JobState
ToState JobState
Count int // num in FromState drop by this much, num in ToState rise by this much
}
// BadServer is the details of servers that have gone bad that we send to the
// status webpage. Previously bad servers can also be sent if they become good
// again, hence the IsBad boolean.
type BadServer struct {
ID string
Name string
IP string
Date int64 // seconds since Unix epoch
IsBad bool
Problem string
}
// schedulerIssue is the details of scheduler problems encountered that we send
// to the status webpage.
type schedulerIssue struct {
Msg string
FirstDate int64 // seconds since Unix epoch
LastDate int64
Count int // the number of identical Msg sent
}
// sgroup represents a scheduler group
type sgroup struct {
name string
count int
skipped int
req *scheduler.Requirements
priority uint8
sync.RWMutex
}
// clone creates a new copy of the sgroup with the given count
func (s *sgroup) clone(count int) *sgroup {
s.RLock()
defer s.RUnlock()
return &sgroup{
name: s.name,
count: count,
skipped: s.skipped,
req: s.req.Clone(),
priority: s.priority,
}
}
// getCount is a thread-safe way of getting the current count
func (s *sgroup) getCount() int {
s.RLock()
defer s.RUnlock()
return s.count
}
// decrement is a thread-safe way of dropping the count of the group by the
// given amount.
//
// If the sgroup's skipped is greater than 0, first decrements that and only
// decrements count if given drop is greater than skipped.
//
// Returns the new count, or -1 if the count didn't change.
func (s *sgroup) decrement(drop int) int {
if drop < 1 {
return -1
}
s.Lock()
defer s.Unlock()
if s.skipped > 0 {
if drop <= s.skipped {
s.skipped -= drop
return -1
}
drop -= s.skipped
s.skipped = 0
}
prev := s.count
s.count -= drop
if s.count < 0 {
s.count = 0
}
if s.count == prev {
return -1
}
return s.count
}
// hasSkips is a thread-safe way of seeing if skipped is greater than 0.
func (s *sgroup) hasSkips() bool {
s.RLock()
defer s.RUnlock()
return s.skipped > 0
}
// Server represents the server side of the socket that clients Connect() to.
type Server struct {
token []byte
uploadDir string
sock mangos.Socket
ch codec.Handle
rc string // runner command string compatible with fmt.Sprintf(..., schedulerGroup, deployment, serverAddr, reserveTimeout, maxMinsAllowed)
ServerInfo *ServerInfo
ServerVersions *ServerVersions
db *db
done chan error
stopSigHandling chan bool
stopClientHandling chan bool
wg *waitgroup.WaitGroup
q *queue.Queue
rpl *rgToKeys
limiter *limiter.Limiter
scheduler *scheduler.Scheduler
previouslyScheduledGroups map[string]*sgroup
httpServer *http.Server
statusCaster *bcast.Group
badServerCaster *bcast.Group
schedCaster *bcast.Group
racCheckTimer *time.Timer
pauseRequests int
wsconns map[string]*websocket.Conn
badServers map[string]*cloud.Server
schedIssues map[string]*schedulerIssue
racmutex sync.RWMutex // to protect the readyaddedcallback
bsmutex sync.RWMutex
simutex sync.RWMutex
krmutex sync.RWMutex
ssmutex sync.RWMutex // "server state mutex" to protect up, drain, blocking and ServerInfo.Mode
psgmutex sync.RWMutex // to protect previouslyScheduledGroups
rpmutex sync.Mutex // to protect racPending, racRunning and waitingReserves
sync.Mutex
wsmutex sync.Mutex
up bool
drain bool
blocking bool
racChecking bool
killRunners bool
racPending bool
racRunning bool
waitingReserves []chan struct{}
recoveredRunningJobs map[string]bool
}
// ServerConfig is supplied to Serve() to configure your jobqueue server. All
// fields are required with no working default unless otherwise noted.
type ServerConfig struct {
// Port for client-server communication.
Port string
// Port for the web interface.
WebPort string
// Name of the desired scheduler (eg. "local" or "lsf" or "openstack") that
// jobs will be submitted to.
SchedulerName string
// SchedulerConfig should define the config options needed by the chosen
// scheduler, eg. scheduler.ConfigLocal{Deployment: "production", Shell:
// "bash"} if using the local scheduler.
SchedulerConfig interface{}
// The command line needed to bring up a jobqueue runner client, which
// should contain 6 %s parts which will be replaced with the scheduler
// group, deployment, ip:host address of the server, domain name that the
// server's certificate should be valid for, reservation time out and
// maximum number of minutes allowed, eg. "my_jobqueue_runner_client --group
// '%s' --deployment %s --server '%s' --domain %s --reserve_timeout %d
// --max_mins %d". If you supply an empty string (the default), runner
// clients will not be spawned; for any work to be done you will have to run
// your runner client yourself manually.
RunnerCmd string
// Absolute path to where the database file should be saved. The database is
// used to ensure no loss of added commands, to keep a permanent history of
// all jobs completed, and to keep various stats, amongst other things.
DBFile string
// Absolute path to where the database file should be backed up to.
DBFileBackup string
// Absolute path to where the server will store the authorization token
// needed by clients to communicate with the server. Storing it in a file
// could make using any CLI clients more convenient. The file will be
// read-only by the user starting the server. The default of empty string
// means the token is not saved to disk.
TokenFile string
// Absolute path to where CA PEM file is that will be used for
// securing access to the web interface. If the given file does not exist,
// a certificate will be generated for you at this path.
CAFile string
// Absolute path to where certificate PEM file is that will be used for
// securing access to the web interface. If the given file does not exist,
// a certificate will be generated for you at this path.
CertFile string
// Absolute path to where key PEM file is that will be used for securing
// access to the web interface. If the given file does not exist, a
// key will be generated for you at this path.
KeyFile string
// Domain that a generated CertFile should be valid for. If not supplied,
// defaults to "localhost".
//
// When using your own CertFile, this should be set to a domain that the
// certifcate is valid for, as when the server spawns clients, those clients
// will validate the server's certifcate based on this domain. For the web
// interface and REST API, it is up to you to ensure that your DNS has an
// entry for this domain that points to the IP address of the machine
// running your server.
CertDomain string
// If using a CertDomain, and if you have (or very soon will) set the domain
// to point to the server's IP address, set this to true. This will result
// in runner clients spawned by the server being told to access the server
// at CertDomain (instead of the current IP address), which means if the
// server's host is lost and you bring it back at a different IP address and
// update the domain again, those clients will be able to reconnect and
// continue running.
DomainMatchesIP bool
// AutoConfirmDead is the time that a spawned server must be considered
// dead before it is automatically destroyed and jobs running on it are
// confirmed lost. The default of 0 time disables automatic destruction.
// Only relevant when using a scheduler that spawns servers on which to
// execute jobs.
AutoConfirmDead time.Duration
// Name of the deployment ("development" or "production"); development
// databases are deleted and recreated on start up by default.
Deployment string
// CIDR is the IP address range of your network. When the server needs to
// know its own IP address, it uses this CIDR to confirm it got it correct
// (ie. it picked the correct network interface). You can leave this unset,
// in which case it will do its best to pick correctly. (This is only a
// possible issue if you have multiple network interfaces.)
CIDR string
// UploadDir is the directory where files uploaded to the Server will be
// stored. They get given unique names based on the MD5 checksum of the file
// uploaded. Defaults to /tmp.
UploadDir string
// Logger is a logger object that will be used to log uncaught errors and
// debug statements. "Uncought" errors are all errors generated during
// operation that either shouldn't affect the success of operations, and can
// be ignored (logged at the Warn level, and which is why the errors are not
// returned by the methods generating them), or errors that could not be
// returned (logged at the Error level, eg. generated during a go routine,
// such as errors by the server handling a particular client request).
// We attempt to recover from panics during server operation and log these
// at the Crit level.
//
// If your logger is levelled and set to the debug level, you will also get
// information tracking the inner workings of the server.
//
// If this is unset, nothing is logged (defaults to a logger using a
// log15.DiscardHandler()).
Logger log15.Logger
}
// Serve is for use by a server executable and makes it start listening on
// localhost at the configured port for Connect()ions from clients, and then
// handles those clients.
//
// It returns a *Server that you will typically call Block() on to block until
// your executable receives a SIGINT or SIGTERM, or you call Stop(), at which
// point the queues will be safely closed (you'd probably just exit at that
// point).
//
// If it creates a db file or recreates one from backup, and if it creates TLS
// certificates, it will say what it did in the returned msg string.
//
// The returned token must be provided by any client to authenticate. The server
// is a single user system, so there is only 1 token kept for its entire
// lifetime. If config.TokenFile has been set, the token will also be written to
// that file, potentially making it easier for any CLI clients to authenticate
// with this returned Server. If that file already exists prior to calling this,
// the token in that file will be re-used, allowing reconnection of existing
// clients if this server dies ungracefully.
//
// The possible errors from Serve() will be related to not being able to start
// up at the supplied address; errors encountered while dealing with clients are
// logged but otherwise ignored.
//
// It also spawns your runner clients as needed, running them via the configured
// job scheduler, using the configured shell. It determines the command line to
// execute for your runner client from the configured RunnerCmd string you
// supplied.
func Serve(ctx context.Context, config ServerConfig) (s *Server, msg string, token []byte, err error) {
// if a logger was configured we will log debug statements and "harmless"
// errors not worth returning (or not possible to return), along with
// panics. Otherwise we create a default logger that discards all log
// attempts.
serverLogger := config.Logger
if serverLogger == nil {
serverLogger = log15.New()
serverLogger.SetHandler(log15.DiscardHandler())
} else {
serverLogger = serverLogger.New()
}
defer internal.LogPanic(ctx, "jobqueue serve", true)
// generate a secure token for clients to authenticate with
token, err = generateToken(config.TokenFile)
if err != nil {
return s, msg, token, err
}
// check if the cert files are available
httpAddr := "0.0.0.0:" + config.WebPort
caFile := config.CAFile
certFile := config.CertFile
keyFile := config.KeyFile
certDomain := config.CertDomain
if certDomain == "" {
certDomain = localhost
}
err = internal.CheckCerts(certFile, keyFile)
var certMsg string
if err != nil {
// if not, generate our own
err = internal.GenerateCerts(caFile, certFile, keyFile, certDomain,
internal.DefaultBitsForRootRSAKey, internal.DefualtBitsForServerRSAKey, crand.Reader, internal.DefaultCertFileFlags)
if err != nil {
serverLogger.Error("GenerateCerts failed", "err", err)
return s, msg, token, err
}
certMsg = "created a new key and certificate for TLS"
}
// we need to persist stuff to disk, and we do so using boltdb
db, msg, err := initDB(ctx, config.DBFile, config.DBFileBackup, config.Deployment)
if certMsg != "" {
if msg == "" {
msg = certMsg
} else {
msg = certMsg + ". " + msg
}
}
if err != nil {
return s, msg, token, err
}
defer func() {
if err != nil {
errc := db.close(ctx)
if errc != nil {
err = fmt.Errorf("%s; db close also failed: %s", err.Error(), errc.Error())
}
}
}()
sock, err := rep.NewSocket()
if err != nil {
return s, msg, token, err
}
defer func() {
if err != nil {
errc := sock.Close()
if errc != nil {
err = fmt.Errorf("%s; socket close also failed: %s", err.Error(), errc.Error())
}
}
}()
// we open ourselves up to possible denial-of-service attack if a client
// sends us tons of data, but at least the client doesn't silently hang
// forever when it legitimately wants to Add() a ton of jobs
// unlimited Recv() length
if err = sock.SetOption(mangos.OptionMaxRecvSize, 0); err != nil {
return s, msg, token, err
}
// we use raw mode, allowing us to respond to multiple clients in
// parallel
if err = sock.SetOption(mangos.OptionRaw, true); err != nil {
return s, msg, token, err
}
// we'll wait ServerInterruptTime to recv from clients before trying again,
// allowing us to check if signals have been passed
if err = sock.SetOption(mangos.OptionRecvDeadline, ServerInterruptTime); err != nil {
return s, msg, token, err
}
// check certificate expiry, because everything breaks with generic errors
// when it expires
expiry, err := internal.CertExpiry(caFile)
if err != nil {
return s, msg, token, err
}
if time.Now().After(expiry) {
return s, msg, token, internal.CertError{Type: internal.ErrExpiredCert, Path: caFile}
}
expiry2, err := internal.CertExpiry(certFile)
if err != nil {
return s, msg, token, err
}
if time.Now().After(expiry2) {
return s, msg, token, internal.CertError{Type: internal.ErrExpiredCert, Path: certFile}
}
if expiry2.Before(expiry) {
expiry = expiry2
}
// have mangos listen using TLS over TCP
sock.AddTransport(tlstcp.NewTransport())
cer, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return s, msg, token, err
}
tlsConfig := &tls.Config{Certificates: []tls.Certificate{cer}}
listenOpts := make(map[string]interface{})
caCert, err := os.ReadFile(caFile)
if err == nil {
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = certPool
}
listenOpts[mangos.OptionTLSConfig] = tlsConfig
if err = sock.ListenOptions("tls+tcp://0.0.0.0:"+config.Port, listenOpts); err != nil {
return s, msg, token, err
}
// serving will happen in a goroutine that will stop on SIGINT or SIGTERM,
// or if something is sent on the stopSigHandling channel. The done channel
// is used to report back to a user that called Block() when and why we
// stopped serving. stopClientHandling is used to stop client handling at
// the right moment during the shutdown process. To know when all the
// goroutines we start actually finish, the shutdown process will check a
// waitgroup as well.
sigs := make(chan os.Signal, 2)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
stopSigHandling := make(chan bool, 1)
stopClientHandling := make(chan bool)
done := make(chan error, 1)
wg := waitgroup.New()
// if we end up spawning clients on other machines, they'll need to know
// our non-loopback ip address so they can connect to us
var ip string
if config.DomainMatchesIP {
ip = config.CertDomain
} else {
ip, err = internal.CurrentIP(config.CIDR)
if err != nil {
serverLogger.Error("getting current IP failed", "err", err)
}
if ip == "" {
return s, msg, token, Error{"Serve", "", ErrNoHost}
}
}
// we will spawn runner clients via the requested job scheduler
sch, err := scheduler.New(ctx, config.SchedulerName, config.SchedulerConfig)
if err != nil {
return s, msg, token, err
}
uploadDir := config.UploadDir
if uploadDir == "" {
uploadDir = "/tmp"
}
// our limiter will use a callback that gets group limits from our database
l := limiter.New(db.retrieveLimitGroup)
s = &Server{
ServerInfo: &ServerInfo{Addr: ip + ":" + config.Port, Host: certDomain, Port: config.Port, WebPort: config.WebPort, PID: os.Getpid(), Deployment: config.Deployment, Scheduler: config.SchedulerName, Mode: ServerModeNormal},
ServerVersions: &ServerVersions{Version: ServerVersion, API: restAPIVersion},
token: token,
uploadDir: uploadDir,
sock: sock,
ch: new(codec.BincHandle),
rpl: &rgToKeys{lookup: make(map[string]map[string]bool)},
limiter: l,
db: db,
stopSigHandling: stopSigHandling,
stopClientHandling: stopClientHandling,
done: done,
wg: wg,
up: true,
scheduler: sch,
previouslyScheduledGroups: make(map[string]*sgroup),
rc: config.RunnerCmd,
wsconns: make(map[string]*websocket.Conn),
statusCaster: bcast.NewGroup(),
badServerCaster: bcast.NewGroup(),
badServers: make(map[string]*cloud.Server),
schedCaster: bcast.NewGroup(),
schedIssues: make(map[string]*schedulerIssue),
recoveredRunningJobs: make(map[string]bool),
}
// if we're restarting from a state where there were incomplete jobs, we
// need to load those in to our queue now
s.createQueue(ctx)
priorJobs, err := db.recoverIncompleteJobs()
if err != nil {
return nil, msg, token, err
}
if len(priorJobs) > 0 {
var loginUser string
var ttd time.Duration
if cloudConfig, ok := config.SchedulerConfig.(scheduler.CloudConfig); ok {
// *** for server recovery purposes, which involves ssh'ing to
// existing servers and monitoring them, we need to know the login
// username, but we don't. The best we can do is hope the configured
// default username is the right one
loginUser = cloudConfig.GetOSUser()
ttd = cloudConfig.GetServerKeepTime()
}
var itemdefs []*queue.ItemDef
for _, job := range priorJobs {
var deps []string
deps, err = job.Dependencies.incompleteJobKeys(s.db)
if err != nil {
return nil, msg, token, err
}
itemdef := &queue.ItemDef{Key: job.Key(), ReserveGroup: job.getSchedulerGroup(), Data: job, Priority: job.Priority, Delay: 0 * time.Second, TTR: ServerItemTTR, Dependencies: deps}
switch job.State {
case JobStateRunning:
itemdef.StartQueue = queue.SubQueueRun
if len(job.LimitGroups) > 0 {
if s.limiter.Increment(ctx, job.LimitGroups) {
// (our note of incrementation done in the server that died
// is not stored in the db)
job.noteIncrementedLimitGroups(job.LimitGroups)
}
}
req := reqForScheduler(job.Requirements)
errr := s.scheduler.Recover(ctx, fmt.Sprintf(s.rc, req.Stringify(), s.ServerInfo.Deployment, s.ServerInfo.Addr, s.ServerInfo.Host, s.scheduler.ReserveTimeout(ctx, req), int(s.scheduler.MaxQueueTime(req).Minutes())), req, &scheduler.RecoveredHostDetails{Host: job.Host, UserName: loginUser, TTD: ttd})
if errr != nil {
clog.Warn(ctx, "recovery of an old cmd failed", "cmd", job.Cmd, "host", job.Host, "err", errr)
}
s.recoveredRunningJobs[job.Key()] = true
case JobStateBuried:
itemdef.StartQueue = queue.SubQueueBury
}
itemdefs = append(itemdefs, itemdef)
}
_, _, err = s.enqueueItems(ctx, itemdefs)
if err != nil {
return nil, msg, token, err
}
}
// wait for signal or s.Stop() and call s.shutdown(). (We don't use the
// waitgroup here since we call shutdown, which waits on the group)
certExpired := time.After(time.Until(expiry))
go func() {
// log panics and die
defer internal.LogPanic(ctx, "jobqueue serving", true)
for {
select {
case sig := <-sigs:
var reason string
switch sig {
case os.Interrupt:
reason = ErrClosedInt
case syscall.SIGTERM:
reason = ErrClosedTerm
}
signal.Stop(sigs)
s.shutdown(ctx, reason, true, false)
return
case <-certExpired:
signal.Stop(sigs)
s.shutdown(ctx, ErrClosedCert, true, false)
case <-stopSigHandling: // s.Stop() causes this to be sent during s.shutdown(), which it calls
signal.Stop(sigs)
return
}
}
}()
// set up the web interface
ready := make(chan bool)
wgk := wg.Add(1)
go func() {
// log panics and die
defer internal.LogPanic(ctx, "jobqueue web server", true)
defer wg.Done(wgk)
mux := http.NewServeMux()
mux.HandleFunc("/", webInterfaceStatic(ctx, s))
mux.HandleFunc("/status_ws", webInterfaceStatusWS(ctx, s))
mux.HandleFunc(restJobsEndpoint, restJobs(ctx, s))
mux.HandleFunc(restWarningsEndpoint, restWarnings(ctx, s))
mux.HandleFunc(restBadServersEndpoint, restBadServers(ctx, s))
mux.HandleFunc(restFileUploadEndpoint, restFileUpload(ctx, s))
mux.HandleFunc(restInfoEndpoint, restInfo(ctx, s))
mux.HandleFunc(restVersionEndpoint, restVersion(ctx, s))
srv := &http.Server{Addr: httpAddr, Handler: mux}
wgk2 := wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue web server listenAndServe", true)
defer wg.Done(wgk2)
errs := srv.ListenAndServeTLS(certFile, keyFile)
if errs != nil && errs != http.ErrServerClosed {
clog.Error(ctx, "server web interface had problems", "err", errs)
}
}()
s.httpServer = srv
wgk3 := wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue web server status casting", true)
defer wg.Done(wgk3)
s.statusCaster.Broadcasting(0)
}()
wgk4 := wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue web server server casting", true)
defer wg.Done(wgk4)
s.badServerCaster.Broadcasting(0)
}()
wgk5 := wg.Add(1)
go func() {
defer internal.LogPanic(ctx, "jobqueue web server scheduler casting", true)
defer wg.Done(wgk5)
s.schedCaster.Broadcasting(0)
}()
badServerCB := func(server *cloud.Server) {
s.bsmutex.Lock()
skip := false
if server.IsBad() {
// double check that due to timing issues this server hasn't
// been destroyed, which is not something to warn anyone about
if server.Destroyed() {
skip = true
} else {
s.badServers[server.ID] = server
// arrange to confirm this dead after the configured time
if config.AutoConfirmDead > 0 {
go func(id string) {
<-time.After(config.AutoConfirmDead)
s.bsmutex.Lock()
defer s.bsmutex.Unlock()
if badServer, exists := s.badServers[id]; exists && badServer.BadDuration() >= config.AutoConfirmDead {
delete(s.badServers, id)
waited := badServer.BadDuration()
errd := badServer.Destroy(ctx)
clog.Warn(ctx, "server destroyed after remaining bad for some time", "server", id, "waited", waited, "err", errd)
serverIDs := make(map[string]bool)
serverIDs[id] = true
s.killJobsOnServers(ctx, serverIDs)
if errd == nil {
// make the message in the web interface
// about this server go away
s.badServerCaster.Send(&BadServer{
ID: id,
Name: badServer.Name,
IP: badServer.IP,
Date: time.Now().Unix(),
IsBad: false,
Problem: badServer.PermanentProblem(),
})
}
}
}(server.ID)
}
}
} else {
delete(s.badServers, server.ID)
}
s.bsmutex.Unlock()
if !skip {
s.badServerCaster.Send(&BadServer{
ID: server.ID,
Name: server.Name,
IP: server.IP,
Date: time.Now().Unix(),
IsBad: server.IsBad(),
Problem: server.PermanentProblem(),
})
}
}
s.scheduler.SetBadServerCallBack(ctx, badServerCB)
messageCB := func(msg string) {
s.simutex.Lock()
var si *schedulerIssue
var existed bool
if si, existed = s.schedIssues[msg]; existed {
si.LastDate = time.Now().Unix()
si.Count++
} else {
si = &schedulerIssue{
Msg: msg,
FirstDate: time.Now().Unix(),
LastDate: time.Now().Unix(),
Count: 1,
}
s.schedIssues[msg] = si
}
s.simutex.Unlock()
s.schedCaster.Send(si)
}
s.scheduler.SetMessageCallBack(ctx, messageCB)
// wait a while for ListenAndServe() to start listening
<-time.After(10 * time.Millisecond)
ready <- true
}()
<-ready
// store token on disk
if config.TokenFile != "" {
err = os.WriteFile(config.TokenFile, token, 0600)
if err != nil {
return s, msg, token, err
}
}
// now that we're ready, set up responding to command-line clients
wgk = wg.Add(1)
go func() {
// log panics and die
defer internal.LogPanic(ctx, "jobqueue serving", true)
defer wg.Done(wgk)
for {
select {
case <-stopClientHandling: // s.shutdown() sends this
return
default:
// receive a clientRequest from a client
m, rerr := sock.RecvMsg()
if rerr != nil {
s.krmutex.RLock()
inShutdown := s.killRunners
s.krmutex.RUnlock()
if !inShutdown && rerr != mangos.ErrRecvTimeout {
clog.Error(ctx, "Server socket Receive error", "err", rerr)
}
continue
}
// parse the request, do the desired work and respond to the client
wgk2 := wg.Add(1)
go func() {
// log panics and continue
defer internal.LogPanic(ctx, "jobqueue server client handling", false)
defer wg.Done(wgk2)
herr := s.handleRequest(ctx, m)
if ServerLogClientErrors && herr != nil {
s.krmutex.RLock()
inShutdown := s.killRunners
s.krmutex.RUnlock()
if !inShutdown {
clog.Error(ctx, "Server handle client request error", "err", herr)
}
}
}()
}
}
}()
return s, msg, token, err
}
// Block makes you block while the server does the job of serving clients. This
// will return with an error indicating why it stopped blocking, which will
// be due to receiving a signal or because you called Stop()
func (s *Server) Block() error {
s.ssmutex.Lock()
s.blocking = true
s.ssmutex.Unlock()
return <-s.done
}
// Stop will cause a graceful shut down of the server. Supplying an optional
// bool of true will cause Stop() to wait until all runners have exited and
// the server is truly down before returning.
func (s *Server) Stop(ctx context.Context, wait ...bool) {
s.shutdown(ctx, ErrClosedStop, len(wait) == 1 && wait[0], true)
}
// Drain will stop the server spawning new runners and stop Reserve*() from
// returning any more Jobs. Once all current runners exit, we Stop().
func (s *Server) Drain(ctx context.Context) error {
s.ssmutex.Lock()
defer s.ssmutex.Unlock()
if !s.up {
return Error{"Drain", "", ErrNoServer}
}
if s.drain && s.ServerInfo.Mode == ServerModeDrain {
return nil
}
s.drain = true