-
Notifications
You must be signed in to change notification settings - Fork 1
/
forwarder.py
291 lines (240 loc) · 9.51 KB
/
forwarder.py
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
import asyncio
import json
import os
import subprocess
import time
import sys
VERBOSE = False
# Maxinum time to wait for the container to start
MAX_WAIT_TIME = int(os.getenv("PORT_FORWARDER_MAX_WAIT_TIME", 300))
# Flag to indicate if the server should stop running
STOP_RUNNING = False
def verbose_print(message, display=False):
if VERBOSE or display:
with open("/tmp/devcontainer-cli-port-forwarder.log", "w+") as f:
f.write(f"[*] forwarder -- {message}\n")
async def _expect_container(container_id, field, value):
cmd = ["docker", "inspect", "-f", "{{" + field + "}}", container_id]
process = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.PIPE)
stdout, _ = await process.communicate()
return stdout.decode().strip() == value
async def monitor_container(container_id):
global STOP_RUNNING
while True:
container_running = await _expect_container(
container_id, ".State.Running", "true"
)
container_restarting = await _expect_container(
container_id, ".State.Restarting", "true"
)
container_creating = await _expect_container(
container_id, ".State.Status", "created"
)
if not (container_creating or container_restarting) and not container_running:
STOP_RUNNING = True
break
await asyncio.sleep(1) # Check every second
async def forward_data(source, target):
while True:
data = await source.read(4096)
if not data:
break
target.write(data)
await target.drain()
async def handle_client(reader, writer, args):
# Setting up the subprocess to run the command
(container_id, remote_user, port) = args
# Now the container is running, proceed with docker exec
try:
command = [
"docker",
"exec",
"-i",
container_id,
"bash",
"-c",
f"su - {remote_user} -c 'socat - TCP:localhost:{port}'",
]
proc = await asyncio.create_subprocess_exec(
*command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
verbose_print(f"Execute: {' '.join(command)}")
# Give a brief moment for the command to start and potentially fail
await asyncio.sleep(0.5)
# Check if the subprocess was successfully started
if proc.returncode is not None:
# The process terminated immediately, handle the error
verbose_print(
f"Error: subprocess terminated immediately with return code {proc.returncode}"
)
# Check if stderr is available and read from it
if proc.stdout is not None:
if stdout := await proc.stdout.read():
verbose_print(f"Error in subprocess: {stdout.decode()}")
if proc.stderr is not None:
if stderr := await proc.stdout.read():
verbose_print(f"Error in subprocess: {stderr.decode()}")
writer.close()
await writer.wait_closed()
return
except OSError as e:
# Handle errors related to subprocess execution
verbose_print(f"Error executing subprocess: {e}")
writer.close()
await writer.wait_closed()
return
# Separate tasks for reading and writing in both directions
client_to_container = asyncio.create_task(forward_data(reader, proc.stdin))
container_to_client = asyncio.create_task(forward_data(proc.stdout, writer))
# Wait for both tasks to complete
await asyncio.wait(
[client_to_container, container_to_client], return_when=asyncio.FIRST_COMPLETED
)
writer.close()
await writer.wait_closed()
proc.terminate()
verbose_print(f"Termiate process in {container_id} '{command[-1]}'")
async def start_server(container_id: str, remote_user: str, port):
host = "0.0.0.0"
server = await asyncio.start_server(
lambda r, w: handle_client(r, w, (container_id, remote_user, port)),
host,
port,
)
async with server:
await server.start_serving()
verbose_print(f"Listening on {host}:{port}", display=True)
while not STOP_RUNNING:
await asyncio.sleep(1)
server.close()
await server.wait_closed()
verbose_print(f"Stop listening {host}:{port}, exited graceflly", display=True)
async def start_all(container_id, remote_user, forward_ports):
server_tasks = [
start_server(container_id, remote_user, port) for port in forward_ports
]
# Start container monitoring task
monitor_task = asyncio.create_task(monitor_container(container_id))
await asyncio.gather(*server_tasks, monitor_task)
def get_container_id(workspace):
verbose_print("Wait to get container id")
command = [
"docker",
"ps",
"-q",
"--filter",
f"label=devcontainer.local_folder={workspace}",
"--filter",
f"label=devcontainer.config_file={workspace}/.devcontainer/devcontainer.json",
"--filter",
"status=running",
]
result = subprocess.run(command, capture_output=True, text=True)
start_time = time.time()
if not result.stdout.strip():
verbose_print(" ".join(command))
while result.returncode != 0 or not result.stdout.strip():
time.sleep(1) # Wait and check again in 1 second
if time.time() - start_time > MAX_WAIT_TIME:
verbose_print(
f"Exited: Container did not start within {MAX_WAIT_TIME} seconds."
)
exit(1)
else:
result = subprocess.run(command, capture_output=True, text=True)
return result.stdout.strip()
else:
# return result.stdout.strip()
verbose_print(
f"previous devcontainer {result.stdout.strip()} is running, wait for its removal."
)
while result.returncode == 0 and result.stdout.strip():
time.sleep(1)
if time.time() - start_time > MAX_WAIT_TIME:
verbose_print(
f"Exited: Container did not restart within {MAX_WAIT_TIME} seconds."
)
exit(1)
else:
result = subprocess.run(command, capture_output=True, text=True)
# wait for new devcontainer become running
while result.returncode != 0 or not result.stdout.strip():
time.sleep(1)
if time.time() - start_time > MAX_WAIT_TIME:
verbose_print(
f"Exited: Container did not restart within {MAX_WAIT_TIME} seconds."
)
exit(1)
else:
result = subprocess.run(command, capture_output=True, text=True)
return result.stdout.strip()
def wait_for_contaier_running(container_id):
start_time = time.time()
command = ["docker", "inspect", "-f", "{{.State.Running}}", container_id]
result = subprocess.run(command, capture_output=True, text=True)
verbose_print("Wait for container to be running")
while result.returncode != 0 or result.stdout.strip() != "true":
time.sleep(1)
if time.time() - start_time > MAX_WAIT_TIME:
verbose_print(
f"Exited: Container {container_id} .State.Running did not become true within {MAX_WAIT_TIME} seconds."
)
exit(1)
else:
result = subprocess.run(command, capture_output=True, text=True)
def _docker_command(command, container_running=True):
if container_running:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
verbose_print(f"Error: {command} {result.stderr}", display=True)
exit(1)
return result.stdout.strip()
def get_remote_user(devcontainer_json, container_id):
# determine the user to run the command
remoteUser = "root"
if devcontainer_json.get("remoteUser"):
remoteUser = devcontainer_json.get("remoteUser")
else:
metadata: list[dict] = json.loads(
_docker_command(
[
"docker",
"inspect",
"-f",
'{{ index .Config.Labels "devcontainer.metadata" }}',
container_id,
],
)
)
for item in metadata:
if metadata_remote_user := item.get("remoteUser"):
remoteUser = metadata_remote_user
break
verbose_print(f"remoteUser: {remoteUser}")
return remoteUser
def main():
# parse json with comments
# ideally use commentjson or pyjosn5
# but this will introduce dependency
jsondata = ""
with open(".devcontainer/devcontainer.json", "r") as f:
for line in f:
jsondata += line.split("//")[0]
verbose_print(jsondata)
devcontainer_json = json.loads(jsondata)
forward_ports = devcontainer_json.get("forwardPorts", [])
if forward_ports:
workspace = os.path.realpath(os.getcwd())
container_id = get_container_id(workspace)
# wait_for_contaier_running(container_id)
# determine the user to run the socat command
remote_user = get_remote_user(devcontainer_json, container_id)
asyncio.run(start_all(container_id, remote_user, forward_ports))
else:
verbose_print("No forwardPorts found", display=True)
if __name__ == "__main__":
if len(sys.argv) > 1 and (sys.argv[1].lower() == "verbose"):
VERBOSE = True
main()