views.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. __package__ = 'abx.archivebox'
  2. import os
  3. import inspect
  4. from pathlib import Path
  5. from typing import Any, List, Dict, cast
  6. from benedict import benedict
  7. from django.http import HttpRequest
  8. from django.conf import settings
  9. from django.utils import timezone
  10. from django.utils.html import format_html, mark_safe
  11. from admin_data_views.typing import TableContext, ItemContext
  12. from admin_data_views.utils import render_with_table_view, render_with_item_view, ItemLink
  13. import abx
  14. import archivebox
  15. from archivebox.config import CONSTANTS
  16. from archivebox.misc.util import parse_date
  17. from machine.models import InstalledBinary
  18. def obj_to_yaml(obj: Any, indent: int=0) -> str:
  19. indent_str = " " * indent
  20. if indent == 0:
  21. indent_str = '\n' # put extra newline between top-level entries
  22. if isinstance(obj, dict):
  23. if not obj:
  24. return "{}"
  25. result = "\n"
  26. for key, value in obj.items():
  27. result += f"{indent_str}{key}:{obj_to_yaml(value, indent + 1)}\n"
  28. return result
  29. elif isinstance(obj, list):
  30. if not obj:
  31. return "[]"
  32. result = "\n"
  33. for item in obj:
  34. result += f"{indent_str}- {obj_to_yaml(item, indent + 1).lstrip()}\n"
  35. return result.rstrip()
  36. elif isinstance(obj, str):
  37. if "\n" in obj:
  38. return f" |\n{indent_str} " + obj.replace("\n", f"\n{indent_str} ")
  39. else:
  40. return f" {obj}"
  41. elif isinstance(obj, (int, float, bool)):
  42. return f" {str(obj)}"
  43. elif callable(obj):
  44. source = '\n'.join(
  45. '' if 'def ' in line else line
  46. for line in inspect.getsource(obj).split('\n')
  47. if line.strip()
  48. ).split('lambda: ')[-1].rstrip(',')
  49. return f" {indent_str} " + source.replace("\n", f"\n{indent_str} ")
  50. else:
  51. return f" {str(obj)}"
  52. @render_with_table_view
  53. def binaries_list_view(request: HttpRequest, **kwargs) -> TableContext:
  54. FLAT_CONFIG = archivebox.pm.hook.get_FLAT_CONFIG()
  55. assert request.user.is_superuser, 'Must be a superuser to view configuration settings.'
  56. rows = {
  57. "Binary Name": [],
  58. "Found Version": [],
  59. "From Plugin": [],
  60. "Provided By": [],
  61. "Found Abspath": [],
  62. "Related Configuration": [],
  63. # "Overrides": [],
  64. # "Description": [],
  65. }
  66. relevant_configs = {
  67. key: val
  68. for key, val in FLAT_CONFIG.items()
  69. if '_BINARY' in key or '_VERSION' in key
  70. }
  71. for plugin_id, plugin in abx.get_all_plugins().items():
  72. if not plugin.hooks.get('get_BINARIES'):
  73. continue
  74. for binary in plugin.hooks.get_BINARIES().values():
  75. try:
  76. installed_binary = InstalledBinary.objects.get_from_db_or_cache(binary)
  77. binary = installed_binary.load_from_db()
  78. except Exception as e:
  79. print(e)
  80. rows['Binary Name'].append(ItemLink(binary.name, key=binary.name))
  81. rows['Found Version'].append(f'✅ {binary.loaded_version}' if binary.loaded_version else '❌ missing')
  82. rows['From Plugin'].append(plugin.package)
  83. rows['Provided By'].append(
  84. ', '.join(
  85. f'[{binprovider.name}]' if binprovider.name == getattr(binary.loaded_binprovider, 'name', None) else binprovider.name
  86. for binprovider in binary.binproviders_supported
  87. if binprovider
  88. )
  89. # binary.loaded_binprovider.name
  90. # if binary.loaded_binprovider else
  91. # ', '.join(getattr(provider, 'name', str(provider)) for provider in binary.binproviders_supported)
  92. )
  93. rows['Found Abspath'].append(str(binary.loaded_abspath or '❌ missing'))
  94. rows['Related Configuration'].append(mark_safe(', '.join(
  95. f'<a href="/admin/environment/config/{config_key}/">{config_key}</a>'
  96. for config_key, config_value in relevant_configs.items()
  97. if str(binary.name).lower().replace('-', '').replace('_', '').replace('ytdlp', 'youtubedl') in config_key.lower()
  98. or config_value.lower().endswith(binary.name.lower())
  99. # or binary.name.lower().replace('-', '').replace('_', '') in str(config_value).lower()
  100. )))
  101. # if not binary.overrides:
  102. # import ipdb; ipdb.set_trace()
  103. # rows['Overrides'].append(str(obj_to_yaml(binary.overrides) or str(binary.overrides))[:200])
  104. # rows['Description'].append(binary.description)
  105. return TableContext(
  106. title="Binaries",
  107. table=rows,
  108. )
  109. @render_with_item_view
  110. def binary_detail_view(request: HttpRequest, key: str, **kwargs) -> ItemContext:
  111. assert request.user and request.user.is_superuser, 'Must be a superuser to view configuration settings.'
  112. binary = None
  113. plugin = None
  114. for plugin_id, plugin in abx.get_all_plugins().items():
  115. try:
  116. for loaded_binary in plugin['hooks'].get_BINARIES().values():
  117. if loaded_binary.name == key:
  118. binary = loaded_binary
  119. plugin = plugin
  120. # break # last write wins
  121. except Exception as e:
  122. print(e)
  123. assert plugin and binary, f'Could not find a binary matching the specified name: {key}'
  124. try:
  125. binary = binary.load()
  126. except Exception as e:
  127. print(e)
  128. return ItemContext(
  129. slug=key,
  130. title=key,
  131. data=[
  132. {
  133. "name": binary.name,
  134. "description": binary.abspath,
  135. "fields": {
  136. 'plugin': plugin['package'],
  137. 'binprovider': binary.loaded_binprovider,
  138. 'abspath': binary.loaded_abspath,
  139. 'version': binary.loaded_version,
  140. 'overrides': obj_to_yaml(binary.overrides),
  141. 'providers': obj_to_yaml(binary.binproviders_supported),
  142. },
  143. "help_texts": {
  144. # TODO
  145. },
  146. },
  147. ],
  148. )
  149. @render_with_table_view
  150. def plugins_list_view(request: HttpRequest, **kwargs) -> TableContext:
  151. assert request.user.is_superuser, 'Must be a superuser to view configuration settings.'
  152. rows = {
  153. "Label": [],
  154. "Version": [],
  155. "Author": [],
  156. "Package": [],
  157. "Source Code": [],
  158. "Config": [],
  159. "Binaries": [],
  160. "Package Managers": [],
  161. # "Search Backends": [],
  162. }
  163. config_colors = {
  164. '_BINARY': '#339',
  165. 'USE_': 'green',
  166. 'SAVE_': 'green',
  167. '_ARGS': '#33e',
  168. 'KEY': 'red',
  169. 'COOKIES': 'red',
  170. 'AUTH': 'red',
  171. 'SECRET': 'red',
  172. 'TOKEN': 'red',
  173. 'PASSWORD': 'red',
  174. 'TIMEOUT': '#533',
  175. 'RETRIES': '#533',
  176. 'MAX': '#533',
  177. 'MIN': '#533',
  178. }
  179. def get_color(key):
  180. for pattern, color in config_colors.items():
  181. if pattern in key:
  182. return color
  183. return 'black'
  184. for plugin_id, plugin in abx.get_all_plugins().items():
  185. plugin.hooks.get_BINPROVIDERS = plugin.hooks.get('get_BINPROVIDERS', lambda: {})
  186. plugin.hooks.get_BINARIES = plugin.hooks.get('get_BINARIES', lambda: {})
  187. plugin.hooks.get_CONFIG = plugin.hooks.get('get_CONFIG', lambda: {})
  188. rows['Label'].append(ItemLink(plugin.label, key=plugin.package))
  189. rows['Version'].append(str(plugin.version))
  190. rows['Author'].append(mark_safe(f'<a href="{plugin.homepage}" target="_blank">{plugin.author}</a>'))
  191. rows['Package'].append(ItemLink(plugin.package, key=plugin.package))
  192. rows['Source Code'].append(format_html('<code>{}</code>', str(plugin.source_code).replace(str(Path('~').expanduser()), '~')))
  193. rows['Config'].append(mark_safe(''.join(
  194. f'<a href="/admin/environment/config/{key}/"><b><code style="color: {get_color(key)};">{key}</code></b>=<code>{value}</code></a><br/>'
  195. for configdict in plugin.hooks.get_CONFIG().values()
  196. for key, value in benedict(configdict).items()
  197. )))
  198. rows['Binaries'].append(mark_safe(', '.join(
  199. f'<a href="/admin/environment/binaries/{binary.name}/"><code>{binary.name}</code></a>'
  200. for binary in plugin.hooks.get_BINARIES().values()
  201. )))
  202. rows['Package Managers'].append(mark_safe(', '.join(
  203. f'<a href="/admin/environment/binproviders/{binprovider.name}/"><code>{binprovider.name}</code></a>'
  204. for binprovider in plugin.hooks.get_BINPROVIDERS().values()
  205. )))
  206. # rows['Search Backends'].append(mark_safe(', '.join(
  207. # f'<a href="/admin/environment/searchbackends/{searchbackend.name}/"><code>{searchbackend.name}</code></a>'
  208. # for searchbackend in plugin.SEARCHBACKENDS.values()
  209. # )))
  210. return TableContext(
  211. title="Installed plugins",
  212. table=rows,
  213. )
  214. @render_with_item_view
  215. def plugin_detail_view(request: HttpRequest, key: str, **kwargs) -> ItemContext:
  216. assert request.user.is_superuser, 'Must be a superuser to view configuration settings.'
  217. plugin_id = None
  218. for check_plugin_id, loaded_plugin in settings.PLUGINS.items():
  219. if check_plugin_id.split('.')[-1] == key.split('.')[-1]:
  220. plugin_id = check_plugin_id
  221. break
  222. assert plugin_id, f'Could not find a plugin matching the specified name: {key}'
  223. plugin = abx.get_plugin(plugin_id)
  224. return ItemContext(
  225. slug=key,
  226. title=key,
  227. data=[
  228. {
  229. "name": plugin.package,
  230. "description": plugin.label,
  231. "fields": {
  232. "id": plugin.id,
  233. "package": plugin.package,
  234. "label": plugin.label,
  235. "version": plugin.version,
  236. "author": plugin.author,
  237. "homepage": plugin.homepage,
  238. "dependencies": getattr(plugin, 'DEPENDENCIES', []),
  239. "source_code": plugin.source_code,
  240. "hooks": plugin.hooks,
  241. },
  242. "help_texts": {
  243. # TODO
  244. },
  245. },
  246. ],
  247. )
  248. @render_with_table_view
  249. def worker_list_view(request: HttpRequest, **kwargs) -> TableContext:
  250. assert request.user.is_superuser, "Must be a superuser to view configuration settings."
  251. rows = {
  252. "Name": [],
  253. "State": [],
  254. "PID": [],
  255. "Started": [],
  256. "Command": [],
  257. "Logfile": [],
  258. "Exit Status": [],
  259. }
  260. from queues.supervisor_util import get_existing_supervisord_process
  261. supervisor = get_existing_supervisord_process()
  262. if supervisor is None:
  263. return TableContext(
  264. title="No running worker processes",
  265. table=rows,
  266. )
  267. all_config_entries = cast(List[Dict[str, Any]], supervisor.getAllConfigInfo() or [])
  268. all_config = {config["name"]: benedict(config) for config in all_config_entries}
  269. # Add top row for supervisord process manager
  270. rows["Name"].append(ItemLink('supervisord', key='supervisord'))
  271. rows["State"].append(supervisor.getState()['statename'])
  272. rows['PID'].append(str(supervisor.getPID()))
  273. rows["Started"].append('-')
  274. rows["Command"].append('supervisord --configuration=tmp/supervisord.conf')
  275. rows["Logfile"].append(
  276. format_html(
  277. '<a href="/admin/environment/logs/{}/">{}</a>',
  278. 'supervisord',
  279. 'logs/supervisord.log',
  280. )
  281. )
  282. rows['Exit Status'].append('0')
  283. # Add a row for each worker process managed by supervisord
  284. for proc in cast(List[Dict[str, Any]], supervisor.getAllProcessInfo()):
  285. proc = benedict(proc)
  286. # {
  287. # "name": "daphne",
  288. # "group": "daphne",
  289. # "start": 1725933056,
  290. # "stop": 0,
  291. # "now": 1725933438,
  292. # "state": 20,
  293. # "statename": "RUNNING",
  294. # "spawnerr": "",
  295. # "exitstatus": 0,
  296. # "logfile": "logs/server.log",
  297. # "stdout_logfile": "logs/server.log",
  298. # "stderr_logfile": "",
  299. # "pid": 33283,
  300. # "description": "pid 33283, uptime 0:06:22",
  301. # }
  302. rows["Name"].append(ItemLink(proc.name, key=proc.name))
  303. rows["State"].append(proc.statename)
  304. rows['PID'].append(proc.description.replace('pid ', ''))
  305. rows["Started"].append(parse_date(proc.start).strftime("%Y-%m-%d %H:%M:%S") if proc.start else '')
  306. rows["Command"].append(all_config[proc.name].command)
  307. rows["Logfile"].append(
  308. format_html(
  309. '<a href="/admin/environment/logs/{}/">{}</a>',
  310. proc.stdout_logfile.split("/")[-1].split('.')[0],
  311. proc.stdout_logfile,
  312. )
  313. )
  314. rows["Exit Status"].append(str(proc.exitstatus))
  315. return TableContext(
  316. title="Running worker processes",
  317. table=rows,
  318. )
  319. @render_with_item_view
  320. def worker_detail_view(request: HttpRequest, key: str, **kwargs) -> ItemContext:
  321. assert request.user.is_superuser, "Must be a superuser to view configuration settings."
  322. from queues.supervisor_util import get_existing_supervisord_process, get_worker
  323. from queues.settings import SUPERVISORD_CONFIG_FILE
  324. supervisor = get_existing_supervisord_process()
  325. if supervisor is None:
  326. return ItemContext(
  327. slug='none',
  328. title='error: No running supervisord process.',
  329. data=[],
  330. )
  331. all_config = cast(List[Dict[str, Any]], supervisor.getAllConfigInfo() or [])
  332. if key == 'supervisord':
  333. relevant_config = SUPERVISORD_CONFIG_FILE.read_text()
  334. relevant_logs = cast(str, supervisor.readLog(0, 10_000_000))
  335. start_ts = [line for line in relevant_logs.split("\n") if "RPC interface 'supervisor' initialized" in line][-1].split(",", 1)[0]
  336. uptime = str(timezone.now() - parse_date(start_ts)).split(".")[0]
  337. proc = benedict(
  338. {
  339. "name": "supervisord",
  340. "pid": supervisor.getPID(),
  341. "statename": supervisor.getState()["statename"],
  342. "start": start_ts,
  343. "stop": None,
  344. "exitstatus": "",
  345. "stdout_logfile": "logs/supervisord.log",
  346. "description": f'pid 000, uptime {uptime}',
  347. }
  348. )
  349. else:
  350. proc = benedict(get_worker(supervisor, key) or {})
  351. relevant_config = [config for config in all_config if config['name'] == key][0]
  352. relevant_logs = supervisor.tailProcessStdoutLog(key, 0, 10_000_000)[0]
  353. return ItemContext(
  354. slug=key,
  355. title=key,
  356. data=[
  357. {
  358. "name": key,
  359. "description": key,
  360. "fields": {
  361. "Command": proc.name,
  362. "PID": proc.pid,
  363. "State": proc.statename,
  364. "Started": parse_date(proc.start).strftime("%Y-%m-%d %H:%M:%S") if proc.start else "",
  365. "Stopped": parse_date(proc.stop).strftime("%Y-%m-%d %H:%M:%S") if proc.stop else "",
  366. "Exit Status": str(proc.exitstatus),
  367. "Logfile": proc.stdout_logfile,
  368. "Uptime": (proc.description or "").split("uptime ", 1)[-1],
  369. "Config": relevant_config,
  370. "Logs": relevant_logs,
  371. },
  372. "help_texts": {"Uptime": "How long the process has been running ([days:]hours:minutes:seconds)"},
  373. },
  374. ],
  375. )
  376. @render_with_table_view
  377. def log_list_view(request: HttpRequest, **kwargs) -> TableContext:
  378. assert request.user.is_superuser, "Must be a superuser to view configuration settings."
  379. log_files = CONSTANTS.LOGS_DIR.glob("*.log")
  380. log_files = sorted(log_files, key=os.path.getmtime)[::-1]
  381. rows = {
  382. "Name": [],
  383. "Last Updated": [],
  384. "Size": [],
  385. "Most Recent Lines": [],
  386. }
  387. # Add a row for each worker process managed by supervisord
  388. for logfile in log_files:
  389. st = logfile.stat()
  390. rows["Name"].append(ItemLink("logs" + str(logfile).rsplit("/logs", 1)[-1], key=logfile.name))
  391. rows["Last Updated"].append(parse_date(st.st_mtime).strftime("%Y-%m-%d %H:%M:%S"))
  392. rows["Size"].append(f'{st.st_size//1000} kb')
  393. with open(logfile, 'rb') as f:
  394. try:
  395. f.seek(-1024, os.SEEK_END)
  396. except OSError:
  397. f.seek(0)
  398. last_lines = f.read().decode('utf-8', errors='replace').split("\n")
  399. non_empty_lines = [line for line in last_lines if line.strip()]
  400. rows["Most Recent Lines"].append(non_empty_lines[-1])
  401. return TableContext(
  402. title="Debug Log files",
  403. table=rows,
  404. )
  405. @render_with_item_view
  406. def log_detail_view(request: HttpRequest, key: str, **kwargs) -> ItemContext:
  407. assert request.user.is_superuser, "Must be a superuser to view configuration settings."
  408. from django.conf import settings
  409. log_file = [logfile for logfile in CONSTANTS.LOGS_DIR.glob('*.log') if key in logfile.name][0]
  410. log_text = log_file.read_text()
  411. log_stat = log_file.stat()
  412. return ItemContext(
  413. slug=key,
  414. title=key,
  415. data=[
  416. {
  417. "name": key,
  418. "description": key,
  419. "fields": {
  420. "Path": str(log_file),
  421. "Size": f"{log_stat.st_size//1000} kb",
  422. "Last Updated": parse_date(log_stat.st_mtime).strftime("%Y-%m-%d %H:%M:%S"),
  423. "Tail": "\n".join(log_text[-10_000:].split("\n")[-20:]),
  424. "Full Log": log_text,
  425. },
  426. },
  427. ],
  428. )