-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathcli.py
More file actions
410 lines (311 loc) · 9.96 KB
/
cli.py
File metadata and controls
410 lines (311 loc) · 9.96 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
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
from __future__ import annotations
import json
import os
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING
import click
import requests
from agent.bench import Bench
from agent.proxy import Proxy
from agent.server import Server
from agent.site import Site
from agent.utils import get_timestamp
if TYPE_CHECKING:
from IPython.terminal.embed import InteractiveShellEmbed
@click.group()
def cli():
pass
@cli.group()
def setup():
pass
@cli.command()
@click.option("--restart-web-workers", default=True)
@click.option("--restart-rq-workers", default=True)
@click.option("--restart-redis", default=True)
@click.option("--skip-repo-setup", default=False)
@click.option("--skip-patches", default=False)
def update(restart_web_workers, restart_rq_workers, restart_redis, skip_repo_setup, skip_patches):
Server().update_agent_cli(
restart_redis=restart_redis,
restart_rq_workers=restart_rq_workers,
restart_web_workers=restart_web_workers,
skip_repo_setup=skip_repo_setup,
skip_patches=skip_patches,
)
@cli.command()
def run_patches():
from agent.patch_handler import run_patches
run_patches()
@cli.command()
@click.option("--password", required=True)
def ping_server(password: str):
"""Ping web api on localhost and check for pong."""
res = requests.get(
"http://localhost:25052/ping",
headers={"Authorization": f"bearer {password}"},
)
res = res.json()
if res["message"] != "pong":
raise Exception("pong not in response")
print(res)
@setup.command()
@click.option("--name", required=True)
@click.option("--user", default="frappe")
@click.option("--db-port", default=3306)
@click.option("--workers", required=True, type=int)
@click.option("--proxy-ip", required=False, type=str, default=None)
@click.option("--sentry-dsn", required=False, type=str)
@click.option("--press-url", required=False, type=str)
def config(name, user, workers, proxy_ip=None, sentry_dsn=None, press_url=None, db_port=3306):
config = {
"benches_directory": f"/home/{user}/benches",
"name": name,
"tls_directory": f"/home/{user}/agent/tls",
"nginx_directory": f"/home/{user}/agent/nginx",
"redis_port": 25025,
"user": user,
"workers": workers,
"gunicorn_workers": 2,
"web_port": 25052,
"press_url": "https://frappecloud.com",
"db_port": db_port,
}
if press_url:
config["press_url"] = press_url
if proxy_ip:
config["proxy_ip"] = proxy_ip
if sentry_dsn:
config["sentry_dsn"] = sentry_dsn
with open("config.json", "w") as f:
json.dump(config, f, sort_keys=True, indent=4)
@setup.command()
def pyspy():
privileges_line = "frappe ALL = (root) NOPASSWD: /home/frappe/agent/env/bin/py-spy"
with open("/etc/sudoers.d/frappe", "a+") as sudoers:
sudoers.seek(0)
lines = sudoers.read().splitlines()
if privileges_line not in lines:
sudoers.write(privileges_line + "\n")
@setup.command()
@click.option("--password", prompt=True, hide_input=True)
def authentication(password):
Server().setup_authentication(password)
@setup.command()
@click.option("--sentry-dsn", required=True)
def sentry(sentry_dsn):
Server().setup_sentry(sentry_dsn)
@setup.command()
def supervisor():
Server().setup_supervisor()
@setup.command()
def nginx():
Server().setup_nginx()
@setup.command()
@click.option("--domain")
@click.option("--press-url")
def proxy(domain=None, press_url=None):
proxy = Proxy()
if domain:
config = proxy.get_config(for_update=True)
config["domain"] = domain
config["press_url"] = press_url
proxy.set_config(config, indent=4)
proxy.setup_proxy()
@setup.command()
@click.option("--domain")
def standalone(domain=None):
if not domain:
return
server = Server()
config = server.get_config(for_update=True)
config["domain"] = domain
config["standalone"] = True
server.set_config(config, indent=4)
server.setup_supervisor()
@setup.command()
def database():
from agent.job import JobModel, PatchLogModel, StepModel
from agent.job import agent_database as database
database.create_tables([JobModel, StepModel, PatchLogModel])
@setup.command()
def site_analytics():
from crontab import CronTab
script_directory = os.path.dirname(__file__)
agent_directory = os.path.dirname(os.path.dirname(script_directory))
logs_directory = os.path.join(agent_directory, "logs")
script = os.path.join(script_directory, "analytics.py")
stdout = os.path.join(logs_directory, "analytics.log")
stderr = os.path.join(logs_directory, "analytics.error.log")
cron = CronTab(user=True)
command = f"cd {agent_directory} && {sys.executable} {script} 1>> {stdout} 2>> {stderr}"
if command in str(cron):
cron.remove_all(command=command)
job = cron.new(command=command)
job.hour.on(23)
job.minute.on(0)
cron.write()
@setup.command()
def usage():
from crontab import CronTab
script_directory = os.path.dirname(__file__)
agent_directory = os.path.dirname(os.path.dirname(script_directory))
logs_directory = os.path.join(agent_directory, "logs")
script = os.path.join(script_directory, "usage.py")
stdout = os.path.join(logs_directory, "usage.log")
stderr = os.path.join(logs_directory, "usage.error.log")
cron = CronTab(user=True)
command = f"cd {agent_directory} && {sys.executable} {script} 1>> {stdout} 2>> {stderr}"
if command not in str(cron):
job = cron.new(command=command)
job.every(6).hours()
job.minute.on(30)
cron.write()
@setup.command()
def registry():
Server().setup_registry()
@setup.command()
@click.option("--url", required=True)
@click.option("--token", required=True)
def monitor(url, token):
from agent.monitor import Monitor
server = Monitor()
server.update_config({"monitor": True, "press_url": url, "press_token": token})
server.discover_targets()
@setup.command()
def log():
Server().setup_log()
@setup.command()
def analytics():
Server().setup_analytics()
@setup.command()
def trace():
Server().setup_trace()
@setup.command()
@click.option("--password", prompt=True, hide_input=True)
def proxysql(password):
Server().setup_proxysql(password)
@cli.group()
def run():
pass
@run.command()
def web():
executable = shutil.which("gunicorn")
port = Server().config["web_port"]
arguments = [
executable,
"--bind",
f"127.0.0.1:{port}",
"--reload",
"--preload",
"agent.web:application",
]
os.execv(executable, arguments)
@run.command()
def worker():
executable = shutil.which("rq")
port = Server().config["redis_port"]
arguments = [
executable,
"worker",
"--url",
f"redis://127.0.0.1:{port}",
]
os.execv(executable, arguments)
@cli.command()
def discover():
from agent.monitor import Monitor
Monitor().discover_targets()
@cli.group()
def bench():
pass
@bench.command()
@click.argument("bench", nargs=-1)
def start(bench: tuple[str]):
server = Server()
if bench:
for b in bench:
server.benches[b].start()
else:
server.start_all_benches()
@bench.command()
@click.argument("bench", required=False)
def stop(bench):
if bench:
return Server().benches[bench].stop()
return Server().stop_all_benches()
@cli.command(help="Run iPython console.")
@click.option(
"--config-path",
required=False,
type=str,
help="Path to agent config.json.",
)
def console(config_path):
from atexit import register
from IPython.terminal.embed import InteractiveShellEmbed
terminal = InteractiveShellEmbed.instance()
config_dir = get_config_dir(config_path)
if config_dir:
try:
locals()["server"] = Server(config_dir)
locals()["Proxy"] = Proxy
locals()["Bench"] = Bench
locals()["Site"] = Site
print(f"""
In namespace:
server = agent.server.Server('{config_dir}')
Proxy = agent.proxy.Proxy
Bench = agent.bench.Bench
Site = agent.site.Site
""")
except Exception:
print(f"Could not initialize agent.server.Server('{config_dir}')")
elif config_path:
print(f"Could not find config.json at '{config_path}'")
else:
print("Could not find config.json use --config-path to specify")
register(store_ipython_logs, terminal, config_dir)
# ref: https://stackoverflow.com/a/74681224
try:
from IPython.core import ultratb
ultratb.VerboseTB._tb_highlight = "bg:ansibrightblack"
except Exception:
pass
terminal.colors = "neutral"
terminal.display_banner = False
terminal()
def get_config_dir(config_path: str | None = None) -> str | None:
cwd = os.getcwd()
if config_path is None:
config_path = cwd
config_dir = Path(config_path)
if config_dir.suffix == "json" and config_dir.exists():
return config_dir.parent.as_posix()
if config_dir.suffix != "":
config_dir = config_dir.parent
potential = [
Path("/home/frappe/agent/config.json"),
config_dir / "config.json",
config_dir / ".." / "config.json",
]
for p in potential:
if not p.exists():
continue
try:
return p.parent.relative_to(cwd).as_posix()
except Exception:
return p.parent.as_posix()
return None
def store_ipython_logs(terminal: InteractiveShellEmbed, config_dir: str | None):
if not config_dir:
config_dir = os.getcwd()
log_path = Path(config_dir) / "logs" / "agent_console.log"
log_path.parent.mkdir(exist_ok=True)
with log_path.open("a") as file:
timestamp = get_timestamp()
file.write(f"# SESSION BEGIN {timestamp}\n")
for line in terminal.history_manager.get_range():
file.write(f"{line[2]}\n")
file.write(f"# SESSION END {timestamp}\n\n")