-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathvssh.go
458 lines (386 loc) · 9.85 KB
/
vssh.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
//: Copyright Verizon Media
//: Licensed under the terms of the Apache 2.0 License. See LICENSE file in the project root for terms.
// Package vssh is a Go library to handle tens of thousands SSH connections and execute
// the command with higher-level API for building network device / server automation.
//
// run(ctx, command, timeout)
// runWithLabel(ctx, command, timeout, "OS == Ubuntu && POP == LAX")
//
// By calling the run method vssh sends the given command to all available clients or
// based on your query it runs the command on the specific clients and the results of
// the ran command can be received in two options, streaming or final result.In streaming
// you can get line by line from command’s stdout / stderr in real time or in case of
// non-real time you can get the whole of the lines together.
package vssh
import (
"bytes"
"context"
"errors"
"fmt"
"log"
"net"
"os"
"sync"
"sync/atomic"
"time"
"golang.org/x/crypto/ssh"
)
var (
defaultMaxSessions uint8 = 3
maxErrRecent uint64 = 10
maxEstablishedRetry = 20
actionQueueSize = 1000
initNumProc = 1000
resetErrRecentDur = time.Duration(300) * time.Second
reConnDur = time.Duration(10) * time.Second
errSSHConfig = errors.New("ssh config can not be nil")
errNotExist = errors.New("not exist")
)
// VSSH represents VSSH instance.
type VSSH struct {
clients clients
logger *log.Logger
stats stats
mode bool
bufPool sync.Pool
actionQ chan task
procSig chan struct{}
procCtl chan struct{}
}
type stats struct {
queries uint64
connects uint64
processes uint64
}
type task interface {
run(v *VSSH)
}
// ClientOption represents client optional parameters.
type ClientOption func(c *clientAttr)
// RunOption represents run optional parameters.
type RunOption func(q *query)
// New constructs a new VSSH instance.
func New() *VSSH {
return &VSSH{
clients: newClients(),
actionQ: make(chan task, actionQueueSize),
logger: log.New(os.Stdout, "vssh: ", log.Lshortfile),
procSig: make(chan struct{}, 1),
procCtl: make(chan struct{}, 1),
bufPool: sync.Pool{
New: func() interface{} { return new(bytes.Buffer) },
},
mode: false,
}
}
// OnDemand changes VSSH connection behavior. By default VSSH
// connects to all of the clients before any run request and
// it maintains the authenticated SSH connection to all clients.
// We can call this "persistent SSH connection" but with
// OnDemand it tries to connect to clients once the run requested
// and it closes the appropriate connection once the response data returned.
func (v *VSSH) OnDemand() *VSSH {
v.mode = true
return v
}
// AddClient adds a new SSH client to VSSH.
func (v *VSSH) AddClient(addr string, config *ssh.ClientConfig, opts ...ClientOption) error {
client := &clientAttr{
addr: addr,
config: config,
maxSessions: defaultMaxSessions,
logger: v.logger,
pty: pty{
enabled: true,
term: "xterm",
modes: ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
},
wide: 80,
height: 40,
},
}
for _, opt := range opts {
opt(client)
}
if err := clientValidation(client); err != nil {
return err
}
v.clients.add(client)
if !v.mode {
v.actionQ <- &connect{client}
}
return nil
}
// SetMaxSessions sets maximum sessions for given client.
func SetMaxSessions(n int) ClientOption {
return func(c *clientAttr) {
c.maxSessions = uint8(n)
}
}
// RequestPty sets the pty parameters.
func RequestPty(term string, h, w uint, modes ssh.TerminalModes) ClientOption {
return func(c *clientAttr) {
c.pty = pty{
enabled: true,
term: term,
modes: modes,
wide: w,
height: h,
}
}
}
// DisableRequestPty disables the pty.
func DisableRequestPty() ClientOption {
return func(c *clientAttr) {
c.pty.enabled = false
}
}
// SetLabels sets labels for a client.
func SetLabels(labels map[string]string) ClientOption {
return func(c *clientAttr) {
c.labels = labels
}
}
func clientValidation(c *clientAttr) error {
if c.config == nil {
return errSSHConfig
}
_, _, err := net.SplitHostPort(c.addr)
if err != nil {
return err
}
return nil
}
// Start starts vSSH, including action queue and re-connect procedures.
// You can construct and start the vssh like below:
// vs := vssh.New().Start()
func (v *VSSH) Start() *VSSH {
ctx := context.Background()
go v.process(ctx)
go v.reConnect(ctx)
for i := 0; i < initNumProc; i++ {
v.procCtl <- struct{}{}
}
return v
}
// StartWithContext is same as Run but it accepts external context.
func (v *VSSH) StartWithContext(ctx context.Context) *VSSH {
go v.process(ctx)
go v.reConnect(ctx)
for i := 0; i < initNumProc; i++ {
v.procCtl <- struct{}{}
}
return v
}
func (v *VSSH) process(ctx context.Context) {
for {
go func() {
for {
select {
case a := <-v.actionQ:
switch b := a.(type) {
case *connect:
atomic.AddUint64(&v.stats.connects, 1)
b.run(v)
case *query:
atomic.AddUint64(&v.stats.queries, 1)
b.run(v)
}
case <-v.procSig:
atomic.AddUint64(&v.stats.processes, ^uint64(0))
return
case <-ctx.Done():
return
}
}
}()
<-v.procCtl
v.stats.processes++
}
}
// IncreaseProc adds more processes / workers.
func (v *VSSH) IncreaseProc(n ...int) {
num := 1
if len(n) > 0 {
num = n[0]
}
for i := 0; i < num; i++ {
v.procCtl <- struct{}{}
}
}
// DecreaseProc destroys the idle processes / workers.
func (v *VSSH) DecreaseProc(n ...int) {
num := 1
if len(n) > 0 {
num = n[0]
}
for i := 0; i < num; i++ {
v.procSig <- struct{}{}
}
}
// CurrentProc returns number of running processes / workers.
func (v *VSSH) CurrentProc() uint64 {
return v.stats.processes
}
// SetInitNumProc sets the initial number of processes / workers.
//
// You need to set this number right after creating vssh.
// vs := vssh.New()
// vs.SetInitNumProc(200)
// vs.Start()
// There are two other methods in case you need to change
// the settings in the middle of your code.
// IncreaseProc(n int)
// DecreaseProc(n int)
func (v *VSSH) SetInitNumProc(n int) {
initNumProc = n
}
// Run sends a new run query with given context, command and timeout.
//
// timeout allows you to set a limit on the length of time the command
// will run for. You can cancel the running command by context.WithCancel.
func (v *VSSH) Run(ctx context.Context, cmd string, timeout time.Duration, opts ...RunOption) chan *Response {
respChan := make(chan *Response, 100)
q := &query{
ctx: ctx,
cmd: cmd,
respChan: respChan,
respTimeout: timeout,
}
for _, opt := range opts {
opt(q)
}
v.actionQ <- q
return respChan
}
// RunWithLabel runs the command on the specific clients which
// they matched with given query statement.
// labels := map[string]string {
// "POP" : "LAX",
// "OS" : "JUNOS",
// }
// // sets labels to a client
// vs.AddClient(addr, config, vssh.SetLabels(labels))
// // run the command with label
// vs.RunWithLabel(ctx, cmd, timeout, "POP == LAX || POP == DCA) && OS == JUNOS")
func (v *VSSH) RunWithLabel(ctx context.Context, cmd, queryStmt string, timeout time.Duration, opts ...RunOption) (chan *Response, error) {
vis, err := parseExpr(queryStmt)
if err != nil {
return nil, err
}
respChan := make(chan *Response, 100)
q := &query{
ctx: ctx,
cmd: cmd,
stmt: queryStmt,
compiledQuery: vis,
respChan: respChan,
respTimeout: timeout,
}
for _, opt := range opts {
opt(q)
}
v.actionQ <- q
return respChan, nil
}
// SetLimitReaderStdout sets limit for stdout reader.
// respChan := vs.Run(ctx, cmd, timeout, vssh.SetLimitReaderStdout(1024))
func SetLimitReaderStdout(n int64) RunOption {
return func(q *query) {
q.limitReadOut = n
}
}
// SetLimitReaderStderr sets limit for stderr reader.
func SetLimitReaderStderr(n int64) RunOption {
return func(q *query) {
q.limitReadErr = n
}
}
func (v *VSSH) reConnect(ctx context.Context) {
if v.mode {
return
}
ticker := time.NewTicker(reConnDur)
defer ticker.Stop()
for {
select {
case <-ticker.C:
for client := range v.clients.enum() {
client.Lock()
if client.err != nil && client.stats.errRecent < maxErrRecent {
if client.client != nil {
client.client.Close()
}
v.actionQ <- &connect{client}
} else if time.Since(client.lastUpdate) > resetErrRecentDur {
client.stats.errRecent = 0
}
client.Unlock()
}
case <-ctx.Done():
return
}
}
}
// ForceReConn reconnects the client immediately.
func (v *VSSH) ForceReConn(addr string) error {
client, ok := v.clients.get(addr)
if !ok {
return errNotExist
}
if client.client != nil {
client.client.Close()
}
v.actionQ <- &connect{client}
return nil
}
// Wait stands by until percentage of the clients have been processed.
// An optional percentage can be passed as an argument - otherwise the default
// value of 100% is used.
func (v *VSSH) Wait(p ...int) (float64, error) {
var (
start = time.Now()
retry = 0
pct = 100
)
if v.mode {
return 0, nil
}
if len(p) > 0 {
pct = p[0]
}
for {
total := 0
established := 0
retry++
for client := range v.clients.enum() {
total++
if client.getClient() != nil {
established++
}
}
time.Sleep(time.Millisecond * 500)
if total == 0 || (established*100/total) >= pct {
break
}
if retry > maxEstablishedRetry {
return time.Since(start).Seconds(), fmt.Errorf("wait established timeout")
}
}
return time.Since(start).Seconds(), nil
}
// SetLogger sets external logger.
func (v *VSSH) SetLogger(l *log.Logger) {
v.logger = l
}
// SetClientsShardNumber sets the clients shard number.
//
// vSSH uses map data structure to keep the clients
// data in the memory. Sharding helps to have better performance
// on write/read with mutex. This setting can be tuned if needed.
func SetClientsShardNumber(n int) {
clientsShardNum = n
}