/
scripts.go
714 lines (633 loc) · 21.7 KB
/
scripts.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
package plugins
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sync"
"github.com/WeBankPartners/wecube-plugins-saltstack/common/log"
"os/exec"
"strings"
"time"
)
const (
SCRIPT_SAVE_PATH = "/srv/salt/base/"
END_POINT_TYPE_S3 = "S3"
END_POINT_TYPE_LOCAL = "LOCAL"
END_POINT_TYPE_USER_PARAM = "USER_PARAM"
)
var ScriptPluginActions = make(map[string]Action)
func init() {
ScriptPluginActions["run"] = new(RunScriptAction)
ScriptPluginActions["ssh-run"] = new(SSHRunScriptAction)
}
type ScriptPlugin struct {
}
func (plugin *ScriptPlugin) GetActionByName(actionName string) (Action, error) {
action, found := ScriptPluginActions[actionName]
if !found {
return nil, fmt.Errorf("Script plugin,action = %s not found", actionName)
}
return action, nil
}
type RunScriptInputs struct {
Inputs []RunScriptInput `json:"inputs,omitempty"`
}
type RunScriptInput struct {
CallBackParameter
EndPointType string `json:"endpointType,omitempty"` // "S3" or "LOCAL", Defalt: "LOCAL"
EndPoint string `json:"endpoint,omitempty"`
ScriptContent string `json:"scriptContent,omitempty"`
Target string `json:"target,omitempty"`
RunAs string `json:"runAs,omitempty"`
ExecArg string `json:"args,omitempty"`
Guid string `json:"guid,omitempty"`
Password string `json:"password,omitempty"`
Seed string `json:"seed,omitempty"`
WorkDir string `json:"workDir,omitempty"`
// AccessKey string `json:"accessKey,omitempty"`
// SecretKey string `json:"secretKey,omitempty"`
}
type RunScriptOutputs struct {
Outputs []RunScriptOutput `json:"outputs"`
}
type RunScriptOutput struct {
CallBackParameter
Result
Target string `json:"target"`
RetCode int `json:"retCode"`
Detail string `json:"detail"`
Guid string `json:"guid,omitempty"`
}
type RunScriptThreadObj struct {
Data RunScriptOutput
Err error
Index int
TmpScriptPathList []string
}
type RunScriptAction struct {
Language string
}
func (action *RunScriptAction) SetAcceptLanguage(language string) {
action.Language = language
}
func (action *RunScriptAction) ReadParam(param interface{}) (interface{}, error) {
var inputs RunScriptInputs
if err := UnmarshalJson(param, &inputs); err != nil {
return nil, err
}
return inputs, nil
}
func (action *RunScriptAction) CheckParam(input RunScriptInput) error {
if input.EndPointType != END_POINT_TYPE_LOCAL && input.EndPointType != END_POINT_TYPE_S3 && input.EndPointType != END_POINT_TYPE_USER_PARAM {
return getParamValidateError(action.Language, "endpointType", fmt.Sprintf("must in (%s,%s,%s)", END_POINT_TYPE_LOCAL, END_POINT_TYPE_S3, END_POINT_TYPE_USER_PARAM))
}
if input.EndPoint == "" && input.EndPointType == END_POINT_TYPE_S3 {
return getParamValidateError(action.Language, "endpoint", "endpoint cat not empty when endpointType="+END_POINT_TYPE_S3)
}
if input.Target == "" {
return getParamEmptyError(action.Language, "target")
}
if input.RunAs == "" {
return getParamEmptyError(action.Language, "runAs")
}
return nil
}
// why not move? TODO
func saveFileToSaltMasterBaseDir(fileName string) (string, error) {
var err error
content, err := ioutil.ReadFile(fileName)
if err != nil {
return "", fmt.Errorf("read %s fail,%s", fileName, err.Error())
}
tmpFile, err := ioutil.TempFile(SCRIPT_SAVE_PATH, "script-")
if err != nil {
return "", fmt.Errorf("create tmp file fail,%s", err.Error())
}
defer func() {
if err != nil {
defer os.Remove(tmpFile.Name())
}
}()
if _, err = tmpFile.Write(content); err != nil {
return "", fmt.Errorf("write content to tmp file fail,%s", err.Error())
}
if err = tmpFile.Close(); err != nil {
return "", fmt.Errorf("close tmp file fail,%s", err.Error())
}
fullPath := tmpFile.Name()
return fullPath, err
}
func executeS3Script(fileName string, target string, runAs string, execArg string, language string) (string, error) {
request := SaltApiRequest{}
request.Client = "local"
request.TargetType = "ipcidr"
request.Target = target
request.Function = "cmd.script"
request.Args = append(request.Args, "salt://base/"+fileName)
if len(execArg) > 0 {
request.Args = append(request.Args, "args="+execArg)
}
if len(runAs) > 0 {
request.Args = append(request.Args, "runas="+runAs)
}
if !SaltResetEnv {
request.Args = append(request.Args, "reset_system_locale=False")
}
result, err := CallSaltApi("https://127.0.0.1:8080", request, language)
if err != nil {
return "", err
}
return result, nil
}
func executeLocalScript(fileName string, target string, runAs string, execArg string, language string) (string, error) {
request := SaltApiRequest{}
request.Client = "local"
request.TargetType = "ipcidr"
request.Target = target
request.Function = "cmd.run"
request.FullReturn = true
log.Logger.Info("Exec local script", log.String("fileName", fileName), log.String("target", target), log.String("runAs", runAs), log.String("args", execArg))
fileScriptPath := fileName
scriptArgs := ""
if strings.Contains(fileName, " ") {
fileScriptPath = strings.Split(fileName, " ")[0]
scriptArgs = fileName[len(fileScriptPath)+1:]
}
var fileAbsPath string
if lastIndex := strings.LastIndex(fileScriptPath, "/"); lastIndex >= 0 {
fileAbsPath = fileScriptPath[:lastIndex]
} else {
return "", fmt.Errorf("script:%s illegal with absolute path check ", fileScriptPath)
}
//fileAbsPath := fileScriptPath[:strings.LastIndex(fileScriptPath, "/")]
if fileAbsPath == "" {
fileAbsPath = "/"
}
fileShellName := fileScriptPath[strings.LastIndex(fileScriptPath, "/")+1:]
//cmdRun := "/bin/bash " + fileName
fileShellName = strings.TrimSpace(fileShellName)
//tmpFileShellBin := fileShellName
//if strings.Contains(tmpFileShellBin, " ") {
// tmpFileShellBin = strings.Split(tmpFileShellBin, " ")[0]
//}
cmdRun := fmt.Sprintf("/bin/bash -c 'cd %s && chmod +x %s && ./%s %s", fileAbsPath, fileShellName, fileShellName, scriptArgs)
if len(execArg) > 0 {
cmdRun = cmdRun + " " + execArg
}
cmdRun += "'"
request.Args = append(request.Args, cmdRun)
if len(runAs) > 0 {
request.Args = append(request.Args, "runas="+runAs)
}
if !SaltResetEnv {
request.Args = append(request.Args, "reset_system_locale=False")
}
log.Logger.Info("Exec script", log.String("target", target), log.StringList("args", request.Args))
result, err := CallSaltApi("https://127.0.0.1:8080", request, language)
if err != nil {
return "", err
}
return result, nil
}
func checkRunUserIsExists(target, userGroup, language string) (exist bool, output string) {
if userGroup == "" {
return false, "user is empty"
}
exist = false
var user, group string
if strings.Contains(userGroup, ":") {
tmpList := strings.Split(userGroup, ":")
user = tmpList[0]
group = tmpList[1]
} else {
user = userGroup
}
log.Logger.Info("Check user group if exist", log.String("user", user), log.String("group", group))
request := SaltApiRequest{}
request.Client = "local"
request.TargetType = "ipcidr"
request.Target = target
request.Function = "cmd.run"
request.FullReturn = true
cmdRun := fmt.Sprintf("/bin/bash -c 'cat /etc/passwd|grep %s:'", user)
request.Args = append(request.Args, cmdRun)
result, err := CallSaltApi("https://127.0.0.1:8080", request, language)
if err != nil {
log.Logger.Error("Check user exists,call salt api error", log.Error(err))
return false, fmt.Sprintf("call salt api error,%s", err.Error())
}
saltApiResult, err := parseSaltApiCmdRunCallResult(result)
if err != nil {
log.Logger.Error("check user exists,parse salt api result error", log.Error(err))
return false, fmt.Sprintf("parse salt api result error,%s", err.Error())
}
for _, v := range saltApiResult.Results[0] {
if strings.Contains(v.RetDetail, user) {
exist = true
}
}
if !exist {
return false, fmt.Sprintf("user %s not exist", user)
}
if group != "" {
exist = false
groupRequest := SaltApiRequest{}
groupRequest.Client = "local"
groupRequest.TargetType = "ipcidr"
groupRequest.Target = target
groupRequest.Function = "cmd.run"
groupRequest.FullReturn = true
cmdRun := fmt.Sprintf("/bin/bash -c 'cat /etc/group|grep %s:'", group)
groupRequest.Args = append(groupRequest.Args, cmdRun)
result, err := CallSaltApi("https://127.0.0.1:8080", groupRequest, language)
if err != nil {
log.Logger.Error("check group exists,call salt api error", log.Error(err))
return false, fmt.Sprintf("check group exists,call salt api error,%s", err.Error())
}
saltApiResult, err := parseSaltApiCmdRunCallResult(result)
if err != nil {
log.Logger.Error("check group exists,parse salt api result error", log.Error(err))
return false, fmt.Sprintf("check group exists,parse salt api result error,%s", err.Error())
}
for _, v := range saltApiResult.Results[0] {
if strings.Contains(v.RetDetail, group) {
exist = true
}
}
if !exist {
return false, fmt.Sprintf("group %s not exist", group)
}
}
return true, ""
}
func downloadFile(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return []byte{}, fmt.Errorf("downloadFile status code=%v", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
func downLoadScript(input RunScriptInput, language string) ([]string, error) {
var result []string
for _, v := range splitWithCustomFlag(input.EndPoint) {
fileName, err := downloadS3File(v, DefaultS3Key, DefaultS3Password, true, language)
if err != nil {
return result, err
}
scriptPath, err := saveFileToSaltMasterBaseDir(fileName)
os.Remove(fileName)
if err != nil {
return result, fmt.Errorf("Move file:%s to salt-dir fail,%v ", fileName, err)
}
result = append(result, scriptPath)
}
return result, nil
}
func runScript(scriptPath string, input RunScriptInput, language string) (string, error) {
var result string
var output string
var err error
if strings.Contains(input.RunAs, ":") {
input.RunAs = strings.Split(input.RunAs, ":")[0]
}
switch input.EndPointType {
case END_POINT_TYPE_LOCAL:
scriptPath = input.WorkDir + scriptPath
result, err = executeLocalScript(scriptPath, input.Target, input.RunAs, input.ExecArg, language)
if err != nil {
return "", getRunRemoteScriptError(language, input.Target, result, err)
}
saltApiResult, err := parseSaltApiCmdRunCallResult(result)
if err != nil {
return "", fmt.Errorf("Parse salt call result fail,%s ", err.Error())
}
for k, v := range saltApiResult.Results[0] {
if k != input.Target {
err = fmt.Errorf("Script run ip[%s] is not a available target[%s] ", k, input.Target)
return fmt.Sprintf("parseSaltApiCmdRunCallResult meet error=%v", err), err
}
if v.RetCode != 0 {
err = fmt.Errorf("Script run ip[%s] meet error = %v ", k, v.RetDetail)
return k + ": " + v.RetDetail, err
}
output = k + ": " + v.RetDetail
break
}
case END_POINT_TYPE_S3, END_POINT_TYPE_USER_PARAM:
result, err = executeS3Script(filepath.Base(scriptPath), input.Target, input.RunAs, input.ExecArg, language)
//os.Remove(scriptPath)
if err != nil {
return "", getRunRemoteScriptError(language, input.Target, result, err)
}
saltApiResult, err := parseSaltApiCmdScriptCallResult(result)
if err != nil {
return "", fmt.Errorf("Parse salt call result fail,%s ", err.Error())
}
for _, v := range saltApiResult.Results[0] {
if v.RetCode != 0 || strings.Contains(v.Stdout, "ERROR") {
return v.Stderr, fmt.Errorf("Script run retCode=%d output=%s error=%s ", v.RetCode, v.Stdout, v.Stderr)
}
output = v.Stdout + v.Stderr
break
}
default:
err = fmt.Errorf("No such endPointType ")
return "", err
}
return output, nil
}
func writeScriptContentToTempFile(content string) (fileName string, err error) {
tmpFile, err := ioutil.TempFile(SCRIPT_SAVE_PATH, "script-")
if err != nil {
err = fmt.Errorf("New tmp file error,%s ", err.Error())
return fileName, err
}
defer func() {
if err != nil {
defer os.Remove(tmpFile.Name())
}
}()
if _, err = tmpFile.Write([]byte(content)); err != nil {
err = fmt.Errorf("Write script content to tmp file error,%s ", err.Error())
return fileName, err
}
if err = tmpFile.Close(); err != nil {
err = fmt.Errorf("Tmp file close fail,%s ", err.Error())
return fileName, err
}
fileName = tmpFile.Name()
return fileName, err
}
func (action *RunScriptAction) runScript(input *RunScriptInput) (output RunScriptOutput, tmpScriptPathList []string, err error) {
defer func() {
output.Guid = input.Guid
output.Target = input.Target
output.CallBackParameter.Parameter = input.CallBackParameter.Parameter
if err == nil {
output.RetCode = 0
output.Result.Code = RESULT_CODE_SUCCESS
} else {
output.RetCode = 1
output.Result.Code = RESULT_CODE_ERROR
output.Result.Message = err.Error()
}
}()
err = action.CheckParam(*input)
if err != nil {
return output, tmpScriptPathList, err
}
if input.RunAs != "" {
if strings.Contains(input.RunAs, ":") {
input.RunAs = strings.Split(input.RunAs, ":")[0]
}
userExist, errOut := checkRunUserIsExists(input.Target, input.RunAs, action.Language)
if !userExist {
err = fmt.Errorf(errOut)
return output, tmpScriptPathList, err
}
}
//scriptPath := input.EndPoint
scriptPathList := splitWithCustomFlag(input.EndPoint)
if input.EndPointType == END_POINT_TYPE_S3 {
scriptPathList, err = downLoadScript(*input, action.Language)
if err != nil {
return output, tmpScriptPathList, err
}
}
if input.EndPointType == END_POINT_TYPE_USER_PARAM {
var scriptPath string
scriptPath, err = writeScriptContentToTempFile(input.ScriptContent)
if err != nil {
return output, tmpScriptPathList, err
}
scriptPathList = []string{scriptPath}
}
var stdOut string
for i, v := range scriptPathList {
stdOut, err = runScript(v, *input, action.Language)
stdOut = fmt.Sprintf("script %d result: %s ", i+1, stdOut)
if i < len(scriptPathList)-1 {
stdOut += " | "
}
output.Detail += stdOut
if err != nil {
log.Logger.Error("Run script fail", log.String("output", stdOut), log.Error(err))
break
}
}
if input.EndPointType == END_POINT_TYPE_S3 || input.EndPointType == END_POINT_TYPE_USER_PARAM {
tmpScriptPathList = scriptPathList
//for _, v := range scriptPathList {
// os.Remove(v)
//}
}
return output, tmpScriptPathList, err
}
func (action *RunScriptAction) Do(input interface{}) (interface{}, error) {
inputs, _ := input.(RunScriptInputs)
outputs := RunScriptOutputs{}
var finalErr error
outputChan := make(chan RunScriptThreadObj, len(inputs.Inputs))
concurrentChan := make(chan int, ApiConcurrentNum)
wg := sync.WaitGroup{}
for i, inputObj := range inputs.Inputs {
concurrentChan <- 1
wg.Add(1)
go func(tmpInput RunScriptInput, index int) {
output, tmpScriptPathList, err := action.runScript(&tmpInput)
outputChan <- RunScriptThreadObj{Data: output, Err: err, Index: index, TmpScriptPathList: tmpScriptPathList}
wg.Done()
<-concurrentChan
}(inputObj, i)
outputs.Outputs = append(outputs.Outputs, RunScriptOutput{})
}
wg.Wait()
for {
if len(outputChan) == 0 {
break
}
tmpOutput := <-outputChan
if tmpOutput.Err != nil {
log.Logger.Error("Run script action", log.Error(tmpOutput.Err))
finalErr = tmpOutput.Err
}
outputs.Outputs[tmpOutput.Index] = tmpOutput.Data
for _, tmpScriptPath := range tmpOutput.TmpScriptPathList {
os.Remove(tmpScriptPath)
}
}
return &outputs, finalErr
}
type SSHRunScriptAction struct{ Language string }
func (action *SSHRunScriptAction) SetAcceptLanguage(language string) {
action.Language = language
}
func (action *SSHRunScriptAction) ReadParam(param interface{}) (interface{}, error) {
var inputs RunScriptInputs
if err := UnmarshalJson(param, &inputs); err != nil {
return nil, err
}
return inputs, nil
}
func (action *SSHRunScriptAction) CheckParam(input RunScriptInput) error {
if input.EndPointType != END_POINT_TYPE_LOCAL && input.EndPointType != END_POINT_TYPE_S3 && input.EndPointType != END_POINT_TYPE_USER_PARAM {
return getParamValidateError(action.Language, "endpointType", fmt.Sprintf("must in (%s,%s,%s)", END_POINT_TYPE_LOCAL, END_POINT_TYPE_S3, END_POINT_TYPE_USER_PARAM))
}
if input.EndPoint == "" && input.EndPointType == END_POINT_TYPE_S3 {
return getParamValidateError(action.Language, "endpoint", "endpoint cat not empty when endpointType="+END_POINT_TYPE_S3)
}
if input.Target == "" {
return getParamEmptyError(action.Language, "target")
}
if checkIllegalParam(input.Target) {
return getParamValidateError(action.Language, "target", "Contains illegal character")
}
if input.RunAs == "" {
return getParamEmptyError(action.Language, "runAs")
}
if checkIllegalParam(input.RunAs) {
return getParamValidateError(action.Language, "runAs", "Contains illegal character")
}
if input.Password == "" {
return getParamEmptyError(action.Language, "password")
}
if checkIllegalParam(input.Password) {
return getParamValidateError(action.Language, "password", "Contains illegal character")
}
return nil
}
func sshRunScript(scriptPath string, input RunScriptInput, language string) (string, error) {
var output string
//var cmdOut []byte
var err error
if strings.Contains(input.RunAs, ":") {
input.RunAs = strings.Split(input.RunAs, ":")[0]
}
remoteParam := ExecRemoteParam{User: input.RunAs, Password: input.Password, Host: input.Target, Timeout: 1800}
switch input.EndPointType {
case END_POINT_TYPE_LOCAL:
localAbsPath := ""
if lastIndex := strings.LastIndex(scriptPath, "/"); lastIndex >= 0 {
localAbsPath = scriptPath[:lastIndex]
} else {
return "", fmt.Errorf("scriptPath:%s illegal with absolute path check ", scriptPath)
}
//localAbsPath := scriptPath[:strings.LastIndex(scriptPath, "/")]
if localAbsPath == "" {
localAbsPath = "/"
}
localShellPath := scriptPath[strings.LastIndex(scriptPath, "/")+1:]
localShellPath = strings.TrimSpace(localShellPath)
tmpFileShellBin := localShellPath
if strings.Contains(tmpFileShellBin, " ") {
tmpFileShellBin = strings.Split(tmpFileShellBin, " ")[0]
}
remoteParam.Command = fmt.Sprintf("/bin/bash -c 'cd %s && chmod +x %s && ./%s", localAbsPath, tmpFileShellBin, localShellPath)
if len(input.ExecArg) > 0 {
remoteParam.Command = remoteParam.Command + " " + input.ExecArg
}
remoteParam.Command += "'"
execRemoteWithTimeout(&remoteParam)
err = remoteParam.Err
output = remoteParam.Output
log.Logger.Debug("SSH run script", log.String("type", input.EndPointType), log.String("command", remoteParam.Command), log.String("target", input.Target), log.String("output", output), log.Error(err))
if err != nil {
return "", getRunRemoteScriptError(language, input.Target, output, err)
}
case END_POINT_TYPE_S3, END_POINT_TYPE_USER_PARAM:
newScriptName := fmt.Sprintf("ssh-script-%s-%d", strings.Replace(input.Target, ".", "-", -1), time.Now().Unix())
tmpOut, err := exec.Command("/bin/cp", "-f", scriptPath, fmt.Sprintf("/var/www/html/tmp/%s", newScriptName)).Output()
if err != nil {
return fmt.Sprintf("exec ssh script,cp %s %s meet error output=%s,err=%s", scriptPath, newScriptName, string(tmpOut), err.Error()), err
}
tmpOut, err = exec.Command("bash", "-c", fmt.Sprintf("chmod 666 /var/www/html/tmp/%s", newScriptName)).Output()
if err != nil {
return fmt.Sprintf("exec ssh script,chmod to %s meet output=%s,err=%s", newScriptName, string(tmpOut), err.Error()), err
}
remoteParam.Command = fmt.Sprintf("curl http://%s:9099/tmp/%s | bash ", MasterHostIp, newScriptName)
execRemoteWithTimeout(&remoteParam)
err = remoteParam.Err
os.Remove(scriptPath)
os.Remove(fmt.Sprintf("/var/www/html/tmp/%s", newScriptName))
output = remoteParam.Output
log.Logger.Debug("SSH run script", log.String("type", input.EndPointType), log.String("script", newScriptName), log.String("target", input.Target), log.String("output", output), log.Error(err))
if err != nil {
return "", getRunRemoteScriptError(language, input.Target, output, err)
}
default:
err = fmt.Errorf("No such endPointType ")
return "", err
}
return output, nil
}
func (action *SSHRunScriptAction) runScript(input *RunScriptInput) (output RunScriptOutput, err error) {
defer func() {
output.Guid = input.Guid
output.Target = input.Target
output.CallBackParameter.Parameter = input.CallBackParameter.Parameter
if err == nil {
output.RetCode = 0
output.Result.Code = RESULT_CODE_SUCCESS
} else {
output.RetCode = 1
output.Result.Code = RESULT_CODE_ERROR
output.Result.Message = err.Error()
}
}()
err = action.CheckParam(*input)
if err != nil {
return output, err
}
//scriptPath := input.EndPoint
scriptPathList := splitWithCustomFlag(input.EndPoint)
if input.EndPointType == END_POINT_TYPE_S3 {
scriptPathList, err = downLoadScript(*input, action.Language)
if err != nil {
return output, err
}
}
if input.EndPointType == END_POINT_TYPE_USER_PARAM {
var scriptPath string
scriptPath, err = writeScriptContentToTempFile(input.ScriptContent)
if err != nil {
return output, err
}
scriptPathList = []string{scriptPath}
}
input.Password, err = AesDePassword(input.Guid, input.Seed, input.Password)
if err != nil {
err = getPasswordDecodeError(action.Language, err)
return output, err
}
var stdOut string
for i, v := range scriptPathList {
stdOut, err = sshRunScript(v, *input, action.Language)
stdOut = fmt.Sprintf("script %d result: %s ", i+1, stdOut)
output.Detail += stdOut
if err != nil {
log.Logger.Error("Run ssh script", log.String("output", stdOut), log.Error(err))
return output, err
}
}
return output, err
}
func (action *SSHRunScriptAction) Do(input interface{}) (interface{}, error) {
inputs, _ := input.(RunScriptInputs)
outputs := RunScriptOutputs{}
var finalErr error
for _, input := range inputs.Inputs {
output, err := action.runScript(&input)
if err != nil {
finalErr = err
}
outputs.Outputs = append(outputs.Outputs, output)
}
return &outputs, finalErr
}