-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
connection.py
374 lines (288 loc) · 13.5 KB
/
connection.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
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
import json
import os
import shutil
import sys
from subprocess import Popen
from typing import List, Optional, Tuple
import click
import psutil
from lightning_utilities.core.imports import package_available
from rich.progress import Progress
from lightning_app.utilities.cli_helpers import _LightningAppOpenAPIRetriever
from lightning_app.utilities.cloud import _get_project
from lightning_app.utilities.enum import OpenAPITags
from lightning_app.utilities.log import get_logfile
from lightning_app.utilities.network import LightningClient
_HOME = os.path.expanduser("~")
_PPID = os.getenv("LIGHTNING_CONNECT_PPID", str(psutil.Process(os.getpid()).ppid()))
_LIGHTNING_CONNECTION = os.path.join(_HOME, ".lightning", "lightning_connection")
_LIGHTNING_CONNECTION_FOLDER = os.path.join(_LIGHTNING_CONNECTION, _PPID)
@click.argument("app_name_or_id", required=True)
def connect(app_name_or_id: str):
"""Connect your local terminal to a running lightning app.
After connecting, the lightning CLI will respond to commands exposed by the app.
Example:
\b
# connect to an app named pizza-cooker-123
lightning connect pizza-cooker-123
\b
# this will now show the commands exposed by pizza-cooker-123
lightning --help
\b
# while connected, you can run the cook-pizza command exposed
# by pizza-cooker-123.BTW, this should arguably generate an exception :-)
lightning cook-pizza --flavor pineapple
\b
# once done, disconnect and go back to the standard lightning CLI commands
lightning disconnect
"""
from lightning_app.utilities.commands.base import _download_command
_clean_lightning_connection()
if not os.path.exists(_LIGHTNING_CONNECTION_FOLDER):
os.makedirs(_LIGHTNING_CONNECTION_FOLDER)
connected_file = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "connect.txt")
matched_connection_path = _scan_lightning_connections(app_name_or_id)
if os.path.exists(connected_file):
with open(connected_file) as f:
result = f.readlines()[0].replace("\n", "")
if result == app_name_or_id:
if app_name_or_id == "localhost":
click.echo("You are connected to the local Lightning App.")
else:
click.echo(f"You are already connected to the cloud Lightning App: {app_name_or_id}.")
else:
disconnect()
connect(app_name_or_id)
elif app_name_or_id.startswith("localhost"):
with Progress() as progress_bar:
connecting = progress_bar.add_task("[magenta]Setting things up for you...", total=1.0)
if app_name_or_id != "localhost":
raise Exception("You need to pass localhost to connect to the local Lightning App.")
retriever = _LightningAppOpenAPIRetriever(None)
if retriever.api_commands is None:
raise Exception(f"Connection wasn't successful. Is your app {app_name_or_id} running?")
increment = 1 / (1 + len(retriever.api_commands))
progress_bar.update(connecting, advance=increment)
commands_folder = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands")
if not os.path.exists(commands_folder):
os.makedirs(commands_folder)
_write_commands_metadata(retriever.api_commands)
with open(os.path.join(commands_folder, "openapi.json"), "w") as f:
json.dump(retriever.openapi, f)
_install_missing_requirements(retriever)
for command_name, metadata in retriever.api_commands.items():
if "cls_path" in metadata:
target_file = os.path.join(commands_folder, f"{command_name.replace(' ','_')}.py")
_download_command(
command_name,
metadata["cls_path"],
metadata["cls_name"],
None,
target_file=target_file,
)
else:
with open(os.path.join(commands_folder, f"{command_name}.txt"), "w") as f:
f.write(command_name)
progress_bar.update(connecting, advance=increment)
with open(connected_file, "w") as f:
f.write(app_name_or_id + "\n")
click.echo("The lightning CLI now responds to app commands. Use 'lightning --help' to see them.")
click.echo(" ")
Popen(
f"LIGHTNING_CONNECT_PPID={_PPID} {sys.executable} -m lightning --help",
shell=True,
stdout=sys.stdout,
stderr=sys.stderr,
).wait()
elif matched_connection_path:
matched_connected_file = os.path.join(matched_connection_path, "connect.txt")
matched_commands = os.path.join(matched_connection_path, "commands")
if os.path.isdir(matched_commands):
commands = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands")
shutil.copytree(matched_commands, commands)
shutil.copy(matched_connected_file, connected_file)
click.echo("The lightning CLI now responds to app commands. Use 'lightning --help' to see them.")
click.echo(" ")
Popen(
f"LIGHTNING_CONNECT_PPID={_PPID} {sys.executable} -m lightning --help",
shell=True,
stdout=sys.stdout,
stderr=sys.stderr,
).wait()
else:
with Progress() as progress_bar:
connecting = progress_bar.add_task("[magenta]Setting things up for you...", total=1.0)
retriever = _LightningAppOpenAPIRetriever(app_name_or_id)
if not retriever.api_commands:
client = LightningClient()
project = _get_project(client)
apps = client.lightningapp_instance_service_list_lightningapp_instances(project_id=project.project_id)
click.echo(
"We didn't find a matching App. Here are the available Apps that you can"
f"connect to {[app.name for app in apps.lightningapps]}."
)
return
increment = 1 / (1 + len(retriever.api_commands))
progress_bar.update(connecting, advance=increment)
_install_missing_requirements(retriever)
commands_folder = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands")
if not os.path.exists(commands_folder):
os.makedirs(commands_folder)
_write_commands_metadata(retriever.api_commands)
for command_name, metadata in retriever.api_commands.items():
if "cls_path" in metadata:
target_file = os.path.join(commands_folder, f"{command_name}.py")
_download_command(
command_name,
metadata["cls_path"],
metadata["cls_name"],
retriever.app_id,
target_file=target_file,
)
else:
with open(os.path.join(commands_folder, f"{command_name}.txt"), "w") as f:
f.write(command_name)
progress_bar.update(connecting, advance=increment)
with open(connected_file, "w") as f:
f.write(retriever.app_name + "\n")
f.write(retriever.app_id + "\n")
click.echo("The lightning CLI now responds to app commands. Use 'lightning --help' to see them.")
click.echo(" ")
Popen(
f"LIGHTNING_CONNECT_PPID={_PPID} {sys.executable} -m lightning --help",
shell=True,
stdout=sys.stdout,
stderr=sys.stderr,
).wait()
def disconnect(logout: bool = False):
"""Disconnect from an App."""
_clean_lightning_connection()
connected_file = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "connect.txt")
if os.path.exists(connected_file):
with open(connected_file) as f:
result = f.readlines()[0].replace("\n", "")
os.remove(connected_file)
commands_folder = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands")
if os.path.exists(commands_folder):
shutil.rmtree(commands_folder)
if result == "localhost":
click.echo("You are disconnected from the local Lightning App.")
else:
click.echo(f"You are disconnected from the cloud Lightning App: {result}.")
else:
if not logout:
click.echo(
"You aren't connected to any Lightning App. "
"Please use `lightning connect app_name_or_id` to connect to one."
)
def _read_connected_file(connected_file):
if os.path.exists(connected_file):
with open(connected_file) as f:
lines = [line.replace("\n", "") for line in f.readlines()]
if len(lines) == 2:
return lines[0], lines[1]
return lines[0], None
return None, None
def _retrieve_connection_to_an_app() -> Tuple[Optional[str], Optional[str]]:
connected_file = os.path.join(_LIGHTNING_CONNECTION_FOLDER, "connect.txt")
return _read_connected_file(connected_file)
def _get_commands_folder() -> str:
return os.path.join(_LIGHTNING_CONNECTION_FOLDER, "commands")
def _write_commands_metadata(api_commands):
metadata = {command_name: metadata for command_name, metadata in api_commands.items()}
metadata_path = os.path.join(_get_commands_folder(), ".meta.json")
with open(metadata_path, "w") as f:
json.dump(metadata, f)
def _get_commands_metadata():
metadata_path = os.path.join(_get_commands_folder(), ".meta.json")
with open(metadata_path) as f:
return json.load(f)
def _resolve_command_path(command: str) -> str:
return os.path.join(_get_commands_folder(), f"{command}.py")
def _list_app_commands(echo: bool = True) -> List[str]:
metadata = _get_commands_metadata()
metadata = {key.replace("_", " "): value for key, value in metadata.items()}
command_names = list(sorted(metadata.keys()))
if not command_names:
click.echo("The current Lightning App doesn't have commands.")
return []
app_info = metadata[command_names[0]].get("app_info", None)
title, description, on_connect_end = "Lightning", None, None
if app_info:
title = app_info.get("title")
description = app_info.get("description")
on_connect_end = app_info.get("on_connect_end")
if echo:
click.echo(f"{title} App")
if description:
click.echo("")
click.echo("Description:")
if description.endswith("\n"):
description = description[:-2]
click.echo(f" {description}")
click.echo("")
click.echo("Commands:")
max_length = max(len(n) for n in command_names)
for command_name in command_names:
padding = (max_length + 1 - len(command_name)) * " "
click.echo(f" {command_name}{padding}{metadata[command_name].get('description', '')}")
if "LIGHTNING_CONNECT_PPID" in os.environ and on_connect_end:
if on_connect_end.endswith("\n"):
on_connect_end = on_connect_end[:-2]
click.echo(on_connect_end)
return command_names
def _install_missing_requirements(
retriever: _LightningAppOpenAPIRetriever,
fail_if_missing: bool = False,
):
requirements = set()
for metadata in retriever.api_commands.values():
if metadata["tag"] == OpenAPITags.APP_CLIENT_COMMAND:
for req in metadata.get("requirements", []) or []:
requirements.add(req)
if requirements:
missing_requirements = []
for req in requirements:
if not (package_available(req) or package_available(req.replace("-", "_"))):
missing_requirements.append(req)
if missing_requirements:
if fail_if_missing:
missing_requirements = " ".join(missing_requirements)
print(f"The command failed as you are missing the following requirements: `{missing_requirements}`.")
sys.exit(0)
for req in missing_requirements:
std_out_out = get_logfile("output.log")
with open(std_out_out, "wb") as stdout:
Popen(
f"{sys.executable} -m pip install {req}",
shell=True,
stdout=stdout,
stderr=stdout,
).wait()
os.remove(std_out_out)
def _clean_lightning_connection():
if not os.path.exists(_LIGHTNING_CONNECTION):
return
for ppid in os.listdir(_LIGHTNING_CONNECTION):
try:
psutil.Process(int(ppid))
except (psutil.NoSuchProcess, ValueError):
connection = os.path.join(_LIGHTNING_CONNECTION, str(ppid))
if os.path.exists(connection):
shutil.rmtree(connection)
def _scan_lightning_connections(app_name_or_id):
if not os.path.exists(_LIGHTNING_CONNECTION):
return
for ppid in os.listdir(_LIGHTNING_CONNECTION):
try:
psutil.Process(int(ppid))
except (psutil.NoSuchProcess, ValueError):
continue
connection_path = os.path.join(_LIGHTNING_CONNECTION, str(ppid))
connected_file = os.path.join(connection_path, "connect.txt")
curr_app_name, curr_app_id = _read_connected_file(connected_file)
if not curr_app_name:
continue
if app_name_or_id == curr_app_name or app_name_or_id == curr_app_id:
return connection_path
return None