forked from winebarrel/ecs-exec-pf
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession_manager.go
More file actions
89 lines (68 loc) · 1.59 KB
/
Copy pathsession_manager.go
File metadata and controls
89 lines (68 loc) · 1.59 KB
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
package ecsexecpf
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
)
func StartSession(ctx context.Context, cluster string, taskId string, containerId string, port int, localPort int, debug bool) error {
target := fmt.Sprintf("ecs:%s_%s_%s", cluster, taskId, containerId)
params := fmt.Sprintf(`{"portNumber":["%d"],"localPortNumber":["%d"]}`, port, localPort)
cmdWithArgs := []string{
"aws", "ssm", "start-session",
"--target", target,
"--document-name", "AWS-StartPortForwardingSession",
"--parameters", params,
}
if debug {
// extract the parameters element so we can surround them in quotes when printed in the terminal
params := cmdWithArgs[len(cmdWithArgs)-1]
everythingExceptParams := strings.Join(cmdWithArgs[:len(cmdWithArgs)-1], " ")
fmt.Printf("%s '%s'\n", everythingExceptParams, params)
return nil
}
return runCommand(ctx, cmdWithArgs)
}
func runCommand(ctx context.Context, cmdWithArgs []string) error {
cmd := exec.CommandContext(ctx, cmdWithArgs[0], cmdWithArgs[1:]...)
outReader, err := cmd.StdoutPipe()
if err != nil {
return err
}
errReader, err := cmd.StderrPipe()
if err != nil {
return err
}
wg := &sync.WaitGroup{}
wg.Add(2)
sig := make(chan os.Signal, 1)
signal.Notify(sig)
go func() {
for {
s := <-sig
_ = cmd.Process.Signal(s)
}
}()
go func() {
_, _ = io.Copy(os.Stdout, outReader)
wg.Done()
}()
go func() {
_, _ = io.Copy(os.Stderr, errReader)
wg.Done()
}()
err = cmd.Start()
if err != nil {
return err
}
err = cmd.Wait()
if err != nil {
return err
}
wg.Wait()
return nil
}