-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
plugin.go
422 lines (362 loc) · 9.94 KB
/
plugin.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
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/appleboy/com/random"
"github.com/appleboy/easyssh-proxy"
"github.com/fatih/color"
)
var (
errMissingHost = errors.New("Error: missing server host")
errMissingPasswordOrKey = errors.New("Error: can't connect without a private SSH key or password")
errMissingSourceOrTarget = errors.New("missing source or target config")
)
type (
// Config for the plugin.
Config struct {
Host []string
Port int
Protocol easyssh.Protocol
Username string
Password string
Key string
Passphrase string
Fingerprint string
KeyPath string
Timeout time.Duration
CommandTimeout time.Duration
Target []string
Source []string
Remove bool
StripComponents int
TarExec string
TarTmpPath string
Proxy easyssh.DefaultConfig
Debug bool
Overwrite bool
UnlinkFirst bool
Ciphers []string
UseInsecureCipher bool
TarDereference bool
}
// Plugin values.
Plugin struct {
Config Config
DestFile string
}
copyError struct {
host string
message string
}
)
func (e copyError) Error() string {
return fmt.Sprintf("error copy file to dest: %s, error message: %s\n", e.host, e.message)
}
func globList(paths []string) fileList {
var list fileList
for _, pattern := range paths {
ignore := false
pattern = strings.TrimSpace(pattern)
if string(pattern[0]) == "!" {
pattern = pattern[1:]
ignore = true
}
matches, err := filepath.Glob(pattern)
if err != nil {
fmt.Printf("Glob error for %q: %s\n", pattern, err)
continue
}
if ignore {
list.Ignore = append(list.Ignore, matches...)
} else {
list.Source = append(list.Source, matches...)
}
}
return list
}
func (p Plugin) log(host string, message ...interface{}) {
if count := len(p.Config.Host); count == 1 {
fmt.Printf("%s", fmt.Sprintln(message...))
} else {
fmt.Printf("%s: %s", host, fmt.Sprintln(message...))
}
}
func (p *Plugin) removeDestFile(os string, ssh *easyssh.MakeConfig) error {
p.log(ssh.Server, "remove file", p.DestFile)
_, errStr, _, err := ssh.Run(rmcmd(os, p.DestFile), p.Config.CommandTimeout)
if err != nil {
return err
}
if errStr != "" {
return errors.New(errStr)
}
return nil
}
func (p *Plugin) removeAllDestFile() error {
for _, h := range trimValues(p.Config.Host) {
host, port := p.hostPort(h)
ssh := &easyssh.MakeConfig{
Server: host,
User: p.Config.Username,
Password: p.Config.Password,
Port: port,
Protocol: p.Config.Protocol,
Key: p.Config.Key,
KeyPath: p.Config.KeyPath,
Passphrase: p.Config.Passphrase,
Timeout: p.Config.Timeout,
Ciphers: p.Config.Ciphers,
Fingerprint: p.Config.Fingerprint,
UseInsecureCipher: p.Config.UseInsecureCipher,
Proxy: easyssh.DefaultConfig{
Server: p.Config.Proxy.Server,
User: p.Config.Proxy.User,
Password: p.Config.Proxy.Password,
Port: p.Config.Proxy.Port,
Protocol: p.Config.Proxy.Protocol,
Key: p.Config.Proxy.Key,
KeyPath: p.Config.Proxy.KeyPath,
Passphrase: p.Config.Proxy.Passphrase,
Timeout: p.Config.Proxy.Timeout,
Ciphers: p.Config.Proxy.Ciphers,
Fingerprint: p.Config.Proxy.Fingerprint,
UseInsecureCipher: p.Config.Proxy.UseInsecureCipher,
},
}
_, _, _, err := ssh.Run("ver", p.Config.CommandTimeout)
systemType := "unix"
if err == nil {
systemType = "windows"
}
// remove tar file
err = p.removeDestFile(systemType, ssh)
if err != nil {
return err
}
}
return nil
}
type fileList struct {
Ignore []string
Source []string
}
func (p *Plugin) buildTarArgs(src string) []string {
files := globList(trimValues(p.Config.Source))
args := []string{}
if len(files.Ignore) > 0 {
for _, v := range files.Ignore {
args = append(args, "--exclude")
args = append(args, v)
}
}
if p.Config.TarDereference {
args = append(args, "--dereference")
}
args = append(args, "-zcf")
args = append(args, getRealPath(src))
args = append(args, files.Source...)
return args
}
func (p *Plugin) buildUnTarArgs(target string) []string {
args := []string{}
args = append(args,
p.Config.TarExec,
"-zxf",
p.DestFile,
)
if p.Config.StripComponents > 0 {
args = append(args, "--strip-components")
args = append(args, strconv.Itoa(p.Config.StripComponents))
}
if p.Config.Overwrite {
args = append(args, "--overwrite")
}
if p.Config.UnlinkFirst {
args = append(args, "--unlink-first")
}
args = append(args,
"-C",
target,
)
return args
}
// Exec executes the plugin.
func (p *Plugin) Exec() error {
if len(p.Config.Key) == 0 && len(p.Config.Password) == 0 && len(p.Config.KeyPath) == 0 {
return errMissingPasswordOrKey
}
if len(p.Config.Source) == 0 || len(p.Config.Target) == 0 {
return errMissingSourceOrTarget
}
hosts := trimValues(p.Config.Host)
if len(hosts) == 0 {
return errMissingHost
}
p.DestFile = fmt.Sprintf("%s.tar.gz", random.String(10))
// create a temporary file for the archive
dir := os.TempDir()
src := filepath.Join(dir, p.DestFile)
// show current version
fmt.Println("drone-scp version: " + Version)
// run archive command
fmt.Println("tar all files into " + src)
args := p.buildTarArgs(src)
cmd := exec.Command(p.Config.TarExec, args...)
if p.Config.Debug {
fmt.Println("$", strings.Join(cmd.Args, " "))
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
wg := sync.WaitGroup{}
wg.Add(len(p.Config.Host))
errChannel := make(chan error)
finished := make(chan struct{})
for _, host := range hosts {
go func(h string) {
defer wg.Done()
host, port := p.hostPort(h)
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
Server: host,
User: p.Config.Username,
Password: p.Config.Password,
Port: port,
Key: p.Config.Key,
KeyPath: p.Config.KeyPath,
Passphrase: p.Config.Passphrase,
Timeout: p.Config.Timeout,
Ciphers: p.Config.Ciphers,
Fingerprint: p.Config.Fingerprint,
UseInsecureCipher: p.Config.UseInsecureCipher,
Proxy: easyssh.DefaultConfig{
Server: p.Config.Proxy.Server,
User: p.Config.Proxy.User,
Password: p.Config.Proxy.Password,
Port: p.Config.Proxy.Port,
Key: p.Config.Proxy.Key,
KeyPath: p.Config.Proxy.KeyPath,
Passphrase: p.Config.Proxy.Passphrase,
Timeout: p.Config.Proxy.Timeout,
Ciphers: p.Config.Proxy.Ciphers,
Fingerprint: p.Config.Proxy.Fingerprint,
UseInsecureCipher: p.Config.Proxy.UseInsecureCipher,
},
}
systemType := "unix"
_, _, _, err := ssh.Run("ver", p.Config.CommandTimeout)
if err == nil {
systemType = "windows"
}
// upload file to the tmp path
p.DestFile = fmt.Sprintf("%s%s", p.Config.TarTmpPath, p.DestFile)
p.log(host, "remote server os type is "+systemType)
// Call Scp method with file you want to upload to remote server.
p.log(host, "scp file to server.")
err = ssh.Scp(src, p.DestFile)
if err != nil {
errChannel <- copyError{host, err.Error()}
return
}
for _, target := range p.Config.Target {
target = strings.Replace(target, " ", "\\ ", -1)
// remove target folder before upload data
if p.Config.Remove {
p.log(host, "Remove target folder:", target)
_, _, _, err := ssh.Run(rmcmd(systemType, target), p.Config.CommandTimeout)
if err != nil {
errChannel <- err
return
}
}
p.log(host, "create folder", target)
_, errStr, _, err := ssh.Run(mkdircmd(systemType, target), p.Config.CommandTimeout)
if err != nil {
errChannel <- err
return
}
if len(errStr) != 0 {
errChannel <- fmt.Errorf("%s", errStr)
return
}
// untar file
p.log(host, "untar file", p.DestFile)
commamd := strings.Join(p.buildUnTarArgs(target), " ")
if p.Config.Debug {
fmt.Println("$", commamd)
}
outStr, errStr, _, err := ssh.Run(commamd, p.Config.CommandTimeout)
if outStr != "" {
p.log(host, "output: ", outStr)
}
if errStr != "" {
p.log(host, "error: ", errStr)
}
if err != nil {
errChannel <- err
return
}
}
// remove tar file
err = p.removeDestFile(systemType, ssh)
if err != nil {
errChannel <- err
return
}
}(host)
}
go func() {
wg.Wait()
close(finished)
}()
select {
case <-finished:
case err := <-errChannel:
if err != nil {
c := color.New(color.FgRed)
c.Println("drone-scp error: ", err)
if _, ok := err.(copyError); !ok {
fmt.Println("drone-scp rollback: remove all target tmp file")
if err := p.removeAllDestFile(); err != nil {
return err
}
}
return err
}
}
fmt.Println("===================================================")
fmt.Println("✅ Successfully executed transfer data to all host")
fmt.Println("===================================================")
return nil
}
func (p Plugin) hostPort(host string) (string, string) {
hosts := strings.Split(host, ":")
port := strconv.Itoa(p.Config.Port)
if len(hosts) > 1 &&
(p.Config.Protocol == easyssh.PROTOCOL_TCP ||
p.Config.Protocol == easyssh.PROTOCOL_TCP4) {
host = hosts[0]
port = hosts[1]
}
return host, port
}
func trimValues(keys []string) []string {
var newKeys []string
for _, value := range keys {
value = strings.TrimSpace(value)
if len(value) == 0 {
continue
}
newKeys = append(newKeys, value)
}
return newKeys
}