-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
api_terminal.go
194 lines (165 loc) · 4.87 KB
/
api_terminal.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
package docker
import (
"context"
"github.com/gorilla/mux"
"github.com/docker/docker/api/types"
"github.com/gorilla/websocket"
"net/http"
"strings"
"encoding/json"
"github.com/azukaar/cosmos-server/src/utils"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func splitIntoChunks(input string, chunkSize int) [][]LogOutput {
lines := strings.Split(input, "\n")
var chunks [][]LogOutput
for i := 0; i < len(lines); i += chunkSize {
end := i + chunkSize
// Avoid going over the end of the array
if end > len(lines) {
end = len(lines)
}
var chunk []LogOutput
for j := i; j < end; j++ {
chunk = append(chunk, ParseDockerLogHeader(([]byte)(
lines[j],
)))
}
chunks = append(chunks, chunk)
}
return chunks
}
func TerminalRoute(w http.ResponseWriter, r *http.Request) {
if utils.AdminOnly(w, r) != nil {
return
}
utils.Log("Attempting to attach container")
upgrader.ReadBufferSize = 1024 * 4 // Increase the buffer size as needed
// Upgrade initial GET request to a websocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
utils.Error("Failed to set websocket upgrade: ", err)
http.Error(w, "Failed to set websocket upgrade: "+err.Error(), http.StatusInternalServerError)
return
}
defer ws.Close()
ctx := context.Background()
errD := Connect()
if errD != nil {
utils.Error("ManageContainer", errD)
utils.HTTPError(w, "Internal server error: " + errD.Error(), http.StatusInternalServerError, "DS002")
return
}
vars := mux.Vars(r)
containerID := utils.SanitizeSafe(vars["containerId"])
if containerID == "" {
utils.Error("containerID is required: ", nil)
http.Error(w, "containerID is required", http.StatusBadRequest)
return
}
action := utils.Sanitize(vars["action"])
utils.Log("Attaching container " + containerID + " to websocket")
var resp types.HijackedResponse
if action == "new" {
execConfig := types.ExecConfig{
Tty: true,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Cmd: []string{"/bin/sh"},
}
execStart := types.ExecStartCheck{
Tty: true,
}
execResp, errExec := DockerClient.ContainerExecCreate(ctx, containerID, execConfig)
if errExec != nil {
utils.Error("ContainerExecCreate failed: ", errExec)
http.Error(w, "ContainerExecCreate failed: "+errExec.Error(), http.StatusInternalServerError)
return
}
resp, err = DockerClient.ContainerExecAttach(ctx, execResp.ID, execStart)
if err != nil {
utils.Error("ContainerExecAttach failed: ", err)
http.Error(w, "ContainerExecAttach failed: "+err.Error(), http.StatusInternalServerError)
return
}
utils.Log("Created new shell and attached to it in container " + containerID)
} else {
options := types.ContainerAttachOptions{
Stream: true,
Stdin: true,
Stdout: true,
Stderr: true,
}
// Attach to the container
resp, err = DockerClient.ContainerAttach(ctx, containerID, options)
if err != nil {
utils.Error("ContainerAttach failed: ", err)
http.Error(w, "ContainerAttach failed: "+err.Error(), http.StatusInternalServerError)
return
}
utils.Log("Attached to existing process in container " + containerID)
}
defer resp.Close()
utils.Log("Attached container " + containerID + " to websocket")
var WSChan = make(chan []byte, 1024*1024*4)
var DockerChan = make(chan []byte, 1024*1024*4)
// Start a goroutine to read from our websocket and write to the container
go (func() {
for {
utils.Debug("Waiting for message from websocket")
_, message, err := ws.ReadMessage()
utils.Debug("Got message from websocket")
if err != nil {
utils.Error("Failed to read from websocket: ", err)
break
}
WSChan <- []byte((string)(message) + "\n")
}
})()
// Start a goroutine to read from the container and write to our websocket
go (func() {
for {
buf := make([]byte, 1024*1024*4)
utils.Debug("Waiting for message from container")
n, err := resp.Reader.Read(buf)
utils.Debug("Got message from container")
if err != nil {
utils.Error("Failed to read from container: ", err)
break
}
DockerChan <- buf[:n]
}
})()
for {
select {
case message := <-WSChan:
utils.Debug("Writing message to container")
_, err := resp.Conn.Write(message)
if err != nil {
utils.Error("Failed to write to container: ", err)
return
}
utils.Debug("Wrote message to container")
case message := <-DockerChan:
utils.Debug("Writing message to websocket")
messages := splitIntoChunks(string(message), 5)
for _, messageSplit := range messages {
messageJSON, err := json.Marshal(messageSplit)
if err != nil {
utils.Error("Failed to marshal message: ", err)
return
}
err = ws.WriteMessage(websocket.TextMessage, messageJSON)
if err != nil {
utils.Error("Failed to write to websocket: ", err)
return
}
}
utils.Debug("Wrote message to websocket")
}
}
}