generate_docs.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. #ident "@(#)$Format:LocalFoodAI:app.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  2. # $Id$
  3. # $Author$
  4. # $log$
  5. import os
  6. #ident "@(#)$Format:LocalFoodAI:generate_docs.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  7. import subprocess
  8. docs_dir = "docs"
  9. os.makedirs(docs_dir, exist_ok=True)
  10. docs = {
  11. "Final_Report.md": """# $Id$
  12. # Final Project Report (Living Document)
  13. ## What Has Been Done
  14. 1. **Core Architecture**: Deployed a resilient 8-container local fallback Docker Compose stack (MySQL, Streamlit UI, local Ollama LLM, anonymous SearXNG search, secure Nginx proxy, and local Zabbix Server/Web/Agent observability suite).
  15. 2. **Database Optimization**: Successfully loaded OpenFoodFacts records and utilized advanced vertical partitioning and FULLTEXT indices.
  16. 3. **Clinical Subquery Strategy**: Refactored the core Pandas/SQL query pipeline to use subquery limiting, resolving Cartesian join explosions and reducing query latency to ~0.04s.
  17. 4. **Monitoring & Security**: Nginx securely proxies traffic on Port 80. Zabbix actively monitors proxy and server health, dynamically handling SNMP/alert loops in local/offline fallback mode.
  18. 5. **Git Versioning**: Implemented Git `.gitattributes` to push `$Id$` tracking directly into the Python Application UI.
  19. ## What Needs To Be Done (Day 2 Operations)
  20. 1. **SSL/TLS Certificates**: The Nginx proxy is functional on HTTP port 80. Port 443 (HTTPS) must be configured with a Let's Encrypt certificate for true production encryption.
  21. 2. **User Acceptance Testing (UAT)**: Clinical dietitians should rigorously test the AI Chat constraints and Plate Builder to ensure edge cases are handled safely.
  22. 3. **Advanced Rate Limiting**: Limit the number of AI requests per user using a sliding window algorithm in `app.py`.
  23. ## What Is The Next Step
  24. - Execute the `data_sync.sh` cron job monthly.
  25. - Maintain the automated `backup_db.sh` 7-day retention cycle.
  26. - Begin the hand-off to the operational team for Phase 2 feature requests.
  27. """,
  28. "Backup_Procedure.md": """# $Id$
  29. # Database Backup and Restore Procedure
  30. ## 1. Overview & Policy
  31. To guarantee clinical records integrity and high availability, Local Food AI enforces a strict backup schedule.
  32. - **Scope**: Includes MySQL schemas (`food_db`), user profiles (`app_auth`), and configuration states.
  33. - **Retention Plan**: Automated daily backups with a strict 7-day rolling window purge.
  34. - **Storage Location**: Stored securely inside the persistent `/backups` directory on the host server.
  35. ---
  36. ## 2. Automated Daily Backups
  37. The automated backup mechanism runs via a host cron job pointing to `backup_db.sh`.
  38. - The script dynamically detects the active MySQL container name (`food-mysql-1` or `food_project-mysql-1`).
  39. - It executes `mysqldump` directly inside the container without exposing root passwords to shell logs.
  40. - Outputs are compressed via `gzip` and timestamped: `food_db_YYYYMMDD_HHMM.sql.gz`.
  41. ### Cron Configuration Example:
  42. To run the backup daily at 02:00 AM, add the following to `/etc/crontab`:
  43. ```bash
  44. 0 2 * * * root /bin/bash /c/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/backup_db.sh >> /var/log/backup_db.log 2>&1
  45. ```
  46. ---
  47. ## 3. Manual Backup Execution
  48. If a system migration or major upgrade is scheduled, perform a manual dump using the following command:
  49. ```bash
  50. # 1. Navigate to the project directory
  51. cd /c/Users/lanfr144/Documents/DOPRO1/Antigravity/Food
  52. # 2. Run the backup wrapper
  53. bash backup_db.sh
  54. ```
  55. Verify the output exists inside the backups folder:
  56. ```bash
  57. ls -lh backups/
  58. ```
  59. ---
  60. ## 4. Step-by-Step Restore Procedure
  61. In the event of database corruption or hardware failure, follow these exact steps to restore the database.
  62. ### Step 4.1: Identify the Target Backup File
  63. List available files and pick the desired timestamp:
  64. ```bash
  65. ls -la backups/
  66. # Example Target: backups/food_db_20260521_1100.sql.gz
  67. ```
  68. ### Step 4.2: Verify MySQL Container Health
  69. Ensure the MySQL service container is running and healthy:
  70. ```bash
  71. docker ps --filter name=mysql
  72. ```
  73. ### Step 4.3: Execute Restore Stream
  74. Decompress the backup on-the-fly and pipe it directly into the running MySQL container:
  75. ```bash
  76. # Adjust the container name ('food-mysql-1' or 'food_project-mysql-1') based on active deployment
  77. gunzip < backups/food_db_20260521_1100.sql.gz | docker exec -i food-mysql-1 mysql -u root -proot_pass food_db
  78. ```
  79. ### Step 4.4: Verify Restored Tables
  80. Log in to the database and query the core table to confirm the tables are intact and populated:
  81. ```bash
  82. docker exec -it food-mysql-1 mysql -u food_reader -preader_pass food_db -e "SELECT COUNT(*) FROM products_core;"
  83. ```
  84. Expected result: A count of OpenFoodFacts entries (typically > 10,000 records).
  85. ---
  86. ## 5. Verification & Health Check Loops
  87. Operators must verify the backup archive integrity weekly:
  88. 1. Copy the `.gz` backup to a local testing workspace.
  89. 2. Run `gzip -t backups/filename.sql.gz` to ensure the archive is not corrupted.
  90. 3. Test restoring to a local fallback container instance to verify data accessibility.
  91. """,
  92. "Data_Ingestion.md": """# $Id$
  93. # Data Ingestion Pipeline
  94. ## Overview
  95. The application utilizes `data_sync.sh` to update the OpenFoodFacts dataset.
  96. ## Online Mode
  97. Run `bash data_sync.sh --online`. The script will download the latest CSV directly from the official servers and trigger the ingestion pipeline.
  98. ## Offline Mode
  99. Drop a `en.openfoodfacts.org.products.csv` file into the `/data` folder and run `bash data_sync.sh`. The script detects the file and triggers the Docker ingestion container.
  100. """,
  101. "Installation_Guide.md": """# $Id$
  102. # Installation Guide
  103. ## Requirements
  104. - Ubuntu 24.04 LTS (or WSL2)
  105. - Docker & Docker Compose
  106. - 16GB RAM Minimum
  107. ## Deployment Steps
  108. 1. **Clone the Repository**:
  109. - *Online Mode*: `git clone https://git.btshub.lu/lanfr/LocalFoodAI_lanfr144.git`
  110. - *Offline/Disconnected Mode*: Copy the repository files directly to the target environment via SCP or USB storage.
  111. 2. `cd LocalFoodAI_lanfr144`
  112. 3. `chmod +x data_sync.sh backup_db.sh`
  113. 4. **Deploy Stack**:
  114. - For regular production: `docker compose up -d --build`
  115. - For local/offline single-node fallback: `docker compose -f docker-compose_skip.yml up -d`
  116. 5. Navigate to `http://localhost` (or `http://localhost:8502` for direct Streamlit port)
  117. """,
  118. "User_Guide.md": """# $Id$
  119. # User Guide
  120. ## 1. Clinical Data Search
  121. Search for products using keywords. The system utilizes FULLTEXT matching to instantly return the top 10 relevant matches alongside macronutrient data.
  122. ## 2. My Plate Builder
  123. Add portion sizes of different foods to calculate cumulative nutritional intake. Use the 🗑️ icon to remove items.
  124. ## 3. Chat with AI
  125. Ask the `qwen2.5:7b` model complex dietary questions. It natively utilizes RAG Tool Calling to silently search the database and formulate clinical answers.
  126. """,
  127. "Wiki_Home.md": """# $Id$
  128. # Documentation Home
  129. Welcome to the static documentation mirror. Please navigate the markdown files in this directory for architectural diagrams and guides.
  130. """,
  131. "Scrum_Wiki.md": """# $Id$
  132. # Scrum Wiki Master List & Index Portal
  133. Welcome to the static Scrum documentation portal. This master wiki aggregates and organizes all daily stand-up logs, planning reports, retrospectives, reviews, and velocity charts recorded during the agile development of the **Local Food AI** clinical dietetics engine.
  134. ---
  135. ## 📅 Sprint Ceremonies & Logs
  136. ### 1. [Sprint Plans (Scrum_Plan.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Plan.md)
  137. *Contains Sprint Plan formulations, active user stories selection, scope statements, and team capacity bounds for each milestone loop.*
  138. ### 2. [Daily Scrums (Scrum_Daily.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Daily.md)
  139. *Continuous daily stand-up summaries tracking individual task completion, blocker mitigations, and immediate day-to-day coordination.*
  140. ### 3. [Sprint Reviews (Scrum_Review.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Review.md)
  141. *Contains sprint review logs, clinician demonstration summaries, feature validation checklists, and stakeholder feedback logs.*
  142. ### 4. [Sprint Retrospectives (Scrum_Retro.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Retro.md)
  143. *Reviews process improvements, continuous integration learnings, and action items aimed at optimizing team operations and environment tuning.*
  144. ---
  145. ## 📊 Deliverables & Quality Assurance
  146. ### 5. [Scrum Artifacts (Scrum_Artifacts.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Artifacts.md)
  147. *Indexes sprint velocity metrics, completed story points distributions, burndown coordinates, and final Taiga delivery milestones.*
  148. ### 6. [Sprint 8 Test Cases (Test_Cases_Sprint8.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Test_Cases_Sprint8.md)
  149. *Legacy acceptance test logs covering core NLP chat, portion converters, and initial search validations.*
  150. ---
  151. > [!NOTE]
  152. > **Operational Compliance**: All Scrum files above are synchronized with their respective Taiga milestone identifiers (`Sprint 13` and `Sprint 7`). All physical activities recorded in these markdown logs have corresponding closed tasks inside Taiga.
  153. """,
  154. "Scrum_Daily.md": """# $Id$
  155. # Daily Scrums
  156. - **26.05.07 DAILY**: Fixed time scope bug, added Nginx proxy, built sync scripts.
  157. """,
  158. "Scrum_Plan.md": """# $Id$
  159. # Sprint Plans
  160. - **Sprint 10 PLAN**: Fix LLM Tool Calling, optimize Cartesian SQL explosion, build Teams webhooks.
  161. """,
  162. "Scrum_Retro.md": """# $Id$
  163. # Sprint Retrospectives
  164. - **Sprint 10 RETROSPECTIVE**: Mitigated dirty data duplicates using SQL `GROUP BY`. Need to maintain strict Git commit tagging (`TG-XXX`).
  165. """,
  166. "Scrum_Review.md": """# $Id$
  167. # Sprint Reviews
  168. - **Sprint 10 REVIEW**: App executes sub-second searches. Nginx fully operational on Port 80.
  169. """,
  170. "Scrum_Artifacts.md": """# $Id$
  171. # Scrum Artifacts
  172. Contains User Stories, velocity tracking, and burndown charts from Taiga.
  173. """,
  174. "Test_Cases_Sprint8.md": """# $Id$
  175. # Sprint 8 Legacy Test Cases
  176. - Tested RAG AI tool integration.
  177. - Tested user authentication flows.
  178. """,
  179. "WSL_Deployment.md": """# $Id$
  180. # WSL Deployment Runbook
  181. To deploy on Windows Subsystem for Linux:
  182. 1. Ensure WSL2 backend is enabled in Docker Desktop.
  183. 2. Follow standard Installation Guide inside the WSL Ubuntu terminal.
  184. """,
  185. "User_Description.md": """# $Id$
  186. # Local Food AI - User Description & Functional Guide
  187. ## 1. System Vision
  188. The **Local Food AI** system is a strictly local, privacy-first, professional-grade clinical dietetics assistant. Developed specifically for clinics and healthcare practitioners, it provides offline nutritional analysis, meal planning, and warning flags based on dynamic patient health profiles.
  189. Since the system operates entirely locally on local hypervisors, **zero patient medical data or search queries ever leave the server boundary**, ensuring 100% HIPAA compliance and data sovereignty.
  190. ---
  191. ## 2. Core Functional Pillars
  192. ### 📊 tab 1: Clinical Data Search (🔬 Clinical Search)
  193. Allows practitioners to search the 24GB OpenFoodFacts dataset in real time (average query response time < 0.04 seconds).
  194. - **Dynamic Medical Warnings**: Based on the active patient profile, foods are immediately flagged in the search results:
  195. - ⚠️ **Red Warning Flags**: Highlight high-risk ingredients (e.g. Unpasteurized dairy or raw fish for pregnant patients, high-sodium foods for hypertensive patients, or high-sugar foods for diabetic patients).
  196. - 💚 **Green Recommendations**: Highlight recommended dietary components (e.g. High iron/calcium for pregnant or breastfeeding mothers, high Vitamin C for scurvy prevention, or high iron for anemia).
  197. - **Flexible Column Customization**: Multi-select column headers to inspect specific macro and micro-nutrients.
  198. ### 💬 tab 2: AI Clinical Chat (💬 AI Chat)
  199. An interactive NLP dialogue interface powered by a local lightweight LLM (**Qwen2.5:7b**).
  200. - **RAG-Driven Precision**: The AI dietitian automatically retrieves and reviews local database records and private meta-search results before formulating an answer.
  201. - **Dynamic Medical Guardrails**: The user's active illnesses, diets, and conditions are injected into the AI's system prompt in the background, forcing the AI to strictly enforce clinical safety constraints.
  202. ### 🍽️ tab 3: My Plate Builder (🍽️ My Plate Builder)
  203. A recipe formulation utility to calculate combined nutritional intake.
  204. - **Natural Language Parsing**: Enables entering quantities in natural units (e.g., "1.5 cups", "2 tablespoons", "150g").
  205. - **Exact Conversion**: The system translates these custom units into metric grams based on product density metrics.
  206. - **Macro Summaries**: Instantly calculates and displays the total combined Protein, Fat, and Carbohydrates.
  207. ### 🤖 tab 4: AI Meal Planner (🤖 AI Meal Planner)
  208. An automated clinical diet planner.
  209. - Generates a multi-meal daily menu formatted strictly as a Markdown table.
  210. - Dynamically enforces user-defined calorie limits and active medical restrictions.
  211. ---
  212. ## 3. Supported Health & Medical Profiles
  213. - **Conditions**: Pregnant, Breastfeeding, Low Fat, Osteoporosis.
  214. - **Illnesses**: Diabetes, Hypertension, Kidney Disease, Scurvy, Anemia.
  215. - **Diets**: Vegan, Vegetarian, Kosher, Halal, Keto, Paleo, Christian (Lent/Good Friday).
  216. """,
  217. "Start_Stop_Procedures.md": """# $Id$
  218. # Infrastructure Stop & Start Operational Procedures
  219. This runbook outlines the exact sequence and commands to start, stop, and verify each microservice in the Local Food AI environment.
  220. ---
  221. ## 1. Sequence Priority Rules
  222. Due to database socket requirements and network bindings, services **must** be started and stopped in the following order:
  223. ```mermaid
  224. graph TD
  225. subgraph Startup Sequence
  226. direction TB
  227. A[1. MySQL Database] --> B[2. Ollama & SearXNG AI Services]
  228. B --> C[3. Streamlit Application & Nginx Proxy]
  229. C --> D[4. Zabbix Monitoring & Airflow Supervisor]
  230. end
  231. ```
  232. ---
  233. ## 2. Startup Procedures
  234. ### Step 2.1: Start the Core MySQL Database
  235. Verify that the database service is up and listening on port 3307:
  236. ```bash
  237. docker compose up -d mysql
  238. # Verify database logs
  239. docker compose logs -f mysql
  240. ```
  241. ### Step 2.2: Start AI Engine & SearXNG Search
  242. Deploy the AI components:
  243. ```bash
  244. docker compose up -d ollama searxng
  245. # Check that Ollama responds
  246. curl http://localhost:11434/api/tags
  247. ```
  248. ### Step 2.3: Start Streamlit App and Nginx Gateway
  249. Bring up the frontend web interface and reverse proxy:
  250. ```bash
  251. docker compose up -d app nginx
  252. # Verify Web Interface status
  253. curl -I http://localhost
  254. ```
  255. ### Step 2.4: Start Zabbix Monitoring Suite
  256. Deploy the monitoring server and agents:
  257. ```bash
  258. docker compose up -d zabbix-server zabbix-web zabbix-agent
  259. # Check dashboard availability
  260. curl -I http://localhost:8081
  261. ```
  262. ---
  263. ## 3. Shutdown Procedures
  264. To perform system maintenance or schema migration, stop services in reverse order to prevent lockups:
  265. ```bash
  266. # 1. Stop Monitoring Components
  267. docker compose stop zabbix-agent zabbix-web zabbix-server
  268. # 2. Stop Web Frontend and Proxy Gateway
  269. docker compose stop nginx app
  270. # 3. Stop NLP and Search Services
  271. docker compose stop searxng ollama
  272. # 4. Stop Database Container gracefully
  273. docker compose stop mysql
  274. ```
  275. ---
  276. ## 4. Status Verification Commands
  277. Use these commands to verify container state and port bindings:
  278. ```bash
  279. # List all running containers in the stack
  280. docker compose ps
  281. # Inspect raw container logs for error spikes
  282. docker compose logs --tail=100
  283. # Verify TCP socket listener binds
  284. netstat -tulpn | grep -E "80|3307|8081|11434"
  285. ```
  286. """,
  287. "Operator_Installation_Guide.md": """# $Id$
  288. # Local Food AI - Detailed Operator Installation Guide
  289. This document is a step-by-step installation, mapping, configuration, and verification manual for deploying the **Local Food AI** system in an enterprise environment. It covers hybrid hypervisor infrastructure (WSL2, Hyper-V, and VirtualBox), cross-node networking, SNMPv3 monitoring, alert channels, and acceptance testing.
  290. ---
  291. ## 1. Pre-Deployment Operator Survey (Pre-requisites Gathering)
  292. Before running installation scripts, the operator **must** collect the following physical/virtual infrastructure parameters and store them in the deployment matrix:
  293. | REQUIRED PARAMETER | OPERATOR INPUT / DESCRIPTION |
  294. | :--- | :--- |
  295. | **Deployment Workstation IP** | e.g., 192.168.1.50 |
  296. | **Hyper-V Host VM IP** | e.g., 192.168.130.170 |
  297. | **VirtualBox Host VM IP** | e.g., 192.168.130.161 |
  298. | **SSH Key Location (Private)** | e.g., `~/.ssh/id_rsa` |
  299. | **SMTP Relay Password** | e.g., `********` (For Zabbix/App password reset email) |
  300. | **Teams/Discord Webhook URL** | e.g., `https://discord.com/api/webhooks/...` |
  301. ---
  302. ## 2. Platform Mapping: Which Container Goes Where?
  303. To maximize CPU/GPU efficiency and secure database read/writes, services are distributed across three distinct environments:
  304. | COMPONENT CONTAINER | DEPLOYMENT ENVIRONMENT | WHY |
  305. | :--- | :--- | :--- |
  306. | **streamlit-app (app.py)** | Local WSL2 (Windows) | Low-latency rendering and direct client access |
  307. | **mysql (Database Node)** | Hyper-V VM (Server A) | Persistent enterprise-grade disk storage |
  308. | **ollama (NLP Qwen2.5:7b Engine)** | VirtualBox VM (Server B) | Dedicated CPU/GPU virtualization allocation |
  309. | **zabbix-server & web (Monitoring)** | Hyper-V VM (Server A) | Centralized SNMPv3 alert processing and logs |
  310. | **searxng (Meta-Search Gateway)** | Local WSL2 (Windows) | Dynamic browser-level loopbacks |
  311. ---
  312. ## 3. Platform Provisioning Commands
  313. ### 3.1: WSL2 Provisioning (Local Client Workstation)
  314. Enable WSL2 and install Ubuntu 24.04:
  315. ```powershell
  316. # Run in Administrator PowerShell
  317. dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  318. dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
  319. wsl --install -d Ubuntu-24.04
  320. ```
  321. ### 3.2: Hyper-V VM Provisioning (Server A - Database & Zabbix)
  322. Deploy a dedicated Ubuntu VM on Hyper-V using PowerShell:
  323. ```powershell
  324. # Run in Administrator PowerShell on Server A
  325. New-VM -Name "FoodAI-Database-Node" -MemoryStartupBytes 8GB -Generation 2 -NewVHDPath "C:\\VMs\\FoodAI_DB.vhdx" -VHDSizeBytes 80GB -SwitchName "External Switch"
  326. Set-VMFirmware -VMName "FoodAI-Database-Node" -EnableSecureBoot Off
  327. Start-VM -Name "FoodAI-Database-Node"
  328. ```
  329. ### 3.3: VirtualBox VM Provisioning (Server B - Ollama AI Engine)
  330. Deploy a dedicated VM on VirtualBox using Command Line:
  331. ```bash
  332. # Run in Command Prompt on Server B
  333. vboxmanage createvm --name "FoodAI-AI-Node" --ostype "Ubuntu_64" --register
  334. vboxmanage modifyvm "FoodAI-AI-Node" --memory 8192 --cpus 4 --vram 128 --nic1 bridged --bridgeadapter1 "Intel Ethernet Connection"
  335. vboxmanage createhd --filename "C:\\VMs\\FoodAI_AI.vdi" --size 60000
  336. vboxmanage storagectl "FoodAI-AI-Node" --name "SATA Controller" --add sata --controller IntelAHCI
  337. vboxmanage storageattach "FoodAI-AI-Node" --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium "C:\\VMs\\FoodAI_AI.vdi"
  338. vboxmanage startvm "FoodAI-AI-Node" --type headless
  339. ```
  340. ---
  341. ## 4. Secure Authentication & SSH Exchange
  342. Exchange SSH public keys to allow automated, passwordless container management across nodes:
  343. ```bash
  344. # 1. Generate SSH Keys on WSL Client
  345. ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_foodai -N ""
  346. # 2. Push Key to Database VM (Server A)
  347. ssh-copy-id -i ~/.ssh/id_rsa_foodai.pub operator@192.168.130.170
  348. # 3. Push Key to AI VM (Server B)
  349. ssh-copy-id -i ~/.ssh/id_rsa_foodai.pub operator@192.168.130.161
  350. ```
  351. ---
  352. ## 5. Multi-Node Docker Network & Configuration
  353. To allow WSL, Hyper-V, and VirtualBox nodes to communicate, update the `.env` variables and `docker-compose.yml` to use bridged network endpoints.
  354. ### Step 5.1: Configure WSL Client `.env`
  355. Update `.env` in the Streamlit workspace:
  356. ```ini
  357. DB_HOST=192.168.130.170
  358. DB_USER=food_reader
  359. DB_PASS=reader_pass
  360. APP_AUTH_USER=food_app_auth
  361. APP_AUTH_PASS=auth_pass
  362. OLLAMA_HOST=http://192.168.130.161:11434
  363. SEARXNG_HOST=http://localhost:8080
  364. ZBX_SERVER_HOST=192.168.130.170
  365. ```
  366. ### Step 5.2: Configure Ollama (VirtualBox Server B) Listening Port
  367. Ensure the Ollama daemon inside VirtualBox binds to `0.0.0.0` (all interfaces):
  368. ```bash
  369. # SSH into Server B (192.168.130.161)
  370. sudo systemctl edit ollama.service
  371. # Add the environment variables:
  372. [Service]
  373. Environment="OLLAMA_HOST=0.0.0.0"
  374. # Reload and restart service
  375. sudo systemctl daemon-reload
  376. sudo systemctl restart ollama
  377. ```
  378. ---
  379. ## 6. Zabbix Reconfiguration for Multi-Node SNMPv3 Telemetry
  380. To monitor all distributed deployment environments securely:
  381. ### Step 6.1: Deploy SNMPv3 Daemons
  382. Install and configure SNMPv3 daemons on WSL, Hyper-V Database VM, and VirtualBox AI VM:
  383. ```bash
  384. sudo apt update && sudo apt install -y snmpd
  385. ```
  386. Edit `/etc/snmp/snmpd.conf`:
  387. ```
  388. # Listen on all interfaces
  389. agentAddress udp:161
  390. # Create secure SNMPv3 User
  391. createUser securityUser SHA "securityAuthPassword" AES "securityPrivPassword"
  392. rouser securityUser authpriv
  393. ```
  394. Restart daemon:
  395. ```bash
  396. sudo systemctl restart snmpd
  397. ```
  398. ### Step 6.2: Configure Zabbix Server Dashboard (Web UI)
  399. 1. Open Zabbix in your browser at `http://192.168.130.170:8081`.
  400. 2. Navigate to **Configuration > Hosts > Create Host**.
  401. 3. Create three distinct hosts:
  402. - **WSL-Workstation** (IP: `192.168.1.50`)
  403. - **Database-Node** (IP: `192.168.130.170`)
  404. - **AI-Node** (IP: `192.168.130.161`)
  405. 4. Add the **SNMP Interface** pointing to Port 161 for each host.
  406. 5. In the **Security Tab**, select SNMPv3, enter Username `securityUser`, select Auth Protocol `SHA` / `securityAuthPassword`, and Privacy Protocol `AES` / `securityPrivPassword`.
  407. 6. Attach the pre-installed **Local Food AI Telemetry** Template.
  408. ---
  409. ## 7. Verifying Alert Channels
  410. ### 7.1: Microsoft Teams / Discord Alert Webhook
  411. To verify Zabbix is communicating with Discord / Teams:
  412. 1. Trigger a test CPU threshold spike inside WSL:
  413. ```bash
  414. yes > /dev/null & sleep 10 ; killall yes
  415. ```
  416. 2. Verify Zabbix triggers the alert and transmits the notification.
  417. 3. Check your designated channel for the incoming payload:
  418. - Expected Output: `[PROBLEM] High CPU Utilization Detected on WSL-Workstation`.
  419. ### 7.2: Password Reset Email (SMTP Gateway)
  420. 1. In the Streamlit UI Sidebar, select **Reset Password**.
  421. 2. Trigger a reset link for user `ClinicianA`.
  422. 3. Check the inbox or SMTP system log (`tail -f /var/log/mail.log` on Server A) to verify outbound delivery.
  423. ---
  424. ## 8. Operator Post-Installation Checklist
  425. Run these test cases to verify the installation:
  426. | TEST CASE ID | ACTIONS TO PERFORM | EXPECTED RESULTS | STATUS |
  427. | :--- | :--- | :--- | :---: |
  428. | **TC-OP-01** | Search 'Cheese' on Search Tab | 10+ records returned in <0.04s. Listeria warning flags on unpasteurized. | `[ ]` |
  429. | **TC-OP-02** | Enter '1.5 cups' in Plate Tab | Parsed and converted to metric grams based on density index. | `[ ]` |
  430. | **TC-OP-03** | Ask Chat: 'Can I eat sushi?' | llama3.2-vision:11b retrieves database context and flags raw fish as forbidden for pregnancy. | `[ ]` |
  431. | **TC-OP-04** | Trigger manual db backup | Timestamped compressed .sql.gz created inside backups/ folder. | `[ ]` |
  432. | **TC-OP-05** | Terminate Ollama Container | Zabbix PROBLEM active alert generated on dashboard in < 30 seconds. | `[ ]` |
  433. """
  434. }
  435. import subprocess
  436. try:
  437. log_info = subprocess.check_output(['git', 'log', '-1', '--format=%H %an %ae %ad %cn %ce %cd %N %s', '--date=format:%Y/%m/%d %H:%M:%S'], encoding='utf-8').strip()
  438. try:
  439. tag_info = subprocess.check_output(['git', 'describe', '--tags', '--always'], stderr=subprocess.DEVNULL, encoding='utf-8').strip()
  440. except Exception:
  441. tag_info = ""
  442. if tag_info:
  443. git_id = f"$Id$"
  444. else:
  445. git_id = f"$Id$"
  446. except Exception:
  447. git_id = "$Id$"
  448. for filename, content in docs.items():
  449. filepath = os.path.join(docs_dir, filename)
  450. with open(filepath, "w", encoding="utf-8") as f:
  451. f.write(content.replace('$Id$', git_id))
  452. print(f"Generated {filepath}")
  453. print("\nDocs directory perfectly mirrored with operator level runbooks.")