-
Notifications
You must be signed in to change notification settings - Fork 12
/
server.go
1412 lines (1248 loc) · 41.8 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 cloud
// This file contains the code for the Server struct.
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
sync "github.com/sasha-s/go-deadlock"
"github.com/wtsi-ssg/wr/clog"
mth "github.com/wtsi-ssg/wr/math"
"github.com/VertebrateResequencing/wr/internal"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
const sharePath = "/shared" // mount point for the *SharedDisk methods
const sshShortTimeOut = 15 * time.Second
const localhostName = "localhost"
// maxSSHSessions is the maximum number of sessions we will try and multiplex on
// each ssh client we make for a server. It doesn't matter if this is lower than
// the server is configured for in /etc/ssh/sshd_config (MaxSessions); we create
// more clients than stricly needed, but this is harmless? If it's higher than
// the configured MaxSessions, there doesn't seem to be much we can do about it.
// MaxSessions can't be queried ahead of time, and we can't discover the correct
// value because if we go over it, then all sessions fail, not just the ones
// over the max (and all failures appear at the ~same time if sessions were
// made at the ~same time). The best we can do for now is to set this to sshd's
// default MaxSessions, which is 10. *** can we do better?
const maxSSHSessions = 10
// Flavor describes a "flavor" of server, which is a certain (virtual) hardware
// configuration
type Flavor struct {
ID string
Name string
Cores int
RAM int // MB
Disk int // GB
}
// HasSpaceFor takes the cpu, ram and disk requirements of a command and tells
// you how many of those commands could run simultaneously on a server of our
// flavor. Returns 0 if not even 1 command could fit on a server with this
// flavor.
func (f *Flavor) HasSpaceFor(cores float64, ramMB, diskGB int) int {
if mth.FloatLessThan(float64(f.Cores), cores) || (f.RAM < ramMB) || (f.Disk < diskGB) {
return 0
}
var canDo int
if cores == 0 {
// rather than allow an infinite or very large number of cmds to run on
// a server, because there are still real limits on the number of
// processes we can run at once before things start falling over, we
// only allow double the actual core count of zero core things to run
canDo = f.Cores * internal.ZeroCoreMultiplier
} else {
canDo = int(math.Floor(float64(f.Cores) / cores))
}
if canDo > 1 {
var n int
if ramMB > 0 {
n = f.RAM / ramMB
if n < canDo {
canDo = n
}
}
if diskGB > 0 {
n = f.Disk / diskGB
if n < canDo {
canDo = n
}
}
}
return canDo
}
// Server provides details of the server that Spawn() created for you, and some
// methods that let you keep track of how you use that server.
type Server struct {
Script []byte // the content of a start-up script run on the server
DestroyScript []byte // the content of a script to run on the server before it is destoyted
sshClients []*ssh.Client
sshClientSessions []int
AdminPass string
PrivateKey string // PEM format string of a private key that can be used to SSH to the server
ID string
IP string // ip address that you could SSH to
Name string // ought to correspond to the hostname
OS string // the name of the Operating System image
ConfigFiles string // files that you will CopyOver() and require to be on this Server, in CopyOver() format
UserName string // the username needed to log in to the server
permanentProblem string
homeDir string
Flavor *Flavor
Disk int // GB of available disk space
TTD time.Duration // amount of idle time allowed before destruction
goneBad time.Time
cancelDestruction chan bool
cancelID int
cancelRunCmd map[int]chan bool
provider *Provider
sshClientConfig *ssh.ClientConfig
usedCores float64
cancels int
usedZeroCores int // we keep track of how many zero core things are allocated
usedDisk int
usedRAM int
mutex sync.RWMutex
hmutex sync.Mutex
csmutex sync.Mutex
IsHeadNode bool
SharedDisk bool // the server will mount /shared
created bool // to distinguish instances we discovered or spawned
toBeDestroyed bool
destroyed bool
onDeathrow bool
sshStarted bool
createdShare bool
used bool
}
// NewServer returns a Server with the minimal details set needed to SSH to it
// and use the various SSH-requiring methods. You will need to manually set
// other properties for other functionality to work.
func NewServer(username, ip, key string) *Server {
return &Server{
UserName: username,
IP: ip,
PrivateKey: key,
cancelRunCmd: make(map[int]chan bool),
}
}
// WaitUntilReady waits for the server to become fully ready: the boot process
// will have completed and ssh will work. This is not part of provider.Spawn()
// because you may not want or be able to ssh to your server, and so that you
// can Spawn() another server while waiting for this one to become ready. If you
// get an err, you will want to call server.Destroy() as this is not done for
// you.
//
// You supply a context so that you can cancel waiting if you no longer need
// this server. Be sure to Destroy() it after cancelling.
//
// files is a string in the format taken by the CopyOver() method; if supplied
// non-blank it will CopyOver the specified files (after the server is ready,
// before any postCreationScript is run).
//
// postCreationScript is the []byte content of a script that will be run on the
// server (as the user supplied to Spawn()) once it is ready, and it will
// complete before this function returns; empty slice means do nothing.
func (s *Server) WaitUntilReady(ctx context.Context, files string, postCreationScript []byte) error {
ctx = s.getContextWithServerID(ctx)
// wait for ssh to come up
_, _, err := s.SSHClient(ctx)
if err != nil {
return err
}
// wait for sentinelFilePath to exist, indicating that the server is
// really ready to use
limit := time.After(sentinelTimeOut)
ticker := time.NewTicker(1 * time.Second)
SENTINEL:
for {
select {
case <-ticker.C:
o, e, fileErr := s.RunCmd(ctx, "file "+sentinelFilePath, false)
if fileErr == nil && !strings.Contains(o, "No such file") && !strings.Contains(e, "No such file") {
ticker.Stop()
// *** o contains "empty"; test for that instead? Does file
// behave the same way on all linux variants?
_, _, rmErr := s.RunCmd(ctx, "sudo rm "+sentinelFilePath, false)
if rmErr != nil {
clog.Warn(ctx, "failed to remove sentinel file", "path", sentinelFilePath, "err", rmErr)
}
break SENTINEL
}
continue SENTINEL
case <-limit:
ticker.Stop()
return errors.New("cloud server never became ready to use")
case <-ctx.Done():
ticker.Stop()
return errors.New("cloud server waiting for ready was cancelled")
}
}
// copy over any desired files
if files != "" {
err = s.CopyOver(ctx, files)
if err != nil {
return fmt.Errorf("cloud server files failed to upload: %s", err)
}
s.ConfigFiles = files
}
// run the postCreationScript
if len(postCreationScript) > 0 {
err = s.runScript(ctx, postCreationScript)
if err != nil {
return err
}
s.Script = postCreationScript
// because the postCreationScript may have altered PATH and other things
// that subsequent RunCmd may rely on, clear the clients
for _, client := range s.sshClients {
err = client.Close()
if err != nil {
clog.Warn(ctx, "failed to close client ssh connection", "err", err)
}
}
s.sshClients = []*ssh.Client{}
s.sshClientSessions = []int{}
}
return nil
}
// runScript runs the given script (eg. the byte content of a bash script) on
// the server after transferring it to /tmp on the server with the given
// basename.
func (s *Server) runScript(ctx context.Context, script []byte) error {
if len(script) == 0 {
return nil
}
path := filepath.Join("/tmp", ".server_script")
err := s.CreateFile(ctx, string(script), path)
if err != nil {
return fmt.Errorf("cloud server script failed to upload: %w", err)
}
_, _, err = s.RunCmd(ctx, "chmod u+x "+path, false)
if err != nil {
return fmt.Errorf("cloud server script could not be made executable: %w", err)
}
// protect running the script with a timeout
limit := time.After(pcsTimeOut)
exiterr := make(chan error, 1)
var stderr string
go func() {
var runerr error
_, stderr, runerr = s.RunCmd(ctx, path, false)
exiterr <- runerr
}()
select {
case err = <-exiterr:
if err != nil {
err = fmt.Errorf("cloud server script failed: %w", err)
if len(stderr) > 0 {
err = fmt.Errorf("%w\nSTDERR:\n%s", err, stderr)
}
return err
}
case <-limit:
return fmt.Errorf("cloud server script failed to complete within %s", pcsTimeOut)
}
_, _, rmErr := s.RunCmd(ctx, "rm "+path, false)
if rmErr != nil {
clog.Warn(ctx, "failed to remove script", "path", path, "err", rmErr)
}
return nil
}
// SetDestroyScript will result in future Destroy() calls first running the
// given script over ssh, if possible.
func (s *Server) SetDestroyScript(preDestroyScript []byte) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.DestroyScript = preDestroyScript
}
// Matches tells you if in principle a Server has the given os, script, config
// files, flavor and has a shared disk mounted. Useful before calling
// HasSpaceFor, since if you don't match these things you can't use the Server
// regardless of how empty it is. configFiles is in the CopyOver() format.
func (s *Server) Matches(os string, script []byte, configFiles string, flavor *Flavor, sharedDisk bool) bool {
return s.OS == os && bytes.Equal(s.Script, script) && s.ConfigFiles == configFiles && (flavor == nil || flavor.ID == s.Flavor.ID) && s.SharedDisk == sharedDisk
}
// Allocate considers the current usage (according to prior calls)
// and records the given resources have now been used up on this server, if
// there was enough space. Returns true if there was enough space and the
// allocation occurred.
func (s *Server) Allocate(ctx context.Context, cores float64, ramMB, diskGB int) bool {
ctx = s.getContextWithServerID(ctx)
s.mutex.Lock()
defer s.mutex.Unlock()
if s.checkSpace(cores, ramMB, diskGB) == 0 {
return false
}
s.used = true
if cores == 0 {
s.usedZeroCores++
} else {
s.usedCores = mth.FloatAdd(s.usedCores, cores)
}
s.usedRAM += ramMB
s.usedDisk += diskGB
clog.Debug(ctx, "server allocate", "cores", cores, "RAM", ramMB, "disk", diskGB, "usedCores",
s.usedCores, "usedZeroCores", s.usedZeroCores, "usedRAM", s.usedRAM, "usedDisk", s.usedDisk)
// if the host has initiated its countdown to destruction, cancel that
if s.onDeathrow {
s.cancels++
go func() {
s.cancelDestruction <- true
}()
}
return true
}
// getContextWithServerID returns the context with the server id set. For localhost
// it'll set the server id to localhost.
func (s *Server) getContextWithServerID(ctx context.Context) context.Context {
if s.Name == localhostName {
return clog.ContextWithServerID(ctx, localhostName)
} else {
return clog.ContextWithServerID(ctx, s.ID)
}
}
// Used tells you if this server has ever had Allocate() called on it.
func (s *Server) Used() bool {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.used
}
// Release records that the given resources have now been freed.
func (s *Server) Release(ctx context.Context, cores float64, ramMB, diskGB int) {
ctx = s.getContextWithServerID(ctx)
s.mutex.Lock()
defer s.mutex.Unlock()
if cores == 0 {
s.usedZeroCores--
} else {
s.usedCores = mth.FloatSubtract(s.usedCores, cores)
}
s.usedRAM -= ramMB
s.usedDisk -= diskGB
clog.Debug(ctx, "server release", "cores", cores, "RAM", ramMB, "disk", diskGB, "usedCores", s.usedCores,
"usedZeroCores", s.usedZeroCores, "usedRAM", s.usedRAM, "usedDisk", s.usedDisk)
// if the server is now doing nothing, we'll initiate a countdown to
// destroying the host
if s.usedCores <= 0 && s.usedZeroCores <= 0 && s.usedRAM <= 0 && s.TTD.Seconds() > 0 {
clog.Debug(ctx, "server idle")
go func() {
defer internal.LogPanic(ctx, "server release", false)
s.mutex.Lock()
if s.onDeathrow {
s.mutex.Unlock()
clog.Debug(ctx, "server already on deathrow")
return
} else if s.usedCores > 0 || s.usedRAM > 0 {
s.mutex.Unlock()
clog.Debug(ctx, "allocated before entering deathrow")
return
}
s.cancelDestruction = make(chan bool)
s.onDeathrow = true
s.mutex.Unlock()
timeToDie := time.After(s.TTD)
clog.Debug(ctx, "server entering deathrow", "death", time.Now().Add(s.TTD))
for {
select {
case <-s.cancelDestruction:
// *** this block needed to fail the "Run lots of jobs on a
// deathrow server" scheduler test prior to fix, but we have
// no reasonable way for a scheduler test to turn this on...
// s.mutex.RLock()
// if s.cancels <= 5 {
// s.mutex.RUnlock()
// <-time.After(2 * time.Second)
// } else {
// s.mutex.RUnlock()
// }
s.mutex.Lock()
for i := 1; i < s.cancels; i++ {
<-s.cancelDestruction
}
s.cancels = 0
s.onDeathrow = false
s.mutex.Unlock()
clog.Debug(ctx, "server cancelled deathrow")
return
case <-timeToDie:
// destroy the server
s.mutex.Lock()
s.onDeathrow = false
s.toBeDestroyed = true
s.mutex.Unlock()
err := s.Destroy(ctx)
clog.Debug(ctx, "server died on deathrow", "err", err)
return
}
}
}()
}
}
// HasSpaceFor considers the current usage (according to prior Allocation calls)
// and tells you how many of a cmd needing the given resources can run on this
// server.
func (s *Server) HasSpaceFor(cores float64, ramMB, diskGB int) int {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.checkSpace(cores, ramMB, diskGB)
}
// checkSpace does the work of HasSpaceFor. You must hold a read lock on mutex!
func (s *Server) checkSpace(cores float64, ramMB, diskGB int) int {
if s.destroyed {
return 0
}
if mth.FloatLessThan(float64(s.Flavor.Cores)-s.usedCores, cores) || (s.Flavor.RAM-s.usedRAM < ramMB) || (s.Disk-s.usedDisk < diskGB) {
return 0
}
var canDo int
if cores == 0 {
// rather than allow an infinite or very large number of cmds to run on
// this server, because there are still real limits on the number of
// processes we can run at once before things start falling over, we
// only allow double the actual core count of zero core things to run
// (on top of up to actual core count of non-zero core things).
// On a server with "zero" cores, we also allow a reasonable number of
// zero core jobs to run
if s.Flavor.Cores == 0 {
canDo = internal.ZeroCoreMultiplier*internal.ZeroCoreMultiplier - s.usedZeroCores
} else {
canDo = s.Flavor.Cores*internal.ZeroCoreMultiplier - s.usedZeroCores
}
} else {
canDo = int(math.Floor(mth.FloatSubtract(float64(s.Flavor.Cores), s.usedCores) / cores))
}
if canDo > 1 {
var n int
if ramMB > 0 {
n = (s.Flavor.RAM - s.usedRAM) / ramMB
if n < canDo {
canDo = n
}
}
if diskGB > 0 {
n = (s.Disk - s.usedDisk) / diskGB
if n < canDo {
canDo = n
}
}
}
return canDo
}
// createSSHClientConfig creates an ssh client config and stores it on self.
func (s *Server) createSSHClientConfig(ctx context.Context) error {
if s.PrivateKey == "" {
if s.provider != nil && s.provider.PrivateKey() == "" {
clog.Error(ctx, "resource file did not contain the ssh key", "path", s.provider.savePath)
}
return errors.New("missing ssh key")
}
// parse private key and make config
signer, err := ssh.ParsePrivateKey([]byte(s.PrivateKey))
if err != nil {
path := "unknown"
if s.provider != nil {
path = s.provider.savePath
}
clog.Error(ctx, "failed to parse private key", "path", path, "err", err)
return err
}
s.sshClientConfig = &ssh.ClientConfig{
User: s.UserName,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // *** don't currently know the server's host key, want to use ssh.FixedHostKey(publicKey) instead...
Timeout: sshShortTimeOut,
}
return nil
}
// SSHClient returns an ssh.Client object that could be used to ssh to the
// server. Requires that port 22 is accessible for SSH. The client returned will
// be one that hasn't failed to create a session yet; a new client will be
// created if necessary. You get back the client's index, so that if this client
// fails to create a session you can mark this client as bad.
func (s *Server) SSHClient(ctx context.Context) (*ssh.Client, int, error) {
ctx = s.getContextWithServerID(ctx)
s.mutex.Lock()
defer s.mutex.Unlock()
// return a client that is still good (most likely to be a more recent
// client)
numClients := len(s.sshClients)
var client *ssh.Client
var index int
for i := numClients - 1; i >= 0; i-- {
if s.sshClientSessions[i] < maxSSHSessions {
client = s.sshClients[i]
s.sshClientSessions[i]++
index = i
break
}
}
if client != nil {
return client, index, nil
}
// create a new client, add it to the pool
if s.sshClientConfig == nil {
err := s.createSSHClientConfig(ctx)
if err != nil {
return nil, index, err
}
}
// dial in to the server, allowing certain errors that indicate that the
// network or server isn't really ready for ssh yet; wait for up to
// 5mins for success, if we had only just created this server
hostAndPort := s.IP + ":22"
client, err := sshDial(ctx, hostAndPort, s.sshClientConfig)
if err != nil {
// if we're trying to destroy this server, just give up straight away
if s.destroyed {
return nil, index, err
}
// otherwise, keep trying
limit := time.After(sshTimeOut)
ticker := time.NewTicker(1 * time.Second)
ticks := 0
DIAL:
for {
select {
case <-ticker.C:
client, err = sshDial(ctx, hostAndPort, s.sshClientConfig)
// if it's a known "ssh still starting up" error, wait until the
// timeout, unless ssh had worked previously, in which case
// bail immediately if it's "no route to host"
if err != nil && (strings.HasSuffix(err.Error(), "connection timed out") || strings.HasSuffix(err.Error(), "no route to host") || strings.HasSuffix(err.Error(), "connection refused") || (s.created && strings.HasSuffix(err.Error(), "connection could not be established"))) {
if s.sshStarted && strings.HasSuffix(err.Error(), "no route to host") {
err = errors.New("ssh used to work, but now there's no route to host")
break DIAL
}
continue DIAL
}
// if it worked, we stop trying; if it failed again with a
// different error, we keep trying for at least 45 seconds
// to allow for the vagueries of OS start ups (eg. CentOS
// brings up sshd and starts rejecting connections before
// the centos user gets added)
ticks++
if err != nil && err.Error() == "connection attempt cancelled" {
ticker.Stop()
break DIAL
}
if err == nil || ticks == 9 || !s.created {
ticker.Stop()
break DIAL
} else {
continue DIAL
}
case <-limit:
ticker.Stop()
err = errors.New("giving up waiting for ssh to work")
break DIAL
case <-ctx.Done():
ticker.Stop()
err = errors.New("cancelled waiting for ssh to work")
break DIAL
}
}
if err != nil {
return nil, index, err
}
}
s.sshClients = append(s.sshClients, client)
s.sshClientSessions = append(s.sshClientSessions, 1)
s.sshStarted = true
return client, len(s.sshClients) - 1, nil
}
// sshDial calls ssh.Dial() and enforces the config's timeout, which ssh.Dial()
// doesn't always seem to obey.
func sshDial(ctx context.Context, addr string, sshConfig *ssh.ClientConfig) (*ssh.Client, error) {
clientCh := make(chan *ssh.Client, 1)
errCh := make(chan error, 1)
go func() {
defer internal.LogPanic(ctx, "sshDial", false)
sshClient, err := ssh.Dial("tcp", addr, sshConfig)
clientCh <- sshClient
errCh <- err
}()
deadline := time.After(sshConfig.Timeout + 1*time.Second)
select {
case err := <-errCh:
return <-clientCh, err
case <-deadline:
return nil, fmt.Errorf("connection could not be established")
case <-ctx.Done():
return nil, fmt.Errorf("connection attempt cancelled")
}
}
// SSHSession returns an ssh.Session object that could be used to do things via
// ssh on the server. Will time out and return an error if the session can't be
// created within 5s. Also returns the index of the client this session came
// from, so that when you can call CloseSSHSession() when you're done with the
// returned session.
func (s *Server) SSHSession(ctx context.Context) (*ssh.Session, int, error) {
ctx = s.getContextWithServerID(ctx)
sshClient, clientIndex, err := s.SSHClient(ctx)
if err != nil {
clog.Debug(ctx, "server ssh could not be established", "err", err)
return nil, clientIndex, fmt.Errorf("cloud SSHSession() failed to get a client: %s", err.Error())
}
// *** even though sshclient has a timeout, it still hangs forever if we
// try to get a NewSession to a dead server, so we implement our own 5s
// timeout here
done := make(chan error, 1)
worked := make(chan bool, 1)
sessionCh := make(chan *ssh.Session, 1)
go func() {
select {
case <-time.After(sshShortTimeOut):
clog.Debug(ctx, "server ssh timed out", "clientindex", clientIndex)
done <- fmt.Errorf("cloud SSHSession() timed out")
case <-ctx.Done():
clog.Debug(ctx, "server ssh cancelled", "clientindex", clientIndex)
done <- fmt.Errorf("cloud SSHSession() cancelled")
case <-worked:
return
}
}()
go func() {
defer internal.LogPanic(ctx, "server sshsession", false)
session, errf := sshClient.NewSession()
if errf != nil {
clog.Debug(ctx, "server ssh failed", "err", errf, "clientindex", clientIndex)
done <- fmt.Errorf("cloud SSHSession() failed to esatablish a session: %s", errf.Error())
return
}
worked <- true
done <- nil
sessionCh <- session
}()
err = <-done
if err != nil {
s.mutex.Lock()
// pretend we're now at max sessions, so this client won't be used again
// in the future, at least until sessions get closed, when it might
// start working again
s.sshClientSessions[clientIndex] = maxSSHSessions
s.mutex.Unlock()
return nil, clientIndex, err
}
return <-sessionCh, clientIndex, nil
}
// CloseSSHSession is used to close a session opened with SSHSession(). If the
// client used to create the session (as indicated by the supplied index, also
// retrieved from SSHSession()) was marked as bad, it will now be marked as
// good, on the assumption there is now "space" for a new session.
func (s *Server) CloseSSHSession(ctx context.Context, session *ssh.Session, clientIndex int) {
ctx = s.getContextWithServerID(ctx)
err := session.Close()
s.closeWarning(ctx, err)
s.mutex.Lock()
defer s.mutex.Unlock()
s.sshClientSessions[clientIndex]--
}
// closeWarning warns about the given error if not nil, unless it is expected
// in a close situation.
func (s *Server) closeWarning(ctx context.Context, err error) {
if err != nil && err.Error() != "EOF" && !strings.Contains(err.Error(), "use of closed network connection") {
clog.Warn(ctx, "failed to close ssh session", "err", err)
}
}
// SFTPClient is like sftp.NewClient(), but the underlying
// clientConn.conn.WriteCloser is mutex protected to avoid data races between
// closes due to errors and direct Close() calls on the *sftp.Client.
func SFTPClient(conn *ssh.Client) (*sftp.Client, error) {
s, err := conn.NewSession()
if err != nil {
return nil, err
}
if err = s.RequestSubsystem("sftp"); err != nil {
return nil, err
}
pw, err := s.StdinPipe()
if err != nil {
return nil, err
}
pw = &threadSafeWriteCloser{WriteCloser: pw}
pr, err := s.StdoutPipe()
if err != nil {
return nil, err
}
return sftp.NewClientPipe(pr, pw)
}
type threadSafeWriteCloser struct {
io.WriteCloser
sync.Mutex
}
func (c *threadSafeWriteCloser) Close() error {
c.Lock()
defer c.Unlock()
return c.WriteCloser.Close()
}
// RunCmd runs the given command on the server, optionally in the background.
// You get the command's STDOUT and STDERR as strings.
func (s *Server) RunCmd(ctx context.Context, cmd string, background bool) (stdout, stderr string, err error) {
ctx = s.getContextWithServerID(ctx)
// create a session
session, clientIndex, err := s.SSHSession(ctx)
if err != nil {
return stdout, stderr, err
}
defer s.CloseSSHSession(ctx, session, clientIndex)
// if the sever is destroyed while running, arrange to immediately return an
// error
s.mutex.Lock()
cancelID := s.cancelID
s.cancelID = cancelID + 1
cancelCh := make(chan bool, 1)
s.cancelRunCmd[cancelID] = cancelCh
done := make(chan error, 1)
outCh := make(chan string, 1)
errCh := make(chan string, 1)
finished := make(chan bool, 1)
go func() {
defer internal.LogPanic(ctx, "server runcmd cancellation", false)
select {
case <-cancelCh:
outCh <- ""
errCh <- ""
done <- fmt.Errorf("cloud RunCmd() cancelled due to destruction of server %s", s.ID)
case <-ctx.Done():
outCh <- ""
errCh <- ""
done <- fmt.Errorf("cloud RunCmd() on server %s cancelled on request", s.ID)
case <-finished:
// end select
}
s.mutex.Lock()
close(cancelCh)
delete(s.cancelRunCmd, cancelID)
s.mutex.Unlock()
}()
go func() {
defer internal.LogPanic(ctx, "server runcmd", false)
// run the command, returning stdout
if background {
cmd = "sh -c 'nohup " + cmd + " > /dev/null 2>&1 &'"
}
var o bytes.Buffer
var e bytes.Buffer
session.Stdout = &o
session.Stderr = &e
errf := session.Run(cmd)
finished <- true
if o.Len() > 0 {
outCh <- o.String()
} else {
outCh <- ""
}
if e.Len() > 0 {
errCh <- e.String()
} else {
errCh <- ""
}
if errf != nil {
done <- fmt.Errorf("cloud RunCmd(%s) failed: %s", cmd, errf.Error())
} else {
done <- nil
}
}()
s.mutex.Unlock()
err = <-done
stdout = <-outCh
stderr = <-errCh
return stdout, stderr, err
}
// UploadFile uploads a local file to the given location on the server.
func (s *Server) UploadFile(ctx context.Context, source string, dest string) error {
ctx = s.getContextWithServerID(ctx)
sshClient, _, err := s.SSHClient(ctx)
if err != nil {
return err
}
client, err := SFTPClient(sshClient)
if err != nil {
return err
}
defer internal.LogClose(ctx, client, "upload file client session", "source", source, "dest", dest)
// create all parent dirs of dest
err = s.MkDir(ctx, filepath.Dir(dest))
if err != nil {
return err
}
// open source, create dest
sourceFile, err := os.Open(source)
if err != nil {
return err
}
defer internal.LogClose(ctx, sourceFile, "upload file source", "source", source, "dest", dest)
destFile, err := client.Create(dest)
if err != nil {
return err
}
// copy the file content over
_, err = io.Copy(destFile, sourceFile)
return err
}
// CopyOver uploads the given local files to the corresponding locations on the
// server. files argument is a comma separated list of local file paths.
// Absolute paths are uploaded to the same absolute path on the server. Paths
// beginning with ~/ are uploaded from the local home directory to the server's
// home directory.
//
// If local path and desired remote path are unrelated, the paths can be
// separated with a colon.
//
// If a specified local path does not exist, it is silently ignored, allowing
// the specification of multiple possible config files when you might only have
// one. The mtimes of the files are retained.
//
// NB: currently only works if the server supports the command 'pwd'.
func (s *Server) CopyOver(ctx context.Context, files string) error {
ctx = s.getContextWithServerID(ctx)
for _, path := range strings.Split(files, ",") {
split := strings.Split(path, ":")
var localPath, remotePath string
if len(split) == 2 {
localPath = split[0]
remotePath = split[1]
} else {
localPath = path
remotePath = path
}
// ignore if it doesn't exist locally
localPath = internal.TildaToHome(localPath)
info, err := os.Stat(localPath)
if err != nil {
err = nil
continue
}
if strings.HasPrefix(remotePath, "~/") {
homeDir, errh := s.HomeDir(ctx)
if errh != nil {
return errh
}
remotePath = strings.TrimLeft(remotePath, "~/")
remotePath = filepath.Join(homeDir, remotePath)
}
err = s.UploadFile(ctx, localPath, remotePath)
if err != nil {
return err
}
// if these are config files we likely need to make them user-only read,
// and if they're not, I can't see how it matters if group/all can't
// read? This is a single user server and I'm the only one using it...
_, _, err = s.RunCmd(ctx, "chmod 600 "+remotePath, false)
if err != nil {
return err
}
// sometimes the mtime of the file matters, so we try and set that on
// the remote copy
_, _, err = s.RunCmd(ctx, fmt.Sprintf("touch -d %s %s", info.ModTime().Format(touchStampFormat), remotePath), false)
if err != nil {
return err
}
}
return nil
}
// HomeDir gets the absolute path to the server's home directory. Depends on
// 'pwd' command existing on the server.
func (s *Server) HomeDir(ctx context.Context) (string, error) {
ctx = s.getContextWithServerID(ctx)
s.hmutex.Lock()
defer s.hmutex.Unlock()
if s.homeDir != "" {
return s.homeDir, nil
}
stdout, _, err := s.RunCmd(ctx, "pwd", false)
if err != nil {
return "", err
}
s.homeDir = strings.TrimSuffix(stdout, "\n")
return s.homeDir, nil
}
// CreateFile creates a new file with the given content on the server.
func (s *Server) CreateFile(ctx context.Context, content string, dest string) error {
ctx = s.getContextWithServerID(ctx)
sshClient, _, err := s.SSHClient(ctx)
if err != nil {
return err
}
client, err := SFTPClient(sshClient)
if err != nil {
return err
}
defer internal.LogClose(ctx, client, "create file client session")