-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh_master.go
119 lines (97 loc) · 2.45 KB
/
ssh_master.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
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
log "github.com/sirupsen/logrus"
)
// Responsible for managing an SSH Control-Master that we require so we don't have to type the password of the host in everytime
// AssembleDefaultSocketPath returns default socket-path for a given host
func AssembleDefaultSocketPath(host string) string {
return fmt.Sprintf("/tmp/sshctls/%s/%s", os.Getenv("USER"), host)
}
// ControlMaster manages a SSHControlMaster process
type ControlMaster struct {
host string
SocketPath string
Cmd *exec.Cmd
}
// NewControlMaster returns a constructed ControlMaster instance
func NewControlMaster(socketPath string, host string) *ControlMaster {
var err error
master := &ControlMaster{
SocketPath: socketPath,
host: host,
}
// @TODO: check for stale socket-file without running instance
if FileExists(master.SocketPath) {
return nil
}
{ // no file exists at socketPath, continue creating the master
err = os.MkdirAll(filepath.Dir(master.SocketPath), os.ModePerm)
if err != nil {
panic(err)
}
_ = master.forkSSH(master.SocketPath, master.host)
}
return master
}
func (master *ControlMaster) forkSSH(socketPath string, host string) (errorChan chan error) {
errorChan = make(chan error, 1)
master.Cmd = exec.Command(
"ssh",
"-M", // master
"-S", socketPath,
"-N", // don't execute a remote command, just block
host,
)
master.Cmd.Stdin = os.Stdin
master.Cmd.Stdout = os.Stderr
master.Cmd.Stderr = os.Stderr
log.Debugf("ControlMaster.start: %v", master.Cmd.Args)
err := master.Cmd.Start()
if err != nil {
log.Error(err)
}
// @XXX poll until socket is created >.<
// @TODO is errorChan still necessary?
for {
select {
case err := <-errorChan:
panic(err)
default:
_, err := os.Stat(socketPath)
if err == nil { // file exists
goto End
} else if os.IsNotExist(err) { // file does not exist
time.Sleep(40 * time.Millisecond)
} else { // unknown error
panic(err)
}
}
}
End:
return
}
// Cleanup cleans up stale resources of the ControlMaster
func (master *ControlMaster) Cleanup() {
var err error
if master != nil && master.Cmd != nil {
// clean up master process
if master.Cmd.Process != nil {
err := master.Cmd.Process.Kill()
if err != nil {
log.Error(err)
}
}
// clean up stale socket file
if FileExists(master.SocketPath) {
err = os.Remove(master.SocketPath)
if err != nil {
log.Error(err)
}
}
}
}