-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle.go
96 lines (82 loc) · 1.68 KB
/
single.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
package main
import (
"bytes"
"fmt"
"time"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
type CmdResponse struct {
HostPort string
StdOut string
StdErr string
Err error
}
type Connection struct {
cfg *ssh.ClientConfig
client *ssh.Client
hostPort string
network string // tcp
// session *ssh.Session
command chan string
response chan CmdResponse
}
func NewConnection(cfg *ssh.ClientConfig, network, hostPort string) *Connection {
c := Connection{
cfg: cfg,
hostPort: hostPort,
network: network,
command: make(chan string),
response: make(chan CmdResponse),
}
go c.loop()
return &c
}
func (c *Connection) dial() error {
client, err := ssh.Dial(c.network, c.hostPort, c.cfg)
if err != nil {
return errors.Wrap(err, "Failed to dial")
}
c.client = client
return nil
}
func (c *Connection) loop() {
for {
select {
case cmd := <-c.command:
for c.client == nil {
err := c.dial()
if err != nil {
fmt.Printf("%s: Failed to dial: %v\n", c.hostPort, err)
time.Sleep(time.Second)
}
}
session, err := c.client.NewSession()
if err != nil {
c.response <- CmdResponse{
HostPort: c.hostPort,
Err: errors.Wrap(err, "Failed to create session"),
}
} else {
var o, e bytes.Buffer
session.Stdout = &o
session.Stderr = &e
err = session.Run(cmd)
c.response <- CmdResponse{
HostPort: c.hostPort,
StdOut: o.String(),
StdErr: e.String(),
Err: err,
}
}
default:
time.Sleep(100 * time.Millisecond)
}
}
}
func (c *Connection) Command(cmd string) {
c.command <- cmd
}
func (c *Connection) Response() CmdResponse {
return <-c.response
}