diff --git a/AGENTS.md b/AGENTS.md index d0572ce..9802490 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,5 @@ - Use the Dokploy project/environment and service deployment pages for the current branch, not another person's environment. - Verify the relevant service deployment is `Done` for the pushed commit hash. If both backend and frontend changed, verify both. If only frontend changed, still verify the branch deployment URL serves the new frontend asset after Dokploy finishes. - Use Chrome for production verification on the branch deployment URL after Dokploy is done. - - For the `sky` branch, the Dokploy links are: - - Project/environment: `https://dokploy.observe.tw/dashboard/project/eBpy0zdwgD7qwalkeefAd/environment/DcsSA4yUGTALixthLZ0v4` - - Backend compose deployments: `https://dokploy.observe.tw/dashboard/project/eBpy0zdwgD7qwalkeefAd/environment/DcsSA4yUGTALixthLZ0v4/services/compose/aUjeHZM855eQ9jlgG56_0?tab=deployments` - - Frontend compose deployments: `https://dokploy.observe.tw/dashboard/project/eBpy0zdwgD7qwalkeefAd/environment/DcsSA4yUGTALixthLZ0v4/services/compose/nj1X_yllF5Z_cPbU6CJWp?tab=deployments` + - Current IIC environments and deployment links are listed in [deploy/README.md](deploy/README.md). Each environment uses one Compose deployment for backend and frontend. + - Production is `main` at `https://omni.observe.tw/`; `em-prompt` deploys to `https://em.omni.observe.tw/`. diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..eeefddd --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,44 @@ +# IIC CPU deployment + +The host CD service checks configured Git branches every 30 seconds and asks +Dokploy to clone the changed branch and build deploy/compose.cpu.yml. GitHub +webhook delivery cannot reach the IIC host, so delivery does not depend on inbound +webhooks. Use main for production; sky, ej, ethel, jason, and em-prompt +for their matching development environments (em-prompt uses the em hostname). + +Set OMNI_POSTGRES_VOLUME to the existing environment-specific database volume. +The volume and omniobserve-embeddings network must already exist. Database +credentials and LLM settings stay in Dokploy environment settings. Do not commit +secrets or change volume names when redeploying existing data. + +Frontend public URLs are VITE_API_BASE_URL, VITE_WS_BASE_URL, +VITE_AUDIO_WS_BASE_URL and VITE_JITSI_BASE_URL in Dokploy. They are build arguments; +redeploy after changing them. Without build arguments, the normal frontend +Dockerfile continues to use its existing Vite configuration. + +The shared CPU embedding service is managed separately in infrastructure. +GPU ASR and Jitsi are not part of this CPU Compose file. + +## Environments + +| Branch | Site | Dokploy | +| --- | --- | --- | +| sky | https://sky.omni.observe.tw | [Deployments](https://dokploy.observe.tw/dashboard/project/4XAzxpFxB6VEErRHqWDr0/environment/qA8mx7xjiAv3Ti1Qc8SFb/services/compose/5IHPHhil26L4hiXNrCAaw?tab=deployments) | +| main | https://omni.observe.tw | [Deployments](https://dokploy.observe.tw/dashboard/project/4XAzxpFxB6VEErRHqWDr0/environment/waDEpmtDbwTvSUTYGZSHY/services/compose/XEaczm-V5IwvpnEPa1VZ1?tab=deployments) | +| ej | https://ej.omni.observe.tw | [Deployments](https://dokploy.observe.tw/dashboard/project/4XAzxpFxB6VEErRHqWDr0/environment/fh12whx2Ap4VWOJc-kx7E/services/compose/DBVEbmg3tC4HIKBO2_iVh?tab=deployments) | +| ethel | https://ethel.omni.observe.tw | [Deployments](https://dokploy.observe.tw/dashboard/project/4XAzxpFxB6VEErRHqWDr0/environment/Yt5l_znYlq4QQoxOHI5DB/services/compose/vQd0bkC8v25N2j2wVi3QE?tab=deployments) | +| jason | https://jason.omni.observe.tw | [Deployments](https://dokploy.observe.tw/dashboard/project/4XAzxpFxB6VEErRHqWDr0/environment/3a5DwBCjH3KxBGprjlmqH/services/compose/Q-sYCuFfUZB-FO0cIITvB?tab=deployments) | +| em-prompt | https://em.omni.observe.tw | [Deployments](https://dokploy.observe.tw/dashboard/project/4XAzxpFxB6VEErRHqWDr0/environment/6LXUM3fGRhsRUO0Mw8Mvm/services/compose/W7GffAxu3Gz8Aw08tA_LC?tab=deployments) | + +## CD service + +The installed systemd service is omniobserve-cd.service. It runs cd-poller.py +with a private config at /home/ubuntu/omniobserve-cd/config.json. The project-scoped +API key and state file are not committed. Inspect progress using +`journalctl -u omniobserve-cd.service`; pause automatic deploys for one environment +with its Dokploy Autodeploy switch. Failed commits retry at most three times with +a five-minute delay. Successful deployment requires frontend/API HTTPS checks. + +Run `python3 deploy/test_cd_poller.py` for polling and retry behavior tests. +The host-installed poller is upgraded explicitly; application pushes do not +replace the systemd service or private configuration. diff --git a/deploy/cd-poller.py b/deploy/cd-poller.py new file mode 100644 index 0000000..b011a7e --- /dev/null +++ b/deploy/cd-poller.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Pull-based Dokploy CD for hosts that cannot receive GitHub webhooks.""" +import argparse +import datetime +import re +import json +import os +import pathlib +import subprocess +import time +import urllib.parse +import urllib.request + + +def api(config, method, data=None): + url = config['api_url'] + '/' + method + headers = {'x-api-key': config['api_key'], 'Content-Type': 'application/json'} + if method.endswith('.one'): + url += '?' + urllib.parse.urlencode(data or {}) + body = None + else: + body = json.dumps(data or {}).encode() + with urllib.request.urlopen(urllib.request.Request(url, data=body, headers=headers), timeout=30) as response: + return json.load(response) + + +def save(path, state): + temp = path.with_suffix('.tmp') + temp.write_text(json.dumps(state, indent=2)) + temp.chmod(0o600) + os.replace(temp, path) + + +def log(message): + print(time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), message, flush=True) + + +def healthy(target): + for host, path in [(target['frontend'], '/'), (target['backend'], '/health')]: + result = subprocess.run(['curl', '--fail', '--silent', '--show-error', '--max-time', '15', '--resolve', host + ':443:127.0.0.1', 'https://' + host + path], capture_output=True) + if result.returncode: + return False + return True + + +def tick(config, state, state_path): + targets = config['targets'] + refs = subprocess.check_output(['git', 'ls-remote', config['repository']] + ['refs/heads/' + t['branch'] for t in targets], timeout=45, env={**os.environ, 'GIT_TERMINAL_PROMPT': '0'}).decode() + remote = {ref.removeprefix('refs/heads/'): sha for sha, ref in (line.split() for line in refs.splitlines())} + statuses = {t['branch']: api(config, 'compose.one', {'composeId': t['compose_id']}) for t in targets} + active = False + now = time.time() + for target in targets: + branch = target['branch'] + info = statuses[branch] + entry = state.setdefault(branch, {'deployed': target['initial_commit']}) + pending = entry.get('pending') + if pending: + deployments = sorted(info.get('deployments') or [], key=lambda d: d.get('createdAt', ''), reverse=True) + deployment = next((d for d in deployments if d.get('title') == pending['title'] or pending['sha'] in (d.get('description') or '') or (d.get('createdAt') and datetime.datetime.fromisoformat(d['createdAt'].replace('Z', '+00:00')).timestamp() >= pending['queued_at'])), None) + if deployment and deployment.get('status') == 'done': + if healthy(target): + actual = re.search(r'Commit: ([0-9a-f]{40})', deployment.get('description') or '') + entry['deployed'] = actual.group(1) if actual else pending['sha'] + entry.pop('pending') + entry.pop('failure', None) + log('deployed ' + branch + ' ' + pending['sha']) + elif now - pending['queued_at'] > 900: + entry['failure'] = {'sha': pending['sha'], 'at': now, 'attempts': pending['attempts']} + entry.pop('pending') + log('health check failed ' + branch + ' ' + pending['sha']) + else: + active = True + elif deployment and deployment.get('status') == 'error': + entry['failure'] = {'sha': pending['sha'], 'at': now, 'attempts': pending['attempts']} + entry.pop('pending') + log('deployment failed ' + branch + ' ' + pending['sha']) + elif now - pending['queued_at'] > 1800 and info.get('composeStatus') != 'running': + entry['failure'] = {'sha': pending['sha'], 'at': now, 'attempts': pending['attempts']} + entry.pop('pending') + log('deployment did not complete ' + branch) + else: + active = True + if info.get('composeStatus') == 'running': + active = True + save(state_path, state) + if active: + return + for target in targets: + branch = target['branch'] + info = statuses[branch] + sha = remote.get(branch) + entry = state[branch] + if not sha or sha == entry.get('deployed') or not info.get('autoDeploy'): + continue + failure = entry.get('failure', {}) + attempts = failure.get('attempts', 0) if failure.get('sha') == sha else 0 + if attempts >= 3 or (attempts and now - failure['at'] < 300): + continue + title = 'CD ' + branch + ' ' + sha + api(config, 'compose.deploy', {'composeId': target['compose_id'], 'title': title, 'description': 'Automatic Git branch update. Commit: ' + sha}) + entry['pending'] = {'sha': sha, 'title': title, 'queued_at': now, 'attempts': attempts + 1} + save(state_path, state) + log('queued ' + branch + ' ' + sha) + break + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--config', required=True) + parser.add_argument('--once', action='store_true') + args = parser.parse_args() + config_path = pathlib.Path(args.config) + config = json.loads(config_path.read_text()) + state_path = pathlib.Path(config['state_file']) + state = json.loads(state_path.read_text()) if state_path.exists() else {} + while True: + try: + tick(config, state, state_path) + except Exception as error: + # Do not log HTTP headers, response bodies, config, or credentials. + log('poll failed: ' + type(error).__name__) + if args.once: + raise SystemExit(1) + if args.once: + return + time.sleep(config.get('interval_seconds', 30)) + + +if __name__ == '__main__': + main() diff --git a/deploy/compose.cpu.yml b/deploy/compose.cpu.yml new file mode 100644 index 0000000..ce58243 --- /dev/null +++ b/deploy/compose.cpu.yml @@ -0,0 +1,66 @@ +services: + db: + image: pgvector/pgvector:pg16 + restart: unless-stopped + environment: + POSTGRES_DB: ${POSTGRES_DB:-omniobserve} + POSTGRES_USER: ${POSTGRES_USER:-postgres} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in bootstrap.env} + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: + - CMD-SHELL + - pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-omniobserve} + interval: 10s + timeout: 5s + retries: 5 + backend: + restart: unless-stopped + depends_on: + db: + condition: service_healthy + environment: + DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:?Set + POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB:-omniobserve} + OPENAI_API_KEY: ${OPENAI_API_KEY:-} + OPENAI_BASE_URL: ${OPENAI_BASE_URL:-https://opencode.ai/zen/go/v1} + OPENAI_MODEL: ${OPENAI_MODEL:-qwen3.6-plus} + OLLAMA_BASE_URL: http://embedding-cpu:11434 + OLLAMA_EMBED_MODEL: ${OLLAMA_EMBED_MODEL:-bge-m3} + LLM_MOCK: ${LLM_MOCK:-0} + CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost:8080} + CORS_ALLOW_CREDENTIALS: ${CORS_ALLOW_CREDENTIALS:-0} + expose: + - '8000' + healthcheck: + test: + - CMD + - python + - -c + - import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health') + interval: 15s + timeout: 5s + retries: 5 + networks: + - default + - embeddings + build: + context: ../backend + frontend: + restart: unless-stopped + build: + context: ../frontend + args: + VITE_API_BASE_URL: ${VITE_API_BASE_URL:?Set VITE_API_BASE_URL} + VITE_WS_BASE_URL: ${VITE_WS_BASE_URL:?Set VITE_WS_BASE_URL} + VITE_AUDIO_WS_BASE_URL: ${VITE_AUDIO_WS_BASE_URL:?Set VITE_AUDIO_WS_BASE_URL} + VITE_JITSI_BASE_URL: ${VITE_JITSI_BASE_URL:?Set VITE_JITSI_BASE_URL} +volumes: + postgres_data: + external: true + name: ${OMNI_POSTGRES_VOLUME:?Set OMNI_POSTGRES_VOLUME} +networks: + embeddings: + external: true + name: omniobserve-embeddings diff --git a/deploy/omniobserve-cd.service b/deploy/omniobserve-cd.service new file mode 100644 index 0000000..6157ec8 --- /dev/null +++ b/deploy/omniobserve-cd.service @@ -0,0 +1,22 @@ +[Unit] +Description=OmniObserve branch continuous deployment +After=network-online.target docker.service +Wants=network-online.target + +[Service] +Type=simple +User=ubuntu +Group=ubuntu +WorkingDirectory=/home/ubuntu/omniobserve-cd +ExecStart=/usr/bin/python3 /home/ubuntu/omniobserve-cd/cd-poller.py --config /home/ubuntu/omniobserve-cd/config.json +Restart=on-failure +RestartSec=10 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths=/home/ubuntu/omniobserve-cd + +[Install] +WantedBy=multi-user.target diff --git a/deploy/test_cd_poller.py b/deploy/test_cd_poller.py new file mode 100644 index 0000000..d2c9507 --- /dev/null +++ b/deploy/test_cd_poller.py @@ -0,0 +1,39 @@ +import importlib.util +import pathlib +import tempfile +import unittest +from unittest.mock import patch +spec=importlib.util.spec_from_file_location('poller',pathlib.Path(__file__).with_name('cd-poller.py')) +m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) + +class PollerTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.path=pathlib.Path(self.tmp.name)/'state.json' + self.target={'branch':'sky','compose_id':'sky-service','initial_commit':'old','frontend':'sky.test','backend':'api.sky.test'} + self.config={'repository':'https://example.test/repo.git','targets':[self.target]} + self.info={'composeStatus':'done','autoDeploy':True,'deployments':[]};self.calls=[] + def tearDown(self):self.tmp.cleanup() + def run_tick(self,state,remote='new'): + def api(config,method,data): + if method=='compose.one':return self.info + self.calls.append(data);return {'success':True} + with patch.object(m.subprocess,'check_output',return_value=(remote+'\trefs/heads/sky\n').encode()),patch.object(m,'api',side_effect=api),patch.object(m,'healthy',return_value=True),patch.object(m,'log'): + m.tick(self.config,state,self.path) + def test_new_commit_queues_only_matching_service(self): + state={};self.run_tick(state);self.assertEqual(self.calls[0]['composeId'],'sky-service');self.assertEqual(state['sky']['pending']['sha'],'new') + def test_disabled_auto_deploy_is_respected(self): + self.info['autoDeploy']=False;self.run_tick({});self.assertEqual(self.calls,[]) + def test_pending_job_is_not_queued_twice(self): + state={'sky':{'deployed':'old','pending':{'sha':'new','title':'CD sky new','queued_at':m.time.time(),'attempts':1}}};self.run_tick(state);self.assertEqual(self.calls,[]) + def test_completed_job_is_recorded_after_health(self): + state={'sky':{'deployed':'old','pending':{'sha':'new','title':'CD sky new','queued_at':m.time.time(),'attempts':1}}};self.info['deployments']=[{'title':'CD sky new','status':'done'}];self.run_tick(state);self.assertEqual(state['sky']['deployed'],'new');self.assertNotIn('pending',state['sky']);self.assertEqual(self.calls,[]) + def test_native_git_commit_metadata_is_recognized(self): + state={'sky':{'deployed':'old','pending':{'sha':'new','title':'CD sky new','queued_at':m.time.time(),'attempts':1}}} + self.info['deployments']=[{'title':'Git commit message replaces job title','description':'Commit: new','status':'done'}] + self.run_tick(state);self.assertEqual(state['sky']['deployed'],'new');self.assertNotIn('pending',state['sky']) + def test_failed_commit_stops_after_three_attempts(self): + state={'sky':{'deployed':'old','failure':{'sha':'new','at':0,'attempts':3}}};self.run_tick(state);self.assertEqual(self.calls,[]) + def test_new_commit_can_recover_after_previous_failure(self): + state={'sky':{'deployed':'old','failure':{'sha':'failed','at':0,'attempts':3}}};self.run_tick(state);self.assertEqual(len(self.calls),1) + +if __name__=='__main__':unittest.main() diff --git a/frontend/Dockerfile b/frontend/Dockerfile index d3a31e0..3e30351 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -6,6 +6,10 @@ COPY package.json pnpm-lock.yaml ./ RUN corepack enable && pnpm install --frozen-lockfile COPY . . +ARG VITE_API_BASE_URL +ARG VITE_WS_BASE_URL +ARG VITE_AUDIO_WS_BASE_URL +ARG VITE_JITSI_BASE_URL RUN pnpm build