Self-Cpa-Cleaner / hf-dify /runtime.py
axm0121's picture
Deploy Dify 1.18.0 with private Bucket snapshot recovery
9e9c1d6 verified
Raw History Blame Contribute Delete
12.4 kB
"""One-container HF lifecycle. Application processes never inherit HF credentials."""
import json
import os
from pathlib import Path
import pwd
import shutil
import signal
import subprocess
import time
import urllib.request
from persistence import Store, STATE
PROCS = {}
STOP = False
BACKUP = False
SERVICES = ('api', 'worker', 'beat', 'plugin')
BASE_ENV = {'PATH': '/app/api/.venv/bin:/usr/local/bin:/usr/bin:/bin', 'LANG': 'C.UTF-8', 'PYTHONUNBUFFERED': '1', 'HOME': '/home/hfapp', 'TZ': 'UTC'}
MAINT = Path('/run/hf-dify/maintenance')
def log(message):
print('HF-DIFY: ' + message, flush=True)
def request(url, data=None):
encoded = None if data is None else json.dumps(data).encode()
req = urllib.request.Request(url, data=encoded, headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=10) as r:
return json.load(r)
def wait_http(url, timeout=300):
until = time.monotonic() + timeout
while time.monotonic() < until:
try:
return request(url)
except Exception:
for name, proc in PROCS.items():
if proc.poll() is not None:
raise RuntimeError(name + ' exited ' + str(proc.returncode))
time.sleep(2)
raise RuntimeError('Timed out waiting for ' + url)
def start(name, command, env=None, uid=None, cwd='/app/api'):
kwargs = {'env': env or BASE_ENV, 'cwd': cwd, 'start_new_session': True}
if uid is not None:
kwargs.update(user=uid, group=uid, extra_groups=[], umask=0o027)
PROCS[name] = subprocess.Popen(command, **kwargs)
log('started ' + name)
def stop(names):
for name in names:
p = PROCS.get(name)
if p and p.poll() is None:
os.killpg(p.pid, signal.SIGTERM)
deadline = time.monotonic() + 45
for name in names:
p = PROCS.get(name)
if p:
try:
p.wait(timeout=max(0.1, deadline - time.monotonic()))
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.wait()
del PROCS[name]
def signal_handler(signum, frame):
global STOP, BACKUP
if signum == signal.SIGUSR1:
BACKUP = True
else:
STOP = True
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGUSR1):
signal.signal(sig, signal_handler)
required = ('DIFY_SECRET_KEY', 'DIFY_DB_PASSWORD', 'DIFY_REDIS_PASSWORD', 'DIFY_PLUGIN_KEY', 'DIFY_INNER_KEY', 'DIFY_SANDBOX_KEY', 'DIFY_ADMIN_EMAIL', 'DIFY_ADMIN_PASSWORD')
for key in required:
if not os.environ.get(key):
raise RuntimeError('Missing required setting: ' + key)
# Generated credentials contain URL-safe characters, avoiding DSN/config ambiguities.
for key in required:
if key != 'DIFY_ADMIN_EMAIL' and not all(c.isalnum() or c in '_-' for c in os.environ[key]):
raise RuntimeError('Use URL-safe alphanumeric secrets: ' + key)
url = os.environ.get('DIFY_PUBLIC_URL', '')
config = dict(BASE_ENV)
config.update({
'DEPLOY_ENV': 'PRODUCTION', 'EDITION': 'SELF_HOSTED', 'DEPLOYMENT_EDITION': 'COMMUNITY',
'CONSOLE_API_URL': url, 'CONSOLE_WEB_URL': url, 'APP_API_URL': url, 'APP_WEB_URL': url,
'SERVICE_API_URL': url, 'FILES_URL': url, 'INTERNAL_FILES_URL': 'http://127.0.0.1:5001',
'SECRET_KEY': os.environ['DIFY_SECRET_KEY'], 'DB_TYPE': 'postgresql',
'DB_HOST': '127.0.0.1', 'DB_PORT': '5432', 'DB_USERNAME': 'dify',
'DB_PASSWORD': os.environ['DIFY_DB_PASSWORD'], 'DB_DATABASE': 'dify',
'SQLALCHEMY_POOL_SIZE': '3', 'SQLALCHEMY_MAX_OVERFLOW': '2',
'REDIS_HOST': '127.0.0.1', 'REDIS_PORT': '6379', 'REDIS_PASSWORD': os.environ['DIFY_REDIS_PASSWORD'],
'CELERY_BROKER_URL': 'redis://:' + os.environ['DIFY_REDIS_PASSWORD'] + '@127.0.0.1:6379/1',
'STORAGE_TYPE': 'opendal', 'OPENDAL_SCHEME': 'fs', 'OPENDAL_FS_ROOT': '/state/files',
'VECTOR_STORE': 'pgvector', 'PGVECTOR_HOST': '127.0.0.1', 'PGVECTOR_PORT': '5432',
'PGVECTOR_USER': 'dify', 'PGVECTOR_PASSWORD': os.environ['DIFY_DB_PASSWORD'],
'PGVECTOR_DATABASE': 'dify_vector', 'PGVECTOR_MIN_CONNECTION': '1', 'PGVECTOR_MAX_CONNECTION': '3',
'PGVECTOR_PG_BIGM': 'false', 'DIFY_BIND_ADDRESS': '127.0.0.1', 'DIFY_PORT': '5001',
'SERVER_WORKER_AMOUNT': '1', 'SERVER_WORKER_CONNECTIONS': '50', 'CELERY_WORKER_AMOUNT': '1',
'PLUGIN_DAEMON_URL': 'http://127.0.0.1:5002', 'PLUGIN_DAEMON_KEY': os.environ['DIFY_PLUGIN_KEY'],
'INNER_API_KEY_FOR_PLUGIN': os.environ['DIFY_INNER_KEY'],
'CODE_EXECUTION_ENDPOINT': 'http://127.0.0.1:8194', 'CODE_EXECUTION_API_KEY': os.environ['DIFY_SANDBOX_KEY'],
'SSRF_PROXY_HTTP_URL': 'http://127.0.0.1:3128', 'SSRF_PROXY_HTTPS_URL': 'http://127.0.0.1:3128',
'CHECK_UPDATE_URL': '', 'ENABLE_AGENT_V2': 'false', 'MIGRATION_ENABLED': 'false',
'LOG_LEVEL': 'WARNING', 'GUNICORN_TIMEOUT': '360', 'NEXT_TELEMETRY_DISABLED': '1',
'MARKETPLACE_ENABLED': 'true', 'MARKETPLACE_API_URL': 'https://marketplace.dify.ai', 'MARKETPLACE_URL': 'https://marketplace.dify.ai',
})
plugin_env = dict(BASE_ENV)
plugin_env.update({k: config[k] for k in ('DB_HOST','DB_PORT','DB_USERNAME','DB_PASSWORD','REDIS_HOST','REDIS_PORT','REDIS_PASSWORD')})
plugin_env.update({'DB_DATABASE': 'dify_plugin', 'DB_SSL_MODE': 'disable', 'DB_TYPE': 'postgresql',
'SERVER_HOST': '127.0.0.1', 'SERVER_PORT': '5002', 'SERVER_KEY': os.environ['DIFY_PLUGIN_KEY'],
'DIFY_INNER_API_URL': 'http://127.0.0.1:5001', 'DIFY_INNER_API_KEY': os.environ['DIFY_INNER_KEY'],
'PLUGIN_WORKING_PATH': '/state/plugin/cwd', 'PLUGIN_STORAGE_TYPE': 'local', 'PLUGIN_STORAGE_LOCAL_ROOT': '/state/plugin',
'PLUGIN_INSTALLED_PATH': 'plugin', 'PLUGIN_PACKAGE_CACHE_PATH': 'plugin_packages', 'PLUGIN_MEDIA_CACHE_PATH': 'assets',
'PLUGIN_REMOTE_INSTALLING_HOST': '127.0.0.1', 'PLUGIN_REMOTE_INSTALLING_PORT': '5003',
'FORCE_VERIFYING_SIGNATURE': 'true', 'PYTHON_ENV_INIT_TIMEOUT': '600', 'PLUGIN_MAX_EXECUTION_TIMEOUT': '600',
'PYTHON_INTERPRETER_PATH': '/usr/local/bin/python3', 'UV_CACHE_DIR': '/state/plugin/uv-cache',
})
web_env = dict(BASE_ENV)
web_env.update({k:v for k,v in config.items() if k in ('DEPLOY_ENV','CONSOLE_API_URL','CONSOLE_WEB_URL','APP_API_URL','APP_WEB_URL','ENABLE_AGENT_V2','MARKETPLACE_API_URL','MARKETPLACE_URL','NEXT_TELEMETRY_DISABLED')})
web_env.update({'PORT': '3000', 'HOSTNAME': '127.0.0.1', 'NODE_ENV': 'production'})
def start_apps():
for name in SERVICES:
start(name, ['/opt/hf-dify/run-service.sh', name], plugin_env if name == 'plugin' else config, 1000)
wait_http('http://127.0.0.1:5001/health')
store = None
ready = False
try:
STATE.mkdir(exist_ok=True)
MAINT.parent.mkdir(parents=True, exist_ok=True)
MAINT.touch()
store = Store()
if not (STATE / 'postgres/PG_VERSION').exists():
store.restore()
for name in ('files', 'plugin', 'redis'):
path = STATE / name
path.mkdir(exist_ok=True)
subprocess.run(['chown', '-R', '1000:1000', str(path)], check=True)
pg_uid = pwd.getpwnam('postgres').pw_uid
pgdir = STATE / 'postgres'
pgdir.mkdir(exist_ok=True)
os.chown(pgdir, pg_uid, pg_uid)
os.chmod(pgdir, 0o700)
Path('/run/postgresql').mkdir(exist_ok=True)
os.chown('/run/postgresql', pg_uid, pg_uid)
if not (pgdir / 'PG_VERSION').exists():
subprocess.run(['runuser','-u','postgres','--','/usr/lib/postgresql/15/bin/initdb','-D',str(pgdir),'--auth-local=peer','--auth-host=scram-sha-256'], check=True, stdout=subprocess.DEVNULL)
start('postgres', ['/usr/lib/postgresql/15/bin/postgres', '-D', str(pgdir), '-c', 'listen_addresses=127.0.0.1', '-c', 'max_connections=100', '-c', 'shared_buffers=128MB'], uid=pg_uid)
for _ in range(60):
if subprocess.run(['pg_isready','-q'], stdout=subprocess.DEVNULL).returncode == 0:
break
time.sleep(1)
else:
raise RuntimeError('PostgreSQL did not become ready')
def sql(statement, db='postgres'):
return subprocess.run(['runuser','-u','postgres','--','psql','-v','ON_ERROR_STOP=1','-At',db],input=statement,text=True,capture_output=True,check=True).stdout.strip()
if sql("SELECT count(*) FROM pg_roles WHERE rolname='dify'") == '0':
sql("CREATE ROLE dify LOGIN PASSWORD '" + os.environ['DIFY_DB_PASSWORD'] + "'")
else:
sql("ALTER ROLE dify PASSWORD '" + os.environ['DIFY_DB_PASSWORD'] + "'")
for db in ('dify','dify_plugin','dify_vector'):
if sql("SELECT count(*) FROM pg_database WHERE datname='" + db + "'") == '0':
sql('CREATE DATABASE ' + db + ' OWNER dify')
sql('CREATE EXTENSION IF NOT EXISTS vector', db)
dump = STATE / 'db' / (db + '.dump')
if dump.exists():
os.chmod(STATE / 'db', 0o755)
os.chmod(dump, 0o644)
listing = subprocess.check_output(['pg_restore', '-l', str(dump)], text=True)
items = STATE / 'db' / (db + '.list')
items.write_text('\n'.join(line for line in listing.splitlines() if ' EXTENSION ' not in line) + '\n')
os.chmod(items, 0o644)
subprocess.run(['runuser','-u','postgres','--','pg_restore','--exit-on-error','--no-owner','--no-acl','--role=dify','-L',str(items),'-d',db,str(dump)],check=True)
dump.unlink()
redis_conf = Path('/run/hf-dify/redis.conf')
redis_conf.write_text('bind 127.0.0.1\nport 6379\nprotected-mode yes\ndir /state/redis\nappendonly no\nsave 60 1\nrequirepass ' + os.environ['DIFY_REDIS_PASSWORD'] + '\n')
os.chown(redis_conf,1000,1000)
os.chmod(redis_conf,0o600)
start('redis',['redis-server',str(redis_conf)],uid=1000)
# Preserve the official sandbox rootfs, Python ABI and seccomp runner.
sandbox_root = Path('/opt/dify-sandbox')
for device,minor in (('null',3),('zero',5),('random',8),('urandom',9)):
path = sandbox_root/'dev'/device
path.parent.mkdir(exist_ok=True)
if not path.exists():
subprocess.run(['mknod',str(path),'c','1',str(minor)],check=True)
os.chmod(path,0o666)
cfg = sandbox_root/'conf/config.yaml'
cfg.write_text('app:\n port: 8194\n debug: false\n key: '+os.environ['DIFY_SANDBOX_KEY']+'\nmax_workers: 2\nmax_requests: 50\nworker_timeout: 15\npython_path: /opt/python/bin/python3\nenable_network: false\nenable_preload: false\nlog_path: /tmp/logs\nallowed_syscalls: []\nproxy:\n socks5: ""\n http: ""\n https: ""\n')
start('sandbox',['chroot',str(sandbox_root),'/main'],BASE_ENV,cwd='/')
start('proxy',['/usr/sbin/squid','-N','-f','/opt/hf-dify/squid.conf'],cwd='/')
subprocess.run(['/entrypoint.sh'],env={**config,'MODE':'migration','MIGRATION_ENABLED':'true'},cwd='/app/api',user=1000,group=1000,extra_groups=[],check=True)
start_apps()
setup = request('http://127.0.0.1:5001/console/api/setup')
if setup['step'] == 'not_started':
request('http://127.0.0.1:5001/console/api/setup', {'email':os.environ['DIFY_ADMIN_EMAIL'],'name':'HF Admin','password':os.environ['DIFY_ADMIN_PASSWORD'],'language':'zh-Hans'})
log('administrator initialized before opening public port')
stop(SERVICES)
store.backup()
start_apps()
start('web',['/opt/hf-dify/run-service.sh','web'],web_env,1000)
start('nginx',['/usr/sbin/nginx','-c','/opt/hf-dify/nginx.conf','-g','daemon off;'],cwd='/')
MAINT.unlink(missing_ok=True)
ready = True
log('READY Dify 1.18.0 with verified snapshot store')
due = time.monotonic() + max(60,int(os.environ.get('BACKUP_INTERVAL_SECONDS','300')))
while not STOP:
for name,proc in PROCS.items():
if proc.poll() is not None:
raise RuntimeError(name+' exited '+str(proc.returncode))
if BACKUP or time.monotonic() >= due:
BACKUP = False
MAINT.touch()
stop(SERVICES)
try:
store.backup()
except Exception as exc:
log('BACKUP FAILED (previous complete snapshot retained): '+type(exc).__name__+': '+str(exc))
start_apps()
MAINT.unlink(missing_ok=True)
due = time.monotonic() + max(60,int(os.environ.get('BACKUP_INTERVAL_SECONDS','300')))
time.sleep(1)
finally:
MAINT.touch()
stop(SERVICES)
if ready and store:
try:
store.backup()
except Exception as exc:
log('shutdown backup failed: '+type(exc).__name__+': '+str(exc))
stop(list(PROCS))