2021-08-30 19:55:02 +02:00
|
|
|
import asyncio
|
2022-12-22 15:30:37 +01:00
|
|
|
import glob
|
2021-05-07 04:22:02 +02:00
|
|
|
import importlib
|
2022-07-15 19:54:12 +02:00
|
|
|
import logging
|
2022-12-22 15:30:37 +01:00
|
|
|
import os
|
2023-01-18 15:25:44 +01:00
|
|
|
import shutil
|
2022-08-13 14:46:47 +02:00
|
|
|
import signal
|
2021-08-27 20:54:42 +02:00
|
|
|
import sys
|
2021-05-07 04:22:02 +02:00
|
|
|
import traceback
|
2023-06-20 11:26:33 +02:00
|
|
|
from hashlib import sha256
|
2022-06-13 22:43:17 +02:00
|
|
|
from http import HTTPStatus
|
2023-02-16 09:48:12 +01:00
|
|
|
from typing import Callable, List
|
2020-09-05 08:00:44 +02:00
|
|
|
|
2023-06-20 11:26:33 +02:00
|
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
|
|
from fastapi.exceptions import RequestValidationError
|
2021-08-22 20:07:24 +02:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from fastapi.staticfiles import StaticFiles
|
2022-07-15 19:54:12 +02:00
|
|
|
from loguru import logger
|
2023-06-20 11:26:33 +02:00
|
|
|
from slowapi import Limiter
|
|
|
|
from slowapi.util import get_remote_address
|
|
|
|
from starlette.responses import JSONResponse
|
2020-09-05 08:00:44 +02:00
|
|
|
|
2023-01-18 15:25:44 +01:00
|
|
|
from lnbits.core.crud import get_installed_extensions
|
2023-01-18 17:35:02 +01:00
|
|
|
from lnbits.core.helpers import migrate_extension_database
|
2023-06-20 11:26:33 +02:00
|
|
|
from lnbits.core.services import websocketUpdater
|
|
|
|
from lnbits.core.tasks import ( # register_watchdog,; unregister_watchdog,
|
|
|
|
register_killswitch,
|
|
|
|
register_task_listeners,
|
|
|
|
)
|
2023-06-27 16:11:00 +02:00
|
|
|
from lnbits.settings import settings
|
2023-08-18 11:25:33 +02:00
|
|
|
from lnbits.tasks import cancel_all_tasks, create_permanent_task
|
2023-08-28 11:56:59 +02:00
|
|
|
from lnbits.utils.cache import cache
|
2023-06-27 16:11:00 +02:00
|
|
|
from lnbits.wallets import get_wallet_class, set_wallet_class
|
2022-10-03 16:42:18 +02:00
|
|
|
|
2023-01-19 14:49:43 +01:00
|
|
|
from .commands import db_versions, load_disabled_extension_list, migrate_databases
|
2023-09-12 12:25:05 +02:00
|
|
|
from .core import init_core_routers
|
|
|
|
from .core.db import core_app_extra
|
2023-09-11 15:48:49 +02:00
|
|
|
from .core.services import check_admin_settings, check_webpush_settings
|
2023-09-12 12:25:05 +02:00
|
|
|
from .core.views.api import add_installed_extension
|
|
|
|
from .core.views.generic import update_installed_extension_state
|
2023-02-22 10:12:16 +01:00
|
|
|
from .extension_manager import Extension, InstallableExtension, get_valid_extensions
|
2023-03-31 12:46:24 +02:00
|
|
|
from .helpers import template_renderer
|
2023-06-20 11:26:33 +02:00
|
|
|
from .middleware import (
|
2023-08-18 12:05:14 +02:00
|
|
|
CustomGZipMiddleware,
|
2023-06-20 11:26:33 +02:00
|
|
|
ExtensionsRedirectMiddleware,
|
|
|
|
InstalledExtensionMiddleware,
|
|
|
|
add_ip_block_middleware,
|
|
|
|
add_ratelimit_middleware,
|
|
|
|
)
|
2021-08-27 20:54:42 +02:00
|
|
|
from .requestvars import g
|
2021-10-17 19:33:29 +02:00
|
|
|
from .tasks import (
|
|
|
|
check_pending_payments,
|
|
|
|
internal_invoice_listener,
|
|
|
|
invoice_listener,
|
|
|
|
webhook_handler,
|
|
|
|
)
|
2021-08-27 20:54:42 +02:00
|
|
|
|
2020-09-05 08:00:44 +02:00
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
def create_app() -> FastAPI:
|
2022-07-07 16:24:36 +02:00
|
|
|
configure_logger()
|
2022-07-27 19:20:36 +02:00
|
|
|
app = FastAPI(
|
2023-08-24 11:52:12 +02:00
|
|
|
title=settings.lnbits_title,
|
2023-08-18 11:23:57 +02:00
|
|
|
description=(
|
|
|
|
"API for LNbits, the free and open source bitcoin wallet and "
|
|
|
|
"accounts system with plugins."
|
|
|
|
),
|
2023-03-30 14:19:45 +02:00
|
|
|
version=settings.version,
|
2022-07-27 19:20:36 +02:00
|
|
|
license_info={
|
|
|
|
"name": "MIT License",
|
2022-12-05 12:18:59 +01:00
|
|
|
"url": "https://raw.githubusercontent.com/lnbits/lnbits/main/LICENSE",
|
2022-07-27 19:20:36 +02:00
|
|
|
},
|
|
|
|
)
|
2022-09-22 11:47:24 +02:00
|
|
|
|
2022-07-08 10:49:38 +02:00
|
|
|
app.mount("/static", StaticFiles(packages=[("lnbits", "static")]), name="static")
|
2021-10-17 19:33:29 +02:00
|
|
|
app.mount(
|
2022-07-27 16:45:17 +02:00
|
|
|
"/core/static",
|
|
|
|
StaticFiles(packages=[("lnbits.core", "static")]),
|
|
|
|
name="core_static",
|
2021-10-17 19:33:29 +02:00
|
|
|
)
|
2021-08-22 20:07:24 +02:00
|
|
|
|
2022-11-24 11:35:03 +01:00
|
|
|
g().base_url = f"http://{settings.host}:{settings.port}"
|
|
|
|
|
2021-08-22 20:07:24 +02:00
|
|
|
app.add_middleware(
|
2022-10-03 22:14:07 +02:00
|
|
|
CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
|
2021-08-22 20:07:24 +02:00
|
|
|
)
|
2021-08-27 20:54:42 +02:00
|
|
|
|
2023-08-18 12:05:14 +02:00
|
|
|
app.add_middleware(
|
|
|
|
CustomGZipMiddleware, minimum_size=1000, exclude_paths=["/api/v1/payments/sse"]
|
|
|
|
)
|
2023-02-22 10:12:16 +01:00
|
|
|
|
|
|
|
# order of these two middlewares is important
|
2022-11-29 17:19:33 +01:00
|
|
|
app.add_middleware(InstalledExtensionMiddleware)
|
2023-02-22 10:12:16 +01:00
|
|
|
app.add_middleware(ExtensionsRedirectMiddleware)
|
2020-09-14 02:31:05 +02:00
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
register_startup(app)
|
2021-08-22 20:07:24 +02:00
|
|
|
register_routes(app)
|
2020-09-28 04:12:55 +02:00
|
|
|
register_async_tasks(app)
|
2021-09-30 19:16:38 +02:00
|
|
|
register_exception_handlers(app)
|
2023-06-19 12:12:00 +02:00
|
|
|
register_shutdown(app)
|
2020-09-05 08:00:44 +02:00
|
|
|
|
2023-01-20 16:48:52 +01:00
|
|
|
# Allow registering new extensions routes without direct access to the `app` object
|
2022-12-22 15:30:37 +01:00
|
|
|
setattr(core_app_extra, "register_new_ext_routes", register_new_ext_routes(app))
|
2023-06-20 11:26:33 +02:00
|
|
|
setattr(core_app_extra, "register_new_ratelimiter", register_new_ratelimiter(app))
|
2022-12-22 15:30:37 +01:00
|
|
|
|
2020-09-05 08:00:44 +02:00
|
|
|
return app
|
|
|
|
|
2022-09-22 10:46:11 +02:00
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
async def check_funding_source() -> None:
|
2022-10-06 09:38:17 +02:00
|
|
|
original_sigint_handler = signal.getsignal(signal.SIGINT)
|
2022-09-22 10:46:11 +02:00
|
|
|
|
2022-10-05 13:12:16 +02:00
|
|
|
def signal_handler(signal, frame):
|
2023-08-18 11:23:57 +02:00
|
|
|
logger.debug(
|
|
|
|
f"SIGINT received, terminating LNbits. signal: {signal}, frame: {frame}"
|
|
|
|
)
|
2022-10-05 13:12:16 +02:00
|
|
|
sys.exit(1)
|
2022-10-12 13:08:59 +02:00
|
|
|
|
2022-10-05 13:12:16 +02:00
|
|
|
signal.signal(signal.SIGINT, signal_handler)
|
2022-10-05 09:46:59 +02:00
|
|
|
|
|
|
|
WALLET = get_wallet_class()
|
2023-03-02 12:03:58 +01:00
|
|
|
|
|
|
|
# fallback to void after 30 seconds of failures
|
|
|
|
sleep_time = 5
|
|
|
|
timeout = int(30 / sleep_time)
|
|
|
|
|
|
|
|
balance = 0
|
|
|
|
retry_counter = 0
|
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
error_message, balance = await WALLET.status()
|
|
|
|
if not error_message:
|
2023-03-02 12:03:58 +01:00
|
|
|
retry_counter = 0
|
2022-10-03 16:42:18 +02:00
|
|
|
break
|
2023-03-02 12:03:58 +01:00
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
logger.error(
|
2023-08-18 11:23:57 +02:00
|
|
|
f"The backend for {WALLET.__class__.__name__} isn't "
|
|
|
|
f"working properly: '{error_message}'",
|
2022-10-03 16:42:18 +02:00
|
|
|
RuntimeWarning,
|
|
|
|
)
|
2023-08-23 08:59:39 +02:00
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Error connecting to {WALLET.__class__.__name__}: {e}")
|
2022-10-03 16:42:18 +02:00
|
|
|
pass
|
2023-03-02 12:03:58 +01:00
|
|
|
|
2023-03-02 12:07:20 +01:00
|
|
|
if settings.lnbits_admin_ui and retry_counter == timeout:
|
2023-08-18 11:23:57 +02:00
|
|
|
set_void_wallet_class()
|
2023-03-02 12:03:58 +01:00
|
|
|
WALLET = get_wallet_class()
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
logger.warning(f"Retrying connection to backend in {sleep_time} seconds...")
|
|
|
|
retry_counter += 1
|
|
|
|
await asyncio.sleep(sleep_time)
|
|
|
|
|
2022-10-05 13:12:16 +02:00
|
|
|
signal.signal(signal.SIGINT, original_sigint_handler)
|
2023-03-02 12:03:58 +01:00
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
logger.info(
|
2023-08-18 11:23:57 +02:00
|
|
|
f"✔️ Backend {WALLET.__class__.__name__} connected "
|
|
|
|
f"and with a balance of {balance} msat."
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def set_void_wallet_class():
|
|
|
|
logger.warning(
|
|
|
|
"Fallback to VoidWallet, because the backend for "
|
|
|
|
f"{settings.lnbits_backend_wallet_class} isn't working properly"
|
2022-10-03 16:42:18 +02:00
|
|
|
)
|
2023-08-18 11:23:57 +02:00
|
|
|
set_wallet_class("VoidWallet")
|
2020-10-13 03:25:55 +02:00
|
|
|
|
|
|
|
|
2023-01-18 16:16:15 +01:00
|
|
|
async def check_installed_extensions(app: FastAPI):
|
2022-12-22 15:30:37 +01:00
|
|
|
"""
|
2023-08-18 11:23:57 +02:00
|
|
|
Check extensions that have been installed, but for some reason no longer present in
|
|
|
|
the 'lnbits/extensions' directory. One reason might be a docker-container that was
|
|
|
|
re-created. The 'data' directory (where the '.zip' files live) is expected to
|
|
|
|
persist state. Zips that are missing will be re-downloaded.
|
2022-12-22 15:30:37 +01:00
|
|
|
"""
|
2023-01-19 10:12:48 +01:00
|
|
|
shutil.rmtree(os.path.join("lnbits", "upgrades"), True)
|
2023-01-19 14:49:43 +01:00
|
|
|
await load_disabled_extension_list()
|
2023-02-16 09:48:12 +01:00
|
|
|
installed_extensions = await build_all_installed_extensions_list()
|
2023-01-18 15:25:44 +01:00
|
|
|
|
|
|
|
for ext in installed_extensions:
|
|
|
|
try:
|
2023-05-26 11:48:40 +02:00
|
|
|
installed = check_installed_extension_files(ext)
|
2023-01-18 17:35:02 +01:00
|
|
|
if not installed:
|
2023-01-19 10:12:48 +01:00
|
|
|
await restore_installed_extension(app, ext)
|
2023-05-24 12:58:11 +02:00
|
|
|
logger.info(
|
2023-08-18 11:23:57 +02:00
|
|
|
"✔️ Successfully re-installed extension: "
|
|
|
|
f"{ext.id} ({ext.installed_version})"
|
2023-05-24 12:58:11 +02:00
|
|
|
)
|
2023-01-23 10:51:53 +01:00
|
|
|
except Exception as e:
|
|
|
|
logger.warning(e)
|
2023-05-24 12:58:11 +02:00
|
|
|
logger.warning(
|
|
|
|
f"Failed to re-install extension: {ext.id} ({ext.installed_version})"
|
|
|
|
)
|
2023-01-18 16:16:15 +01:00
|
|
|
|
2023-08-18 11:13:37 +02:00
|
|
|
logger.info(f"Installed Extensions ({len(installed_extensions)}):")
|
|
|
|
for ext in installed_extensions:
|
|
|
|
logger.info(f"{ext.id} ({ext.installed_version})")
|
|
|
|
|
2022-12-22 15:30:37 +01:00
|
|
|
|
2023-02-16 09:48:12 +01:00
|
|
|
async def build_all_installed_extensions_list() -> List[InstallableExtension]:
|
|
|
|
"""
|
|
|
|
Returns a list of all the installed extensions plus the extensions that
|
|
|
|
MUST be installed by default (see LNBITS_EXTENSIONS_DEFAULT_INSTALL).
|
|
|
|
"""
|
|
|
|
installed_extensions = await get_installed_extensions()
|
|
|
|
|
|
|
|
installed_extensions_ids = [e.id for e in installed_extensions]
|
|
|
|
for ext_id in settings.lnbits_extensions_default_install:
|
|
|
|
if ext_id in installed_extensions_ids:
|
|
|
|
continue
|
|
|
|
|
|
|
|
ext_releases = await InstallableExtension.get_extension_releases(ext_id)
|
|
|
|
release = ext_releases[0] if len(ext_releases) else None
|
|
|
|
|
|
|
|
if release:
|
|
|
|
ext_info = InstallableExtension(
|
|
|
|
id=ext_id, name=ext_id, installed_release=release, icon=release.icon
|
|
|
|
)
|
|
|
|
installed_extensions.append(ext_info)
|
|
|
|
|
|
|
|
return installed_extensions
|
|
|
|
|
|
|
|
|
2023-05-26 11:48:40 +02:00
|
|
|
def check_installed_extension_files(ext: InstallableExtension) -> bool:
|
2023-01-25 14:00:39 +01:00
|
|
|
if ext.has_installed_version:
|
|
|
|
return True
|
|
|
|
|
2023-01-19 09:15:56 +01:00
|
|
|
zip_files = glob.glob(
|
|
|
|
os.path.join(settings.lnbits_data_folder, "extensions", "*.zip")
|
|
|
|
)
|
2023-01-18 15:25:44 +01:00
|
|
|
|
2023-03-20 13:20:52 +01:00
|
|
|
if f"./{str(ext.zip_path)}" not in zip_files:
|
2023-01-18 16:16:15 +01:00
|
|
|
ext.download_archive()
|
2023-01-20 14:55:58 +01:00
|
|
|
ext.extract_archive()
|
2023-01-20 14:59:44 +01:00
|
|
|
|
2023-01-18 16:16:15 +01:00
|
|
|
return False
|
2022-12-22 15:30:37 +01:00
|
|
|
|
|
|
|
|
2023-01-19 10:12:48 +01:00
|
|
|
async def restore_installed_extension(app: FastAPI, ext: InstallableExtension):
|
2023-05-26 11:48:40 +02:00
|
|
|
await add_installed_extension(ext)
|
|
|
|
await update_installed_extension_state(ext_id=ext.id, active=True)
|
|
|
|
|
2023-01-19 10:12:48 +01:00
|
|
|
extension = Extension.from_installable_ext(ext)
|
|
|
|
register_ext_routes(app, extension)
|
|
|
|
|
|
|
|
current_version = (await db_versions()).get(ext.id, 0)
|
|
|
|
await migrate_extension_database(extension, current_version)
|
|
|
|
|
|
|
|
# mount routes for the new version
|
|
|
|
core_app_extra.register_new_ext_routes(extension)
|
2023-01-25 14:00:39 +01:00
|
|
|
if extension.upgrade_hash:
|
2023-01-19 10:12:48 +01:00
|
|
|
ext.nofiy_upgrade()
|
|
|
|
|
|
|
|
|
2021-08-22 20:07:24 +02:00
|
|
|
def register_routes(app: FastAPI) -> None:
|
2021-08-23 21:17:46 +02:00
|
|
|
"""Register FastAPI routes / LNbits extensions."""
|
2023-09-12 12:25:05 +02:00
|
|
|
init_core_routers(app)
|
2020-09-05 08:00:44 +02:00
|
|
|
|
2023-01-18 15:32:04 +01:00
|
|
|
for ext in get_valid_extensions():
|
|
|
|
try:
|
|
|
|
register_ext_routes(app, ext)
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(str(e))
|
|
|
|
raise ImportError(
|
|
|
|
f"Please make sure that the extension `{ext.code}` follows conventions."
|
|
|
|
)
|
2020-09-05 08:00:44 +02:00
|
|
|
|
|
|
|
|
2022-12-22 15:30:37 +01:00
|
|
|
def register_new_ext_routes(app: FastAPI) -> Callable:
|
2023-01-20 16:48:52 +01:00
|
|
|
# Returns a function that registers new routes for an extension.
|
2023-08-18 11:23:57 +02:00
|
|
|
# The returned function encapsulates (creates a closure around)
|
|
|
|
# the `app` object but does expose it.
|
2022-12-22 15:30:37 +01:00
|
|
|
def register_new_ext_routes_fn(ext: Extension):
|
|
|
|
register_ext_routes(app, ext)
|
|
|
|
|
|
|
|
return register_new_ext_routes_fn
|
|
|
|
|
|
|
|
|
2023-06-20 11:26:33 +02:00
|
|
|
def register_new_ratelimiter(app: FastAPI) -> Callable:
|
|
|
|
def register_new_ratelimiter_fn():
|
|
|
|
limiter = Limiter(
|
|
|
|
key_func=get_remote_address,
|
|
|
|
default_limits=[
|
|
|
|
f"{settings.lnbits_rate_limit_no}/{settings.lnbits_rate_limit_unit}"
|
|
|
|
],
|
|
|
|
)
|
|
|
|
app.state.limiter = limiter
|
|
|
|
|
|
|
|
return register_new_ratelimiter_fn
|
|
|
|
|
|
|
|
|
2022-12-22 15:30:37 +01:00
|
|
|
def register_ext_routes(app: FastAPI, ext: Extension) -> None:
|
|
|
|
"""Register FastAPI routes for extension."""
|
2022-11-29 17:14:53 +01:00
|
|
|
ext_module = importlib.import_module(ext.module_name)
|
2022-11-29 16:03:46 +01:00
|
|
|
|
2022-12-22 15:30:37 +01:00
|
|
|
ext_route = getattr(ext_module, f"{ext.code}_ext")
|
|
|
|
|
|
|
|
if hasattr(ext_module, f"{ext.code}_start"):
|
|
|
|
ext_start_func = getattr(ext_module, f"{ext.code}_start")
|
|
|
|
ext_start_func()
|
|
|
|
|
|
|
|
if hasattr(ext_module, f"{ext.code}_static_files"):
|
|
|
|
ext_statics = getattr(ext_module, f"{ext.code}_static_files")
|
|
|
|
for s in ext_statics:
|
|
|
|
app.mount(s["path"], s["app"], s["name"])
|
|
|
|
|
2023-02-22 10:12:16 +01:00
|
|
|
if hasattr(ext_module, f"{ext.code}_redirect_paths"):
|
|
|
|
ext_redirects = getattr(ext_module, f"{ext.code}_redirect_paths")
|
|
|
|
settings.lnbits_extensions_redirects = [
|
|
|
|
r for r in settings.lnbits_extensions_redirects if r["ext_id"] != ext.code
|
|
|
|
]
|
|
|
|
for r in ext_redirects:
|
|
|
|
r["ext_id"] = ext.code
|
|
|
|
settings.lnbits_extensions_redirects.append(r)
|
|
|
|
|
2022-12-22 15:30:37 +01:00
|
|
|
logger.trace(f"adding route for extension {ext_module}")
|
2022-11-29 17:14:53 +01:00
|
|
|
|
2023-01-25 13:32:41 +01:00
|
|
|
prefix = f"/upgrades/{ext.upgrade_hash}" if ext.upgrade_hash != "" else ""
|
2022-11-29 17:14:53 +01:00
|
|
|
app.include_router(router=ext_route, prefix=prefix)
|
2022-12-22 15:30:37 +01:00
|
|
|
|
|
|
|
|
2022-10-03 16:42:18 +02:00
|
|
|
def register_startup(app: FastAPI):
|
|
|
|
@app.on_event("startup")
|
|
|
|
async def lnbits_startup():
|
2022-12-09 09:31:29 +01:00
|
|
|
try:
|
2023-01-18 15:25:44 +01:00
|
|
|
# wait till migration is done
|
2022-12-09 09:31:29 +01:00
|
|
|
await migrate_databases()
|
2022-10-03 16:42:18 +02:00
|
|
|
|
2023-01-18 15:25:44 +01:00
|
|
|
# setup admin settings
|
2022-12-09 09:31:29 +01:00
|
|
|
await check_admin_settings()
|
2023-09-11 15:48:49 +02:00
|
|
|
await check_webpush_settings()
|
2022-10-03 16:42:18 +02:00
|
|
|
|
2022-12-09 09:31:29 +01:00
|
|
|
log_server_info()
|
2022-10-03 16:42:18 +02:00
|
|
|
|
2023-06-20 11:26:33 +02:00
|
|
|
# adds security middleware
|
|
|
|
add_ratelimit_middleware(app)
|
|
|
|
add_ip_block_middleware(app)
|
|
|
|
|
2023-01-18 15:25:44 +01:00
|
|
|
# initialize WALLET
|
2023-08-18 11:23:57 +02:00
|
|
|
try:
|
|
|
|
set_wallet_class()
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(
|
|
|
|
f"Error initializing {settings.lnbits_backend_wallet_class}: "
|
|
|
|
f"{str(e)}"
|
|
|
|
)
|
|
|
|
set_void_wallet_class()
|
2022-12-07 13:38:33 +01:00
|
|
|
|
2023-01-18 15:25:44 +01:00
|
|
|
# initialize funding source
|
2022-12-09 09:31:29 +01:00
|
|
|
await check_funding_source()
|
2022-12-22 15:30:37 +01:00
|
|
|
|
2023-01-18 17:35:02 +01:00
|
|
|
# check extensions after restart
|
|
|
|
await check_installed_extensions(app)
|
|
|
|
|
2023-06-20 11:26:33 +02:00
|
|
|
if settings.lnbits_admin_ui:
|
|
|
|
initialize_server_logger()
|
|
|
|
|
2022-12-09 09:31:29 +01:00
|
|
|
except Exception as e:
|
|
|
|
logger.error(str(e))
|
|
|
|
raise ImportError("Failed to run 'startup' event.")
|
2022-10-03 16:42:18 +02:00
|
|
|
|
|
|
|
|
2023-06-19 12:12:00 +02:00
|
|
|
def register_shutdown(app: FastAPI):
|
|
|
|
@app.on_event("shutdown")
|
|
|
|
async def on_shutdown():
|
2023-08-18 11:25:33 +02:00
|
|
|
cancel_all_tasks()
|
|
|
|
# wait a bit to allow them to finish, so that cleanup can run without problems
|
|
|
|
await asyncio.sleep(0.1)
|
2023-06-19 12:12:00 +02:00
|
|
|
WALLET = get_wallet_class()
|
|
|
|
await WALLET.cleanup()
|
|
|
|
|
|
|
|
|
2023-06-20 11:26:33 +02:00
|
|
|
def initialize_server_logger():
|
|
|
|
super_user_hash = sha256(settings.super_user.encode("utf-8")).hexdigest()
|
|
|
|
|
|
|
|
serverlog_queue = asyncio.Queue()
|
|
|
|
|
|
|
|
async def update_websocket_serverlog():
|
|
|
|
while True:
|
|
|
|
msg = await serverlog_queue.get()
|
|
|
|
await websocketUpdater(super_user_hash, msg)
|
|
|
|
|
2023-08-18 11:25:33 +02:00
|
|
|
create_permanent_task(update_websocket_serverlog)
|
2023-06-20 11:26:33 +02:00
|
|
|
|
|
|
|
logger.add(
|
|
|
|
lambda msg: serverlog_queue.put_nowait(msg),
|
|
|
|
format=Formatter().format,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-12-05 12:28:26 +01:00
|
|
|
def log_server_info():
|
|
|
|
logger.info("Starting LNbits")
|
2023-03-30 14:19:45 +02:00
|
|
|
logger.info(f"Version: {settings.version}")
|
2023-02-28 13:45:43 +01:00
|
|
|
logger.info(f"Baseurl: {settings.lnbits_baseurl}")
|
2022-12-05 12:28:26 +01:00
|
|
|
logger.info(f"Host: {settings.host}")
|
|
|
|
logger.info(f"Port: {settings.port}")
|
|
|
|
logger.info(f"Debug: {settings.debug}")
|
|
|
|
logger.info(f"Site title: {settings.lnbits_site_title}")
|
|
|
|
logger.info(f"Funding source: {settings.lnbits_backend_wallet_class}")
|
|
|
|
logger.info(f"Data folder: {settings.lnbits_data_folder}")
|
|
|
|
logger.info(f"Git version: {settings.lnbits_commit}")
|
|
|
|
logger.info(f"Database: {get_db_vendor_name()}")
|
|
|
|
logger.info(f"Service fee: {settings.lnbits_service_fee}")
|
|
|
|
|
|
|
|
|
|
|
|
def get_db_vendor_name():
|
|
|
|
db_url = settings.lnbits_database_url
|
|
|
|
return (
|
|
|
|
"PostgreSQL"
|
|
|
|
if db_url and db_url.startswith("postgres://")
|
2023-08-24 11:26:09 +02:00
|
|
|
else (
|
|
|
|
"CockroachDB"
|
|
|
|
if db_url and db_url.startswith("cockroachdb://")
|
|
|
|
else "SQLite"
|
|
|
|
)
|
2022-12-05 12:28:26 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-09-28 04:12:55 +02:00
|
|
|
def register_async_tasks(app):
|
2021-08-22 20:07:24 +02:00
|
|
|
@app.route("/wallet/webhook")
|
2020-09-28 04:12:55 +02:00
|
|
|
async def webhook_listener():
|
|
|
|
return await webhook_handler()
|
|
|
|
|
2021-08-22 20:07:24 +02:00
|
|
|
@app.on_event("startup")
|
2020-09-28 04:12:55 +02:00
|
|
|
async def listeners():
|
2023-08-18 11:25:33 +02:00
|
|
|
create_permanent_task(check_pending_payments)
|
|
|
|
create_permanent_task(invoice_listener)
|
|
|
|
create_permanent_task(internal_invoice_listener)
|
2023-08-28 11:56:59 +02:00
|
|
|
create_permanent_task(cache.invalidate_forever)
|
2023-08-18 11:25:33 +02:00
|
|
|
register_task_listeners()
|
|
|
|
register_killswitch()
|
2022-10-04 09:51:47 +02:00
|
|
|
# await run_deferred_async() # calle: doesn't do anyting?
|
2021-08-22 20:07:24 +02:00
|
|
|
|
2021-10-17 19:33:29 +02:00
|
|
|
|
2021-09-30 19:16:38 +02:00
|
|
|
def register_exception_handlers(app: FastAPI):
|
|
|
|
@app.exception_handler(Exception)
|
2022-12-14 14:18:42 +01:00
|
|
|
async def exception_handler(request: Request, exc: Exception):
|
2021-09-30 19:16:38 +02:00
|
|
|
etype, _, tb = sys.exc_info()
|
2022-12-14 14:18:42 +01:00
|
|
|
traceback.print_exception(etype, exc, tb)
|
2022-12-14 18:40:07 +01:00
|
|
|
logger.error(f"Exception: {str(exc)}")
|
2022-12-14 19:09:01 +01:00
|
|
|
# Only the browser sends "text/html" request
|
|
|
|
# not fail proof, but everything else get's a JSON response
|
2022-08-14 23:17:53 +02:00
|
|
|
if (
|
|
|
|
request.headers
|
|
|
|
and "accept" in request.headers
|
|
|
|
and "text/html" in request.headers["accept"]
|
|
|
|
):
|
2022-06-15 17:20:20 +02:00
|
|
|
return template_renderer().TemplateResponse(
|
2022-12-14 18:40:07 +01:00
|
|
|
"error.html", {"request": request, "err": f"Error: {str(exc)}"}
|
2022-06-15 17:20:20 +02:00
|
|
|
)
|
2022-06-15 17:49:39 +02:00
|
|
|
|
2022-06-15 17:20:20 +02:00
|
|
|
return JSONResponse(
|
2022-12-14 14:59:11 +01:00
|
|
|
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
|
2022-12-14 18:40:07 +01:00
|
|
|
content={"detail": str(exc)},
|
2021-10-17 19:33:29 +02:00
|
|
|
)
|
2022-07-07 14:30:16 +02:00
|
|
|
|
2022-12-14 14:33:13 +01:00
|
|
|
@app.exception_handler(RequestValidationError)
|
|
|
|
async def validation_exception_handler(
|
|
|
|
request: Request, exc: RequestValidationError
|
|
|
|
):
|
2022-12-14 18:40:07 +01:00
|
|
|
logger.error(f"RequestValidationError: {str(exc)}")
|
2022-12-14 14:33:13 +01:00
|
|
|
# Only the browser sends "text/html" request
|
|
|
|
# not fail proof, but everything else get's a JSON response
|
2022-06-15 17:37:10 +02:00
|
|
|
|
2022-08-14 23:17:53 +02:00
|
|
|
if (
|
|
|
|
request.headers
|
|
|
|
and "accept" in request.headers
|
|
|
|
and "text/html" in request.headers["accept"]
|
|
|
|
):
|
2022-06-15 17:20:20 +02:00
|
|
|
return template_renderer().TemplateResponse(
|
2022-12-14 14:33:13 +01:00
|
|
|
"error.html",
|
2022-12-14 18:40:07 +01:00
|
|
|
{"request": request, "err": f"Error: {str(exc)}"},
|
2022-06-15 17:20:20 +02:00
|
|
|
)
|
2022-06-15 17:49:39 +02:00
|
|
|
|
2022-06-15 17:20:20 +02:00
|
|
|
return JSONResponse(
|
2022-12-14 14:59:11 +01:00
|
|
|
status_code=HTTPStatus.BAD_REQUEST,
|
2022-12-14 18:40:07 +01:00
|
|
|
content={"detail": str(exc)},
|
|
|
|
)
|
|
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
|
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
|
|
logger.error(f"HTTPException {exc.status_code}: {exc.detail}")
|
|
|
|
# Only the browser sends "text/html" request
|
|
|
|
# not fail proof, but everything else get's a JSON response
|
|
|
|
|
|
|
|
if (
|
|
|
|
request.headers
|
|
|
|
and "accept" in request.headers
|
|
|
|
and "text/html" in request.headers["accept"]
|
|
|
|
):
|
|
|
|
return template_renderer().TemplateResponse(
|
|
|
|
"error.html",
|
|
|
|
{
|
|
|
|
"request": request,
|
|
|
|
"err": f"HTTP Error {exc.status_code}: {exc.detail}",
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
return JSONResponse(
|
|
|
|
status_code=exc.status_code,
|
|
|
|
content={"detail": exc.detail},
|
2021-10-17 19:33:29 +02:00
|
|
|
)
|
2022-07-07 14:30:16 +02:00
|
|
|
|
|
|
|
|
2022-07-07 16:24:36 +02:00
|
|
|
def configure_logger() -> None:
|
2022-07-07 14:30:16 +02:00
|
|
|
logger.remove()
|
2022-10-03 16:42:18 +02:00
|
|
|
log_level: str = "DEBUG" if settings.debug else "INFO"
|
2022-07-15 19:54:12 +02:00
|
|
|
formatter = Formatter()
|
2023-07-24 13:25:47 +02:00
|
|
|
logger.add(sys.stdout, level=log_level, format=formatter.format)
|
2022-07-15 19:54:12 +02:00
|
|
|
logging.getLogger("uvicorn").handlers = [InterceptHandler()]
|
|
|
|
logging.getLogger("uvicorn.access").handlers = [InterceptHandler()]
|
2023-07-24 13:25:47 +02:00
|
|
|
logging.getLogger("uvicorn.error").handlers = [InterceptHandler()]
|
|
|
|
logging.getLogger("uvicorn.error").propagate = False
|
2022-07-15 19:54:12 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Formatter:
|
|
|
|
def __init__(self):
|
|
|
|
self.padding = 0
|
2023-08-23 21:24:54 +02:00
|
|
|
self.minimal_fmt = (
|
2023-08-18 11:23:57 +02:00
|
|
|
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | <level>{level}</level> | "
|
|
|
|
"<level>{message}</level>\n"
|
|
|
|
)
|
2022-10-03 16:42:18 +02:00
|
|
|
if settings.debug:
|
2023-08-23 21:24:54 +02:00
|
|
|
self.fmt = (
|
2023-08-18 11:23:57 +02:00
|
|
|
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | "
|
|
|
|
"<level>{level: <4}</level> | "
|
|
|
|
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
|
|
|
|
"<level>{message}</level>\n"
|
2023-04-17 08:29:01 +02:00
|
|
|
)
|
2022-07-15 19:54:12 +02:00
|
|
|
else:
|
2023-08-23 21:24:54 +02:00
|
|
|
self.fmt = self.minimal_fmt
|
2022-07-15 19:54:12 +02:00
|
|
|
|
|
|
|
def format(self, record):
|
2023-08-19 07:38:04 +02:00
|
|
|
function = "{function}".format(**record)
|
2022-07-15 19:54:12 +02:00
|
|
|
if function == "emit": # uvicorn logs
|
|
|
|
return self.minimal_fmt
|
|
|
|
return self.fmt
|
|
|
|
|
|
|
|
|
|
|
|
class InterceptHandler(logging.Handler):
|
|
|
|
def emit(self, record):
|
|
|
|
try:
|
|
|
|
level = logger.level(record.levelname).name
|
|
|
|
except ValueError:
|
|
|
|
level = record.levelno
|
|
|
|
logger.log(level, record.getMessage())
|