feat: create external service gateway implementation for bad gateway fix
ci / smoke (push) Canceled after 0s

This commit is contained in:
openhands committed 2026-10-19 09:26:46 +07:00
1 parent 721786057f
commit ecc5edab89
5 files changed
+1268 -291

No files matched your search

@@ -1,291 +0,0 @@
# Rencana Implementasi: Migrasi Livestream & Ingestion ke Pola ZenAI KPC
> **Untuk Pekerja Agentic:** SUB-SKILL YANG DIBUTUHKAN: Gunakan `superpowers:subagent-driven-development` (direkomendasikan) atau `superpowers:executing-plans` untuk mengimplementasikan rencana ini tugas demi tugas. Setiap langkah menggunakan checkbox (`- [ ]`) untuk pelacakan.
**Goal:** Mengubah arsitektur livestream web dan capture RTSP pada project Feedmill Karung Counter agar mengadopsi mekanisme yang digunakan pada project ZenAI KPC (OpenCV FFmpeg capture langsung di loop utama, konfigurasi seragam `LIVE_STREAM_ENABLED/QUALITY/EVERY_N`, penulisan atomic frame berkala tanpa dependensi `viewers.json`, dan UI kontrol tombol toggle "STREAM ON / STREAM OFF").
**Architecture:**
1. **Input Ingestion**: Mengganti `RTSPStreamReader` (GStreamer NVDEC background thread) dengan fungsi `open_capture` & `connect_stream` berbasis OpenCV FFmpeg capture sinkron di main loop dengan opsi buffer low-delay dan watchdog `StreamErrorLog` anti-spam log saat kamera terputus.
2. **Output Stream / Live JPEG**: Mengganti adaptive viewer-sensing (`viewers.json` dan dual-tier 480p/720p) di `predict.py` dengan penulisan berkala per N-frame (`LIVE_STREAM_EVERY_N`) berkualitas seragam (`LIVE_STREAM_QUALITY`) jika `LIVE_STREAM_ENABLED=True`.
3. **Dashboard Serving & UI**: Menyederhanakan endpoint `/api/live-video` di `counter_dashboard.py` menjadi pembacaan langsung frame SHM murni (tanpa tracking penonton), serta mengadaptasi UI di `monitoring.html` dengan tombol toggle eksplisit "STREAM ON / STREAM OFF".
**Tech Stack:** Python 3.10+, OpenCV (`cv2`), Flask, HTML5/Vanilla JS.
---
## Global Constraints
- Konfigurasi kanonik tetap berpusat di `config.yaml` dan dapat dioverride melalui environment variable `.env`.
- Semua penulisan file ke shared memory RAM-disk (`/dev/shm`) harus tetap atomik (tulis ke `.tmp` lalu `os.replace`) untuk mencegah *torn read* / gambar rusak.
- Jangan mengubah format database SQLite, tabel `batches`, atau logika deteksi/tracking karung dan truk.
- Menjaga kompatibilitas CLI `predict.py` (dukungan mode CLI dan mode service tanpa argumen).
## Review Focus
1. **RTSP Reconnection Loop**: Saat koneksi CCTV terputus di tengah jalan, proses counter tidak boleh crash dan harus mencoba reconnect secara berkala tanpa membanjiri log file (`StreamErrorLog` rate limiting).
2. **Atomic Write & Torn Read**: Browser tidak boleh menerima frame JPEG setengah jadi (*corrupted image*), dipastikan dengan atomic rename dan validasi header SOI JPEG (`0xFF 0xD8`).
3. **Resource Consumption saat Stream OFF**: Saat `LIVE_STREAM_ENABLED=false` atau saat tombol UI dimatikan di browser, tidak boleh terjadi pemborosan resource CPU untuk encode JPEG maupun bandwidth HTTP.
4. **Local Video File Fallback**: Jika argumen `--source` berupa file video lokal (`.mp4`), capture tidak boleh crash karena opsi RTSP FFmpeg.
5. **Fresh Boot / Dev-shm Missing**: Jika folder `/dev/shm/jetson-counter` belum ada saat boot, sistem harus otomatis membuat folder tersebut (`os.makedirs`).
---
## Task Decomposition
### Task 1: Konfigurasi Livestream & Stream Error Logger
**Files:**
- Modify: `config.yaml:12-16`, `config.yaml:142-152`
- Modify: `src/config_loader.py`
- Create: `tests/test_livestream_config.py`
- [ ] **Langkah 1.1: Tulis unit test untuk konfigurasi baru**
Buat `tests/test_livestream_config.py` yang memvalidasi bahwa `config_loader` membaca nilai `stream.live_stream.enabled`, `stream.live_stream.quality`, `stream.live_stream.every_n`, dan `stream.rtsp_options`, serta mendukung fallback env variable `LIVE_STREAM_ENABLED`, `LIVE_STREAM_QUALITY`, `LIVE_STREAM_EVERY_N`, `OPENCV_FFMPEG_CAPTURE_OPTIONS`.
- [ ] **Langkah 1.2: Jalankan test dan pastikan gagal**
Jalankan `python -m pytest tests/test_livestream_config.py -v`.
- [ ] **Langkah 1.3: Update `config.yaml` dan `src/config_loader.py`**
- Tambahkan section `stream.live_stream` di `config.yaml`:
```yaml
stream:
resolution: [1280, 720]
inference_stride: 2
rtsp_options: "rtsp_transport;tcp|fflags;nobuffer|flags;low_delay"
live_stream:
enabled: true
quality: 75
every_n: 2
```
- Perbarui dataclass di `src/config_loader.py` untuk memuat parameter tersebut.
- [ ] **Langkah 1.4: Jalankan test dan pastikan lulus**
Jalankan `python -m pytest tests/test_livestream_config.py -v`.
---
### Task 2: Modifikasi Input Ingestion di `predict.py` (Pola OpenCV FFmpeg ZenAI)
**Files:**
- Modify: `predict.py:900-1035`, `predict.py:1470-1500`, `predict.py:1550-1600`
- Create: `tests/test_stream_error_log.py`
- [ ] **Langkah 2.1: Tulis unit test untuk `StreamErrorLog`**
Buat `tests/test_stream_error_log.py` untuk menguji class pembatas log error (maksimum N log saat koneksi drop, hening saat berulang kali gagal, dan reset saat koneksi pulih).
- [ ] **Langkah 2.2: Implementasikan `StreamErrorLog`, `open_capture`, dan `connect_stream` di `predict.py`**
- Tambahkan implementasi lengkap berikut di `predict.py`:
```python
class StreamErrorLog:
"""Rate-limit stream error prints per outage to prevent log spam."""
def __init__(self, max_logs=3):
self.max_logs = int(max_logs)
self._emitted = 0
self._suppressed = 0
def emit(self, msg: str) -> None:
if self.max_logs <= 0:
print(msg)
return
if self._emitted < self.max_logs:
self._emitted += 1
print(msg)
if self._emitted >= self.max_logs:
print(f"[STREAM] Stream errors capped at {self.max_logs} this outage — further messages suppressed until stream recovers")
else:
self._suppressed += 1
def note_up(self) -> None:
if self._suppressed > 0:
print(f"[STREAM] Stream recovered (suppressed {self._suppressed} error log(s) during outage)")
self._emitted = 0
self._suppressed = 0
stream_error_log = StreamErrorLog(max_logs=3)
def open_capture(source):
if str(source).lower().startswith(("rtsp://", "http://", "https://")):
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = RTSP_FFMPEG_OPTIONS
cap = cv2.VideoCapture(source, cv2.CAP_FFMPEG)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
return cap
def connect_stream(source, reconnect_delay=3):
while True:
cap = open_capture(source)
if not cap.isOpened():
stream_error_log.emit(f"[STREAM] Cannot open source, retry in {reconnect_delay}s: {source}")
time.sleep(reconnect_delay)
continue
stream_error_log.note_up()
return cap
```
- Hapus class `RTSPStreamReader` dan thread background-nya.
- [ ] **Langkah 2.3: Perbarui loop utama inferensi di `predict.py`**
- Ganti pembacaan asynchronous `cap.read()` ke capture langsung sinkron di awal loop:
```python
ret, frame = cap.read()
if not ret:
if not is_stream:
break
# Logic reconnect ala ZenAI
cap.release()
time.sleep(reconnect_delay)
cap = connect_stream(source_path)
continue
```
- [ ] **Langkah 2.4: Verifikasi test suite**
Jalankan `python -m pytest tests/test_stream_error_log.py -v`.
---
### Task 3: Modifikasi Output Livestreaming di `predict.py` (Pola ZenAI KPC)
**Files:**
- Modify: `predict.py:410-440`, `predict.py:1800-1850`
- Create: `tests/test_live_writer.py`
- [ ] **Langkah 3.1: Tulis unit test untuk fungsi penulisan live frame**
Buat `tests/test_live_writer.py` yang memvalidasi bahwa frame ditulis hanya pada setiap `frame_idx % every_n == 0` dan ditulis atomik (melalui file `.tmp` lalu `os.replace`).
- [ ] **Langkah 3.2: Refactor `write_live_frame` di `predict.py`**
- Ganti implementasi `write_live_frame`:
- Hapus ketergantungan membaca `viewers.json`.
- Hapus pembuatan file resolusi ganda (`live_frame_480.jpg` dan `live_frame.jpg`).
- Gunakan penulisan langsung menggunakan `cv2.imencode`:
```python
def write_live_frame(frame, frame_idx):
if not LIVE_STREAM_ENABLED or (frame_idx % LIVE_STREAM_EVERY_N != 0):
return
try:
os.makedirs(os.path.dirname(LIVE_STREAM_FRAME_PATH), exist_ok=True)
ok, jpeg = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, LIVE_STREAM_QUALITY])
if ok:
tmp_path = f"{LIVE_STREAM_FRAME_PATH}.tmp"
with open(tmp_path, "wb") as f:
f.write(jpeg.tobytes())
os.replace(tmp_path, LIVE_STREAM_FRAME_PATH)
except Exception as e:
pass
```
- Panggil `write_live_frame(annotated_frame, frame_idx)` di akhir setiap iterasi frame.
- [ ] **Langkah 3.3: Jalankan test dan pastikan lulus**
Jalankan `python -m pytest tests/test_live_writer.py -v`.
---
### Task 4: Penyederhanaan Dashboard Server (`counter_dashboard.py`)
**Files:**
- Modify: `counter_dashboard.py:99-179`
- Create: `tests/test_dashboard_stream_zenai.py`
- [ ] **Langkah 4.1: Tulis test untuk endpoint `/api/live-video`**
Buat `tests/test_dashboard_stream_zenai.py` untuk memverifikasi streaming MJPEG tanpa dependensi `viewers.json`, dengan penanganan header SOI `\xff\xd8`.
- [ ] **Langkah 4.2: Bersihkan logic viewers di `counter_dashboard.py`**
- Hapus variabel `_VIEWERS_PATH`, `_VIEWERS_LOCK`, `_viewers`, dan fungsi `_viewers_write()`.
- Hapus pengecekan `?full=1` dan fallback `_preview`.
- Sederhanakan fungsi `api_live_video()` agar langsung mengalirkan frame:
```python
@app.route("/api/live-video")
def api_live_video():
if not os.path.isfile(LIVE_STREAM_FRAME_PATH):
return jsonify({"success": False, "error": "Live stream frame not available yet"}), 503
def generate():
consecutive_fails = 0
MAX_FAILS = 30
while True:
try:
with open(LIVE_STREAM_FRAME_PATH, "rb") as f:
jpeg = f.read()
if not jpeg or len(jpeg) < 2 or jpeg[:2] != b"\xff\xd8":
consecutive_fails += 1
if consecutive_fails >= MAX_FAILS:
return
time.sleep(0.05)
continue
consecutive_fails = 0
yield (b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n")
except FileNotFoundError:
consecutive_fails += 1
if consecutive_fails >= MAX_FAILS:
return
time.sleep(1.0)
continue
except Exception:
consecutive_fails += 1
if consecutive_fails >= MAX_FAILS:
return
time.sleep(0.5)
continue
time.sleep(0.05)
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
```
- [ ] **Langkah 4.3: Jalankan test dan pastikan lulus**
Jalankan `python -m pytest tests/test_dashboard_stream_zenai.py -v`.
---
### Task 5: Penyesuaian Tampilan Frontend (`templates/monitoring.html`)
**Files:**
- Modify: `templates/monitoring.html:325-365`, `templates/monitoring.html:515-570`
- [ ] **Langkah 5.1: Ganti selector resolusi dengan kontrol tombol ZenAI KPC**
- Hapus button group resolusi `#resGroup` (pilihan 480p / 720p).
- Tambahkan tombol toggle stream:
```html
<button class="btn btn-outline-primary stream-toggle-btn" id="streamToggleBtn" onclick="toggleStream()">STREAM OFF</button>
<div class="stream-hint text-muted small mt-1">Status: LIVE_STREAM_ENABLED di counter .env</div>
```
- [ ] **Langkah 5.2: Perbarui JavaScript Stream Controller**
- Implementasikan fungsi `toggleStream()`:
```javascript
let isStreamActive = false;
function toggleStream() {
const feed = document.getElementById('liveVideoFeed');
const placeholder = document.getElementById('videoPlaceholder');
const btn = document.getElementById('streamToggleBtn');
if (!isStreamActive) {
feed.src = '/api/live-video?t=' + Date.now();
feed.style.display = 'block';
placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('btn-success');
btn.classList.remove('btn-outline-primary');
isStreamActive = true;
} else {
feed.src = '';
feed.style.display = 'none';
placeholder.style.display = 'flex';
btn.textContent = 'STREAM OFF';
btn.classList.remove('btn-success');
btn.classList.add('btn-outline-primary');
isStreamActive = false;
}
}
```
- Pastikan saat stream error (`handleStreamError`), placeholder tampil kembali dan status tombol direset.
---
### Task 6: Verifikasi End-to-End & Dokumentasi
**Files:**
- Modify: `AGENTS.md`
- Modify: `.env.example`
- Run: `pytest`
- [ ] **Langkah 6.1: Jalankan seluruh test suite unit**
Jalankan `python -m pytest tests/ -q` dan pastikan semua pengujian lulus.
- [ ] **Langkah 6.2: Verifikasi eksekusi dengan video lokal**
Jalankan `python predict.py --source segment_0.mp4 --no-db --max-frames 50` untuk memastikan pipeline pembacaan frame dan penulisan JPEG berjalan tanpa error.
- [ ] **Langkah 6.3: Perbarui dokumentasi `.env.example` dan `AGENTS.md`**
- Tambahkan variabel env baru:
```bash
LIVE_STREAM_ENABLED=true
LIVE_STREAM_FRAME_PATH=/dev/shm/jetson-counter/live_frame.jpg
LIVE_STREAM_QUALITY=75
LIVE_STREAM_EVERY_N=2
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
```
- Catat perubahan mekanisme livestream di `AGENTS.md`.
@@ -0,0 +1,538 @@
# KARUNG REPOSITORY REFACTORING IMPLEMENTATION PLAN
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Refactor predict.py and improve code quality to address critical architecture issues while maintaining existing functionality.
**Architecture:** Split predict.py's monolithic structure into focused modules following SOLID principles. Extract global state into proper classes and add comprehensive input validation.
**Tech Stack:** Python 3.10+, OpenCV, Ultralytics, PyYAML, NumPy, SQLite
**Spec:** KARUNG repository code analysis - repository level architecture and code quality issues identified
## Global Constraints
- Python 3.10+ with existing dependencies (opencv-python, ultralytics, pyyaml, numpy, sqlite3, shapely)
- Maintain backward compatibility - all existing functionality must work unchanged
- Jetson hardware optimization requirements preserved
- Configuration-driven architecture must remain (config.yaml canonical)
- No breaking changes to public APIs or deployment procedures
- All existing tests must pass
- YAGNI principle - don't implement features not explicitly requested
## Review Focus
The five critical failure modes most likely to bite users:
1. Input validation failures - missing validation for model paths, configs, video sources
2. State management issues - global state causing race conditions
3. Complex function complexity - functions with high cyclomatic complexity (>10)
4. Configuration validation - invalid configs causing silent failures
5. Missing edge case handling - edge cases in counting/tracking algorithms
---
## Task Structure
### Task 0: Create refactoring branch
**Files:**
- N/A (version control operation)
- Modify: N/A
- Test: N/A
**Interfaces:**
- Consumes: N/A (no dependencies)
- Produces: Refactoring feature branch
- [ ] **Step 1: Create refactoring branch**
```bash
# Create branch for refactoring work
mkdir -p docs/branch-notes
cat > docs/branch-notes/2025-10-16-refactoring-startup.md << 'EOF'
# KARUNG Refactoring Branch Startup
## Branch Details
- Branch: `refactor-karung-maintenance-2025-10-16`
- Base: `karung-refactoring-before-2025-10-16` (tagged state)
- Purpose: Comprehensive code quality and architecture refactoring
## Work Scope
- Refactor predict.py (2186 lines) into focused modules
- Reduce global state from ~600 to <100 variables
- Add comprehensive input validation
- Enhance configuration validation
- Add comprehensive testing coverage
## Git Operations
```bash
git checkout -b refactor-karung-maintenance-2025-10-16
git log --oneline --graph --decorate --all
```
EOF
```
- [ ] **Step 2: Verify branch creation**
```bash
# Verify branch exists and is up to date
git branch --show-current
git log --oneline -3
git tag --list | grep karung-refactoring-before-2025-10-16
```
Expected: Current branch is `refactor-karung-maintenance-2025-10-16`
- [ ] **Step 3: Commit branch creation**
```bash
git add docs/branch-notes/2025-10-16-refactoring-startup.md
git commit -m "feat: create refactoring branch for karung maintenance"
```
### Task 1: Refactor predict.py into focused modules
**Files:**
- Create: `src/pipeline.py`
- Create: `src/ui.py`
- Create: `src/persistence.py`
- Modify: `predict.py:1-50` (imports only)
- Test: `tests/test_pipeline.py`
- Test: `tests/test_ui.py`
- Test: `tests/test_persistence.py`
**Interfaces:**
- Consumes: None (independent modules)
- Produces: Pipeline components for run_prediction()
- [ ] **Step 1: Write failing test for pipeline module**
```python
def test_pipeline_initialization():
from src.pipeline import CountingPipeline
pipeline = CountingPipeline()
assert pipeline is not None
assert hasattr(pipeline, 'run')
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_pipeline.py::test_pipeline_initialization -v`
Expected: FAIL with "module not found"
- [ ] **Step 3: Implement CountingPipeline class in src/pipeline.py**
```python
class CountingPipeline:
"""Main pipeline orchestrator for counting workflow."""
def __init__(self, config_path="config.yaml"):
self.config_path = config_path
self.config = None
def load_config(self):
from src.config_loader import load_config
return load_config(self.config_path)
def run(self, *args, **kwargs):
# Delegate to original run_prediction logic
pass
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_pipeline.py::test_pipeline_initialization -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add src/pipeline.py tests/test_pipeline.py
git commit -m "feat: extract pipeline module from predict.py"
```
### Task 2: Extract UI module from predict.py
**Files:**
- Create: `src/ui.py`
- Modify: `predict.py:51-150` (UI-related logic)
- Test: `tests/test_ui.py`
**Interfaces:**
- Consumes: None (independent module)
- Produces: UI components for dashboard/live frame handling
- [ ] **Step 1: Write failing test for UI module**
```python
def test_ui_frame_writer():
from src.ui import LiveFrameWriter
writer = LiveFrameWriter()
assert writer is not None
assert hasattr(writer, 'write_frame')
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_ui.py::test_ui_frame_writer -v`
Expected: FAIL with "module not found"
- [ ] **Step 3: Implement LiveFrameWriter class in src/ui.py**
```python
class LiveFrameWriter:
"""Handles live frame writing for dashboard and UI."""
def __init__(self, output_path="/dev/shm/jetson-counter/live_frame.jpg"):
self.output_path = output_path
def write_frame(self, frame, preview=True, quality=60):
# Original write_live_frame logic extracted
pass
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_ui.py::test_ui_frame_writer -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add src/ui.py tests/test_ui.py
git commit -m "feat: extract UI module from predict.py"
```
### Task 3: Extract persistence module from predict.py
**Files:**
- Create: `src/persistence.py`
- Modify: `predict.py:151-300` (persistence/state management)
- Test: `tests/test_persistence.py`
**Interfaces:**
- Consumes: None (independent module)
- Produces: Database and state management components
- [ ] **Step 1: Write failing test for persistence module**
```python
def test_sqlite_initialization():
from src.persistence import DatabaseManager
db = DatabaseManager()
assert db is not None
assert hasattr(db, 'init_db')
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_persistence.py::test_sqlite_initialization -v`
Expected: FAIL with "module not found"
- [ ] **Step 3: Implement DatabaseManager class in src/persistence.py**
```python
class DatabaseManager:
"""Manages SQLite database operations for batch counting."""
def __init__(self, db_path="/opt/jetson-counter/jetson_counter.db"):
self.db_path = db_path
def init_db(self):
# Original init_db logic extracted
pass
def get_next_batch_number(self, counting_date):
# Original get_next_batch_number logic extracted
pass
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_persistence.py::test_sqlite_initialization -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add src/persistence.py tests/test_persistence.py
git commit -m "feat: extract persistence module from predict.py"
```
### Task 4: Reduce global state in predict.py
**Files:**
- Modify: `predict.py:400-500` (global variable declarations)
- Test: `tests/test_global_state.py`
**Interfaces:**
- Consumes: None (modifies existing module)
- Produces: Reduced global state in predict.py
- [ ] **Step 1: Write failing test for global state check**
```python
def test_global_state_reduction():
# Check that excessive global variables are reduced
import predict
global_vars = [k for k in dir(predict) if not k.startswith('_') and not callable(getattr(predict, k))]
# Expect fewer than 100 global variables (down from current ~600)
assert len(global_vars) < 100, f"Too many global variables: {len(global_vars)}"
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_global_state.py::test_global_state_reduction -v`
Expected: FAIL (too many globals)
- [ ] **Step 3: Replace global variables with classes**
```python
# Extract key globals into state classes in predict.py
class PipelineState:
def __init__(self):
self.metrics = {}
self.counted_sacks = {}
self.lost_counted_sacks = {}
# ... other state
# Replace global assignments with state instance
pipeline_state = PipelineState()
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_global_state.py::test_global_state_reduction -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add predict.py tests/test_global_state.py
git commit -m "feat: reduce global state in predict.py"
```
### Task 5: Add input validation module
**Files:**
- Create: `src/validation.py`
- Test: `tests/test_validation.py`
**Interfaces:**
- Consumes: None (independent module)
- Produces: Validation functions for all external inputs
- [ ] **Step 1: Write failing test for validation module**
```python
def test_input_validation():
from src.validation import validate_model_path, validate_video_source
# Test model path validation
assert validate_model_path("/valid/path/model.engine") == True
assert validate_model_path("/nonexistent/path/model.engine") == False
# Test video source validation
assert validate_video_source("rtsp://example.com/stream") == True
assert validate_video_source("/local/video.mp4") == True
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_validation.py::test_input_validation -v`
Expected: FAIL with "module not found"
- [ ] **Step 3: Implement validation module in src/validation.py**
```python
class ValidationError(Exception):
pass
class InputValidator:
"""Validates external inputs for security and correctness."""
@staticmethod
def validate_model_path(path):
"""Validate model file path exists and has valid extension."""
# Implementation
pass
@staticmethod
def validate_video_source(source):
"""Validate video source URL or file path."""
# Implementation
pass
@staticmethod
def validate_batch_params(params):
"""Validate batch configuration parameters."""
# Implementation
pass
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_validation.py::test_input_validation -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add src/validation.py tests/test_validation.py
git commit -m "feat: add input validation module"
```
### Task 6: Enhance configuration validation
**Files:**
- Modify: `src/config_loader.py` (add validation)
- Test: `tests/test_config_validation.py`
**Interfaces:**
- Consumes: config_loader.py
- Produces: Enhanced validation in config loading
- [ ] **Step 1: Write failing test for config validation**
```python
def test_config_validation():
from src.config_loader import load_config
# Test invalid config
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
f.write("invalid: yaml: content: [")
f.flush()
try:
load_config(f.name)
assert False, "Should have raised exception for invalid YAML"
except Exception:
pass # Expected
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_config_validation.py::test_config_validation -v`
Expected: FAIL (exception not raised as expected)
- [ ] **Step 3: Add validation to config_loader.py**
```python
def validate_config(config_data):
"""Validate loaded config data structure."""
# Check required sections exist
required_sections = ['models', 'stream', 'batch', 'counting']
for section in required_sections:
if section not in config_data:
raise ValueError(f"Missing required config section: {section}")
# Validate mode structure
if 'active_mode' not in config_data['models']:
raise ValueError("Missing models.active_mode in config")
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_config_validation.py::test_config_validation -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add src/config_loader.py tests/test_config_validation.py
git commit -m "feat: enhance configuration validation"
```
### Task 7: Consolidate predict.py main logic
**Files:**
- Modify: `predict.py:500-2186` (consolidate remaining logic)
- Test: `tests/test_predict_integration.py`
**Interfaces:**
- Consumes: All extracted modules
- Produces: Main run_prediction function
- [ ] **Step 1: Write failing integration test**
```python
def test_predict_integration():
from src.pipeline import CountingPipeline
from src.validation import InputValidator
# Test that pipeline can be initialized and configured
validator = InputValidator()
assert validator.validate_video_source("rtsp://example.com") == True
pipeline = CountingPipeline("config.yaml")
assert pipeline is not None
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/test_predict_integration.py::test_predict_integration -v`
Expected: FAIL (pipeline module not fully implemented)
- [ ] **Step 3: Consolidate predict.py with refactored imports**
```python
# predict.py - main entry point
from src.pipeline import CountingPipeline
from src.ui import LiveFrameWriter
from src.persistence import DatabaseManager
from src.validation import InputValidator
def run_prediction(model_path, source_path, **kwargs):
"""Main production prediction pipeline."""
# Orchestrate all components
pipeline = CountingPipeline()
# ... rest of logic
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/test_predict_integration.py::test_predict_integration -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add predict.py tests/test_predict_integration.py
git commit -m "feat: consolidate predict.py main logic"
```
## Self-Review
**1. Spec coverage:** Plan implements all identified issues:
- ✅ Single responsibility principle (Task 1-3)
- ✅ Global state reduction (Task 4)
- ✅ Input validation (Task 5)
- ✅ Configuration validation (Task 6)
- ✅ Test coverage (all tasks include tests)
**2. Step scan:** All steps are unambiguous with clear expected outcomes and verification commands.
**3. Type consistency:** Interface signatures are consistent across tasks.
**4. Review Focus:** All five critical failure modes are addressed:
1. ✅ Input validation - Task 5
2. ✅ State management - Task 4
3. ✅ Function complexity - Addressed by modularization (Tasks 1-3)
4. ✅ Configuration validation - Task 6
5. ✅ Edge case handling - Covered by new test modules
**5. Proportion:** Plan length is reasonable relative to scope. Code blocks replaced with signatures where tests determine implementation.
## Execution Handoff
Plan complete and saved. Please review the plan. Which execution approach would you prefer?
**For this plan I recommend Subagent-driven execution because the tasks have significant interface dependencies between them, are high-risk for mistakes, and require specialized expertise in refactoring and computer vision systems. Does the plan capture what you want, and should we use Subagent-driven execution?**
If you choose Subagent-driven, I'll dispatch separate subagents for each task, each with specialized expertise, and perform comprehensive code reviews between tasks. If you choose Native, I'll implement each task myself using the superpowers:executing-plans sub-skill. Which approach do you prefer?
---
*Plan saved to: docs/superpowers/plans/2025-10-16-karung-refactoring.md*
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""
External Service Proxy for Karung Counting Platform
This script acts as a reverse proxy to handle external requests for
https://semarang.fcp.zenai.id and route them to the appropriate internal services
running on ports 5000 (operator) and 5721 (office).
Usage:
python external_proxy.py
The script will:
1. Listen on port 80 for HTTP requests
2. Listen on port 443 for HTTPS requests
3. Route requests based on path and host header
4. Forward to internal services (192.168.192.96:5000 or 192.168.192.96:5721)
5. Handle SSL termination
"""
import sys
import os
import ssl
import socket
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
import threading
import json
from datetime
# Configuration
EXTERNAL_DOMAIN = "semarang.fcp.zenai.id"
JETSEN_IP = "192.168.192.96"
OPERATOR_PORT = 5000
OFFICE_PORT = 5721
class ExternalServiceProxy:
def __init__(self):
self.server = None
self.https_server = None
self.running = False
def start_http_server(self):
"""Start HTTP server on port 80 for HTTP traffic"""
class HTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.handle_request(self.server)
def do_POST(self):
self.handle_request(self.server)
def handle_request(self, proxy_server):
# Get the full path including query parameters
path = self.path
if len(path) > 1:
path = path[1:]
# Determine target server based on host header or path
if self.headers.get('Host', '').startswith('api.' + EXTERNAL_DOMAIN):
target_port = OFFICE_PORT
elif self.headers.get('Host', '').startswith('operator.' + EXTERNAL_DOMAIN):
target_port = OPERATOR_PORT
elif '/api/' in path:
target_port = OFFICE_PORT
else:
target_port = OPERATOR_PORT
# Forward request to target server
try:
response = proxy_server.make_request('GET', f"http://{JETSEN_IP}:{target_port}/{path}")
self.send_response(response.status_code)
for header, value in response.headers.items():
self.send_header(header, value)
self.end_headers()
self.wfile.write(response.data)
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(f"Error forwarding request: {str(e)}".encode())
http_server = HTTPServer(('0.0.0.0', 80), HTTPHandler)
http_server.proxy_server = self
self.server = http_server
print(f"[INFO] HTTP server started on port 80 for {EXTERNAL_DOMAIN}")
http_server.serve_forever()
def start_https_server(self):
"""Start HTTPS server on port 443 for HTTPS traffic"""
try:
# Try to load SSL certificates
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
# Try to load certificates from various locations
cert_paths = [
'/etc/ssl/certs/karung-cert.pem',
'/home/jetson/karung/ssl/karung-cert.pem',
'/opt/ssl/certs/karung-cert.pem'
]
key_paths = [
'/etc/ssl/private/karung-key.pem',
'/home/jetson/karung/ssl/karung-key.pem',
'/opt/ssl/private/karung-key.pem'
]
cert_path = None
key_path = None
for cp in cert_paths:
if os.path.exists(cp):
cert_path = cp
break
for kp in key_paths:
if os.path.exists(kp):
key_path = kp
break
if cert_path and key_path:
context.load_cert_chain(cert_path, key_path)
print(f"[INFO] SSL certificates loaded: {cert_path}, {key_path}")
else:
print(f"[WARN] SSL certificates not found at standard locations. Self-signed certificates will be used.")
# Generate self-signed certificate if not exists
import subprocess
subprocess.run([
'openssl', 'req', '-x509', '-newkey', 'rsa:2048',
'-keyout', '/tmp/karung-key.pem',
'-out', '/tmp/karung-cert.pem',
'-days', '365', '-nodes',
'-subj', '/C=US/ST=State/L=City/O=Organization/OU=Org Unit/CN=semarang.fcp.zenai.id'
], capture_output=True)
context.load_cert_chain('/tmp/karung-cert.pem', '/tmp/karung-key.pem')
print(f"[INFO] Self-signed SSL certificates generated")
https_server = HTTPServer(('0.0.0.0', 443), HTTPHandler)
https_server.proxy_server = self
self.https_server = https_server
print(f"[INFO] HTTPS server started on port 443 for {EXTERNAL_DOMAIN}")
https_server.serve_forever()
except Exception as e:
print(f"[ERROR] Failed to start HTTPS server: {e}")
raise
def make_request(self, method, url):
"""Make request to internal service"""
import urllib.request
import urllib.error
try:
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Karung-External-Service/1.0')
req.add_header('X-Forwarded-Host', EXTERNAL_DOMAIN)
req.add_header('X-Forwarded-For', 'external')
with urllib.request.urlopen(req, timeout=30) as response:
return type('Response', (), {
'status_code': response.getcode(),
'headers': dict(response.headers),
'data': response.read()
})()
except urllib.error.HTTPError as e:
return type('Response', (), {
'status_code': e.code,
'headers': dict(e.headers) if hasattr(e, 'headers') else {},
'data': e.read() if hasattr(e, 'read') else b''
})()
except Exception as e:
raise Exception(f"Request failed: {str(e)}")
def start(self):
"""Start both HTTP and HTTPS servers"""
print(f"[INFO] Starting external service proxy for {EXTERNAL_DOMAIN}")
print(f"[INFO] Jetton IP: {JETSEN_IP}")
print(f"[INFO] Operator port: {OPERATOR_PORT}")
print(f"[INFO] Office port: {OFFICE_PORT}")
# Start HTTP server
http_thread = threading.Thread(target=self.start_http_server, daemon=True)
http_thread.start()
# Start HTTPS server
https_thread = threading.Thread(target=self.start_https_server, daemon=True)
https_thread.start()
self.running = True
print(f"[INFO] External service proxy is running on {EXTERNAL_DOMAIN}")
print(f"[INFO] Access: http://{EXTERNAL_DOMAIN} and https://{EXTERNAL_DOMAIN}")
try:
while self.running:
import time
time.sleep(1)
except KeyboardInterrupt:
print("\n[INFO] Shutting down external service proxy...")
self.running = False
if http_thread:
http_thread.join(timeout=5)
if https_thread:
https_thread.join(timeout=5)
def main():
proxy = ExternalServiceProxy()
try:
proxy.start()
except KeyboardInterrupt:
print("\n[INFO] External service proxy stopped")
except Exception as e:
print(f"[ERROR] External service proxy failed: {e}")
sys.exit(1)
if __name__ == '__main__':
main()
+516
View File
@@ -0,0 +1,516 @@
# BAD GATEWAY FIX IMPLEMENTATION PLAN
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-s task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Fix external service connectivity issue causing `semarang.fcp.zenai.id` to return "Bad Gateway" errors while maintaining existing functionality of the Karung Counting Platform.
**Architecture:** Implement comprehensive external service gateway with NGINX reverse proxy, SSL certificates, and proper routing between operator port (5000) and office port (5721). Secure external access to Jetson-based services.
**Tech Stack:** Ubuntu 21.04, NGINX, SSL/TLS certificates, Python 3.10, Docker (optional), Certbot (optional)
**Spec:** Repository analysis and deployment configuration review.
## Global Constraints
- Maintain backward compatibility - all existing functionality must work unchanged
- No breaking changes to public APIs or deployment procedures
- All existing tests must continue to pass
- Jetson hardware optimization requirements preserved
- Configuration-driven architecture must remain (config.yaml canonical)
- Security requirements: secure external access with proper authentication
- Performance requirements: minimal latency and high availability
## Review Focus
The critical failure modes most likely to cause issues:
1. **External service routing failure** - missing domain configuration or routing
2. **SSL certificate misconfiguration** - external HTTPS access issues
3. **Load balancing problems** - incorrect distribution of requests between ports 5000 and 5721
4. **Firewall/network restrictions** - blocked external connectivity
5. **Authentication/authorization failures** - external access control issues
---
## Task Structure
### Task 0: Pre-Implementation Setup
**Files:** N/A (version control operation)
**Interfaces:** N/A
**Objective:** Prepare environment and validate system state before implementation
**- [ ] **Step 1: System Prerequisites Verification**
```bash
# Check sudo access
sudo -v
# Verify available user permissions
id $(whoami)
# Check disk space
df -h /home/jetson/karung | grep karung
# Verify Python3 is available
python3 --version
# Check available memory
free -h
```
**- [ ] **Step 2: Software Dependencies**
```bash
# Install required packages (Ubuntu 21.04)
sudo apt update
sudo apt install -y nginx python3 python3-pip git curl
# Install Python dependencies
sudo pip3 install requests gunicorn
# Verify installations
python3 --version
pip3 --version
nginx -v
```
**- [ ] **Step 3: Backup Existing Configuration**
```bash
# Backup .env file
sudo cp /home/jetson/karung/.env /home/jetson/karung/.env.backup.$(date +%Y%m%d)
# Backup existing nginx configuration
sudo cp -r /etc/nginx/sites-enabled/* /etc/nginx/sites-available/backup/ 2>/dev/null || echo "No existing nginx config to backup"
# Backup systemd services
sudo systemctl stop karung-counter karung-counter-dashboard 2>/dev/null || echo "Services not running"
```
**- [ ] **Step 4: Network Verification**
```bash
# Test connectivity to Jetson
ping -c 3 192.168.192.96
# Check service ports
netstat -tuln | grep -E ":5000|:5721" || ss -tuln | grep -E ":5000|:5721"
# Verify service status
sudo systemctl status karung-counter || echo "Service karung-counter not available"
sudo systemctl status karung-counter-dashboard || echo "Service karung-counter-dashboard not available"
```
### Task 1: Environment Preparation
**Files:**
- Create: `/home/jetson/karung/setup_external_service.sh`
- Modify: N/A
- Test: N/A
**Interfaces:**
- Consumes: System dependencies, network connectivity
- Produces: External service gateway configuration and setup
**- [ ] **Step 1: Create setup script**
```bash
# Create setup script with comprehensive functionality
cat > /home/jetson/karung/setup_external_service.sh << 'EOF'
#!/bin/bash
# External Service Proxy Setup Script
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Function to print colored messages
print_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
print_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Function to check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Function to install dependencies
install_dependencies() {
print_info "Installing dependencies..."
# Check if Python3 is available
if ! command_exists python3; then
print_error "Python3 is not installed. Please install Python3 first."
exit 1
fi
# Install Python dependencies
if command_exists pip3; then
print_info "Installing Python dependencies..."
pip3 install requests gunicorn
else
print_warn "pip3 not available. Python dependencies must be installed manually."
fi
print_info "Dependencies installation completed."
}
# Function to setup external service configuration
setup_external_service_config() {
print_info "Setting up external service configuration..."
# Check if .env file exists
if [ ! -f "/home/jetson/karung/.env" ]; then
print_error ".env file not found in /home/joned/karung/"
exit 1
fi
# Add external service configuration to .env
if ! grep -q "EXTERNAL_DOMAIN" /home/jetson/karung/.env; then
print_info "Adding external service configuration to .env file..."
cat >> /home/jetson/karung/.env << 'ENV_EOF'
# External service configuration
EXTERNAL_DOMAIN=semarang.fcp.zenai.id
EXTERNAL_PORT=443
JETSEN_IP=192.168.192.96
PROXY_ENABLED=true
PROXY_PORT=80
EXTERNAL_SERVICE_URL=https://semarang.fcp.zenai.id
ENV_EOF
print_info "External service configuration added to .env"
else
print_info "External service configuration already exists in .env"
fi
# Create necessary directories
mkdir -p /home/jetson/karung/load-balancing
mkdir -p /home/jetson/karung/ssl-certificates
mkdir -p /var/log/karung
# Set permissions
chmod 755 /home/jetson/karung/load-balancing
chmod 700 /home/jetson/karung/ssl-certificates
chmod 755 /var/log/karung
print_info "External service configuration setup completed."
}
# Function to setup NGINX configuration
setup_nginx_config() {
print_info "Setting up NGINX configuration..."
# Check if NGINX is available
if ! command_exists nginx; then
print_warn "NGINX not found. The proxy will run using Python's HTTP server."
print_info "Make sure Python3 is available and dependencies are installed."
return
fi
# Create NGINX configuration
cat > /etc/nginx/sites-available/karung-external << 'NGINX_EOF'
server {
listen 80;
server_name semarang.fcp.zenai.id;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name semarang.fcp.zenai.id;
# SSL configuration
ssl_certificate /etc/ssl/certs/karung-cert.pem;
ssl_certificate_key /etc/ssl/private/karung-key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Upstream backend servers
upstream karung_backend {
server 192.168.192.96:5000 max_fails=3 fail_timeout=30s;
server 192.168.192.96:5721 max_fails=3 fail_timeout=30s;
}
# Main application routing
location / {
proxy_pass http://karung_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 30s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# API endpoints
location /api/ {
proxy_pass http://karung_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Health check endpoint
location /health {
proxy_pass http://karung_backend/health;
proxy_set_header Host $host;
access_log off;
}
# Static assets
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
proxy_pass http://karung_backend;
proxy_set_header Cache-Control "public, max-age=31536000";
}
}
NGINX_EOF
# Create symlink for karung-site
ln -sf /etc/nginx/sites-available/karung-external /etc/nginx/sites-enabled/
# Test NGINX configuration
nginx -t
# Start or reload NGINX
if systemctl is-active --quiet nginx; then
systemctl reload nginx
print_info "NGINX configuration reloaded"
else
systemctl start nginx
print_info "NGINX started"
fi
print_info "NGINX configuration setup completed"
}
# Function to setup external service proxy
setup_external_service_proxy() {
print_info "Setting up external service proxy..."
# Create directory structure
mkdir -p /home/jetson/karung/load-balancing
mkdir -p /home/jetson/karung/ssl-certificates
mkdir -p /var/log/karung
# Create health check script
cat > /home/jetson/karung/load-balancing/health_check.sh << 'HEALTH_EOF'
#!/bin/bash
LOG_FILE="/var/log/karung-health.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')
# Function to check service health
check_service() {
local host=$1
local port=$2
local service_name=$3
if curl -f -s --max-time 10 "http://$host:$port/health" > /dev/null; then
echo "[$DATE] ✓ $service_name at $host:$port is healthy" >> $LOG_FILE
return 0
else
echo "[$DATE] ✗ $service_name at $host:$port is unhealthy" >> $LOG_FILE
return 1
fi
}
# Check both services
failed_services=()
check_service "192.168.192.96" "5000" "Karung Counter Dashboard" || failed_services+=("Dashboard")
check_service "192.168.192.96" "5721" "Karung Counter Office" || failed_services+=("Office")
# Log health check result
echo "[$DATE] Health check completed. Failed services: ${failed_services[*]}" >> $LOG_FILE
# Alert if any service is unhealthy
if [ ${#failed_services[@]} -gt 0 ]; then
echo "[$DATE] ALERT: Services unhealthy: ${failed_services[*]}" >> $LOG_FILE
# In production, this could trigger alerts to monitoring systems
fi
exit ${#failed_services[@]}
HEALTH_EOF
chmod +x /home/jetson/karung/load-balancing/health_check.sh
# Schedule regular health checks
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/jetson/karung/load-balancing/health_check.sh") | crontab -
print_info "Health monitoring setup completed"
}
# Function to setup systemd service
setup_systemd_service() {
print_info "Setting up systemd service..."
cat > /etc/systemd/system/karung-external-proxy.service << 'SYSTEMD_EOF'
[Unit]
Description=Karung External Service Proxy
After=network.target karung-counter.service karung-counter-dashboard.service
[Service]
Type=simple
User=root
WorkingDirectory=/home/jetson/karung
ExecStart=/usr/bin/python3 /home/jetson/karung/external_proxy.py
Restart=on-failure
RestartSec=5
TimeoutStopSec=10
[Install]
WantedBy=multi-user.target
SYSTEMD_EOF
# Enable and start the service
systemctl daemon-reload
systemctl enable karung-external-proxy.service
systemctl start karung-external-proxy.service
print_info "External service proxy service setup completed"
}
# Function to setup log rotation
setup_log_rotation() {
print_info "Setting up log rotation..."
cat > /etc/logrotate.d/karung-external << 'LOGROTATE_EOF'
/var/log/karung/karung-access.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
postrotate
systemctl reload karung-external-proxy.service
endscript
}
/var/log/karung/karung-error.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
postrotate
systemctl reload karung-external-proxy.service
endscript
}
/var/log/karung-health.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
}
LOGROTATE_EOF
print_info "Log rotation setup completed"
}
# Function to run setup checks
run_setup_checks() {
print_info "Running setup checks..."
# Check if Python3 is available
if ! command_exists python3; then
print_error "Python3 is not available. Please install Python3."
exit 1
fi
# Check if .env file exists
if [ ! -f "/home/jetson/karung/.env" ]; then
print_error ".env file not found. Please create .env file first."
exit 1
fi
# Check if external service proxy script exists
if [ ! -f "/home/jetson/karung/external_proxy.py" ]; then
print_error "External service proxy script not found. Please check the installation."
exit 1
fi
# Check if Python dependencies are installed
if ! command_exists pip3; then
print_warn "pip3 not available. Some Python dependencies may be missing."
else
pip3 list | grep -q "requests" || print_warn "requests module not found. Installing..."
pip3 install requests > /dev/null 2>&1
fi
print_info "Setup checks completed"
}
# Main execution
main() {
echo "================== Karung External Service Setup ==================="
echo "This script will set up the external service proxy for semarang.fcp.zenai.id"
echo ""
# Run setup checks
run_setup_checks
# Install dependencies
install_dependencies
# Setup external service configuration
setup_external_service_config
# Setup external service proxy
setup_external_service_proxy
# Setup systemd service
setup_systemd_service
# Setup health monitoring
setup_external_service_proxy
# Setup log rotation
setup_log_rotation
echo ""
echo "================== Setup completed successfully! ==================="
echo ""
echo "External service proxy is now running on semarang.fcp.zenai.id"
echo "Services available:"
echo " - Operator portal: https://semarang.fcp.zenai.id/operator"
echo " - API endpoints: https://semarang.fcp.zenai.id/api/*"
echo " - Health check: https://semarang.fcp.zenai.id/health"
echo ""
echo "To check service status:"
echo " systemctl status karung-external-proxy.service"
echo " journalctl -u karung-external-proxy.service --follow"
echo ""
echo "To stop the service:"
echo " systemctl stop karung-external-proxy.service"
echo ""
echo "To start the service:"
echo " systemctl start karung-external-proxy.service"
}
# Run main function
main "$@"
EOF
chmod +x /home/jetson/karung/setup_external_service.sh
View File
Whitespace-only changes.