├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── entrypoint.sh ├── github └── logo.png ├── html └── loading.html ├── inactivity_monitor.py ├── log_monitor.py ├── nginx └── conf.d │ └── default.conf └── services.yaml /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx:stable-alpine 2 | 3 | # Install required packages 4 | RUN apk add --no-cache \ 5 | docker-cli \ 6 | bash \ 7 | curl \ 8 | yq \ 9 | python3 10 | 11 | # Create required directories and log files 12 | RUN mkdir -p /etc/quantixy /tmp/quantixy_last_access /app /var/log/nginx && \ 13 | touch /var/log/nginx/access.log /var/log/nginx/error.log 14 | 15 | # Copy NGINX configuration 16 | COPY nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf 17 | 18 | # Copy HTML loading page 19 | COPY html/loading.html /usr/share/nginx/html/loading.html 20 | 21 | # Copy the entire html folder 22 | COPY html/ /app/html/ 23 | 24 | # Copy services.yaml 25 | COPY services.yaml /etc/quantixy/services.yaml 26 | 27 | # Copy Python log monitor 28 | COPY log_monitor.py /app/log_monitor.py 29 | 30 | # Copy inactivity monitor 31 | COPY inactivity_monitor.py /app/inactivity_monitor.py 32 | 33 | # Copy entrypoint script and make it executable 34 | COPY entrypoint.sh /entrypoint.sh 35 | RUN chmod +x /entrypoint.sh 36 | 37 | # Expose port 80 38 | EXPOSE 80 39 | 40 | # Run entrypoint script 41 | ENTRYPOINT ["/entrypoint.sh"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Logo 2 | 3 | # Quantixy — Schrödinger’s Proxy 4 | Quantixy is proxy which auto-sleeps and wakes Docker containers when the website is reached. Containers are both running and not running until someone checks. 5 | 6 | ## DOCKER HUB 7 | https://hub.docker.com/r/maskalicz/quantixy 8 | 9 | ``` 10 | services: 11 | quantixy: 12 | image: maskalicz/quantixy:latest 13 | container_name: quantixy 14 | ports: 15 | - 8888:80 16 | volumes: 17 | - /var/run/docker.sock:/var/run/docker.sock 18 | - ./services.yaml:/etc/quantixy/services.yaml 19 | environment: 20 | - TIMEOUT_MINUTES=1 # Time (in minutes) after which containers will shutdown (after inactivity) 21 | - VERBOSE_LOGGING=false 22 | #- LOADING_PAGE_PATH= # If you want custom loading 23 | ``` 24 | 25 | ## Fast-guide for those, who know 26 | - Add service to services.yaml 27 | - In other reverseproxy (preferably NGINX) set servername as domain you want and the proxy_pass to http://quantixy:8888 (or the IP of Quantixy) and you're good to go 28 | 29 | ## 🚀 Features 30 | 31 | - **Auto-start and auto-shutdown**: Go to the website and it autostart the container and after certain time stops it 32 | - **Dynamic Service Routing**: Automatically routes requests to containerized services based on domain configuration 33 | - **Graceful Failover**: Serves a loading page when services are unavailable - starting (502, 503, 504 errors) 34 | - **WebSocket Support**: Built-in support for WebSocket connections 35 | 36 | ## 📋 Prerequisites 37 | 38 | - Docker and Docker Compose 39 | - Access to modify nginx configuration files 40 | 41 | ## 🛠️ Installation 42 | 43 | - Preffered Docker image on Docker Hub 44 | 45 | 1. Clone the repository: 46 | 47 | ```bash 48 | git clone https://github.com/yourusername/quantixy.git 49 | cd quantixy 50 | ``` 51 | 52 | 2. Configure your services in `services.yaml` 53 | 54 | 3. Start the nginx proxy: 55 | 56 | ```bash 57 | docker-compose up -d 58 | ``` 59 | 60 | ## 📁 Project Structure 61 | 62 | ``` 63 | quantixy/ 64 | ├── nginx/ 65 | │ └── conf.d/ 66 | │ └── default.conf # Main nginx configuration 67 | ├── html/ 68 | │ └── loading.html # Fallback loading page 69 | ├── logs/ # Nginx logs directory 70 | ├── services.yaml # Service configuration (planned) 71 | └── README.md 72 | ``` 73 | 74 | ## ⚙️ Configuration 75 | 76 | ### Nginx Configuration 77 | 78 | The main configuration is located in `nginx/conf.d/default.conf` and includes: 79 | 80 | - **Default Server Block**: Handles unmatched requests and serves loading page 81 | - **Health Check Endpoint**: Available at `/health` for monitoring 82 | - **Dynamic Server Blocks**: Generated based on `services.yaml` configuration 83 | 84 | ### Service Configuration 85 | 86 | Services are configured through `services.yaml` (implementation pending). Example structure: 87 | 88 | ```yaml 89 | services: 90 | domain: example.com 91 | container: my_example_app 92 | port: 8000 93 | websocket: false 94 | 95 | domain: ws.example.com 96 | container: my_ws_app 97 | port: 3000 98 | websocket: true 99 | ``` 100 | 101 | ## 🔗 Endpoints 102 | 103 | | Endpoint | Description | 104 | | --------- | --------------------------------------------------------- | 105 | | `/` | Default route - serves configured service or loading page | 106 | | `/health` | Health check endpoint (returns 200 OK) | 107 | 108 | ## 🏗️ Architecture 109 | 110 | Quantixy uses nginx as a reverse proxy to route incoming requests to appropriate Docker containers. When a service is unavailable, it gracefully falls back to a loading page instead of showing error messages to users. 111 | 112 | ### Request Flow 113 | 114 | 1. Client makes request to configured domain 115 | 2. Nginx attempts to proxy to corresponding container 116 | 3. If container is available: Request is forwarded 117 | 4. If container is unavailable: Loading page is served 118 | 119 | ## 🐳 Docker Integration 120 | 121 | The system is designed to work with Docker containers. Each service should: 122 | 123 | - Expose its port internally to the Docker network 124 | - Be accessible by the configured container name 125 | - Handle graceful shutdowns for zero-downtime deployments 126 | 127 | ## 📊 Monitoring 128 | 129 | - Access logs: `/var/log/nginx/access.log` 130 | - Error logs: `/var/log/nginx/error.log` 131 | - Health check: `http://your-domain/health` 132 | 133 | ## 🔧 Development 134 | 135 | ### Adding a New Service 136 | 137 | 1. Add service configuration to `services.yaml` 138 | 2. Regenerate nginx configuration (automation pending) 139 | 3. Reload nginx configuration 140 | 4. Deploy your containerized service 141 | 142 | ### WebSocket Services 143 | 144 | For WebSocket-enabled services, ensure your configuration includes: 145 | 146 | ```nginx 147 | proxy_http_version 1.1; 148 | proxy_set_header Upgrade $http_upgrade; 149 | proxy_set_header Connection "upgrade"; 150 | ``` 151 | 152 | ## 🆘 Troubleshooting 153 | 154 | ### Common Issues 155 | 156 | **Service returns 502 Bad Gateway** 157 | 158 | - Check if the target container is running 159 | - Verify container name matches configuration 160 | - Check container port is correctly exposed 161 | 162 | **Loading page not displaying** 163 | 164 | - Ensure `/usr/share/nginx/html/loading.html` exists 165 | - Check nginx error logs for file permission issues 166 | 167 | **Health check failing** 168 | 169 | - Verify nginx is running 170 | - Check if port 80 is accessible 171 | - Review nginx error logs 172 | 173 | ## 📞 Support 174 | 175 | For support and questions: 176 | 177 | - Open an issue on GitHub 178 | - Check the troubleshooting section above 179 | - Review nginx error logs for detailed error information 180 | 181 | --- 182 | 183 | Built with ❤️ by LNLN (LINE by LINE cooked by Martin Skalicky) 184 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | quantixy: 3 | build: . 4 | container_name: quantixy 5 | ports: 6 | - 8888:80 7 | volumes: 8 | - /var/run/docker.sock:/var/run/docker.sock 9 | - ./services.yaml:/etc/quantixy/services.yaml 10 | environment: 11 | - TIMEOUT_MINUTES=10 12 | - VERBOSE_LOGGING=false 13 | #- LOADING_PAGE_PATH= 14 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Default timeout in minutes 4 | TIMEOUT_MINUTES=${TIMEOUT_MINUTES:-10} 5 | SERVICES_CONFIG="/etc/quantixy/services.yaml" 6 | NGINX_ACCESS_LOG="/var/log/nginx/access.log" 7 | LOADING_PAGE_PATH=${LOADING_PAGE_PATH:-"/usr/share/nginx/html/loading.html"} 8 | VERBOSE_LOGGING=${VERBOSE_LOGGING:-"false"} 9 | 10 | # Export environment variables for the inactivity monitor 11 | export TIMEOUT_MINUTES 12 | export VERBOSE_LOGGING 13 | 14 | # Function to start a container 15 | start_container() { 16 | local domain=$1 17 | local container_name=$(yq e ".${domain}.container" $SERVICES_CONFIG) 18 | local container_port=$(yq e ".${domain}.port" $SERVICES_CONFIG) 19 | 20 | if [ -z "$container_name" ] || [ "$container_name" == "null" ]; then 21 | echo "❌ No container mapping found for domain $domain" 22 | return 23 | fi 24 | 25 | # Write current domain being started to a file for the loading page 26 | echo "$domain" >/usr/share/nginx/html/current_domain.txt 27 | 28 | # Check if container exists (running or stopped) 29 | if docker ps -a -q -f name="^${container_name}$" | grep -q .; then 30 | # Container exists, check if it's running 31 | if ! docker ps -q -f name="^${container_name}$" | grep -q .; then 32 | echo "⚡ STARTING: Container '$container_name'..." 33 | docker start $container_name 34 | if [ $? -eq 0 ]; then 35 | #echo "✅ SUCCESS: Container '$container_name' started successfully for domain '$domain'" 36 | # Give the container a moment to start 37 | sleep 5 38 | else 39 | echo "❌ FAILED: Could not start container '$container_name' for domain '$domain'" 40 | fi 41 | #else 42 | #echo "✅ ALREADY RUNNING: Container '$container_name' is already running for domain '$domain'" 43 | fi 44 | else 45 | echo "❌ ERROR: Container '$container_name' does not exist for domain '$domain'!" 46 | echo "📋 AVAILABLE CONTAINERS:" 47 | docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Image}}" 48 | fi 49 | } 50 | 51 | # Function to stop a container 52 | stop_container() { 53 | local container_name=$1 54 | echo "💤 STOPPING CONTAINER: '$container_name' due to inactivity (timeout: ${TIMEOUT_MINUTES} minutes)" 55 | docker stop $container_name 56 | if [ $? -eq 0 ]; then 57 | echo "✅ STOPPED: Container '$container_name' stopped successfully" 58 | else 59 | echo "❌ STOP FAILED: Could not stop container '$container_name'" 60 | fi 61 | } 62 | 63 | # Create a timestamp file for each service to track last access 64 | touch_last_access_file() { 65 | local domain=$1 66 | local container_name=$(yq e ".${domain}.container" $SERVICES_CONFIG) 67 | if [ -n "$container_name" ] && [ "$container_name" != "null" ]; then 68 | mkdir -p /tmp/quantixy_last_access 69 | touch "/tmp/quantixy_last_access/${container_name}" 70 | fi 71 | } 72 | 73 | # Function to generate NGINX config from services.yaml 74 | generate_nginx_config() { 75 | local config_file="/etc/nginx/conf.d/default.conf" 76 | 77 | # Create the main config with log format 78 | cat >"/etc/nginx/nginx.conf" <<'EOF' 79 | user nginx; 80 | worker_processes auto; 81 | error_log /var/log/nginx/error.log notice; 82 | pid /var/run/nginx.pid; 83 | 84 | events { 85 | worker_connections 1024; 86 | } 87 | 88 | http { 89 | include /etc/nginx/mime.types; 90 | default_type application/octet-stream; 91 | 92 | # Custom log format to include host 93 | log_format main_with_host '$remote_addr - $remote_user [$time_local] "$request" ' 94 | '$status $body_bytes_sent "$http_referer" ' 95 | '"$http_user_agent" "$host"'; 96 | 97 | sendfile on; 98 | tcp_nopush on; 99 | keepalive_timeout 65; 100 | gzip on; 101 | 102 | include /etc/nginx/conf.d/*.conf; 103 | } 104 | EOF 105 | 106 | # Start with the default server block 107 | cat >"$config_file" <<'EOF' 108 | server { 109 | listen 80 default_server; 110 | server_name _; 111 | 112 | access_log /var/log/nginx/access.log main_with_host; 113 | error_log /var/log/nginx/error.log; 114 | 115 | # Default location - serve loading page 116 | location / { 117 | root /usr/share/nginx/html; 118 | try_files /loading.html =404; 119 | } 120 | 121 | # Health check endpoint 122 | location /health { 123 | access_log off; 124 | return 200 "OK\n"; 125 | add_header Content-Type text/plain; 126 | } 127 | } 128 | 129 | EOF 130 | 131 | # Generate server blocks for each domain in services.yaml 132 | #echo "🔧 DEBUG: Reading domains from services.yaml..." 133 | #echo "🔧 DEBUG: Services config content:" 134 | #cat "$SERVICES_CONFIG" 135 | 136 | # Use a temporary file to build the dynamic configs 137 | temp_config="/tmp/dynamic_servers.conf" 138 | >"$temp_config" # Clear temp file 139 | 140 | # Get all domains and process them 141 | yq e 'keys | .[]' $SERVICES_CONFIG | while IFS= read -r domain; do 142 | if [ -n "$domain" ]; then 143 | #echo "🔧 DEBUG: Processing domain: '$domain'" 144 | container_name=$(yq e ".[\"${domain}\"].container" $SERVICES_CONFIG) 145 | port=$(yq e ".[\"${domain}\"].port" $SERVICES_CONFIG) 146 | protocol=$(yq e ".[\"${domain}\"].protocol // \"http\"" $SERVICES_CONFIG) 147 | websocket=$(yq e ".[\"${domain}\"].websocket // false" $SERVICES_CONFIG) 148 | 149 | #echo "🔧 DEBUG: Domain '$domain' -> container: '$container_name', port: '$port'" 150 | 151 | if [ -n "$container_name" ] && [ "$container_name" != "null" ]; then 152 | #echo "Generating NGINX config for domain: $domain -> $container_name:$port" 153 | 154 | cat >>"$temp_config" <>"$temp_config" <<'EOF' 180 | # WebSocket support 181 | proxy_http_version 1.1; 182 | proxy_set_header Upgrade $http_upgrade; 183 | proxy_set_header Connection "upgrade"; 184 | 185 | EOF 186 | fi 187 | 188 | cat >>"$temp_config" <<'EOF' 189 | # Connection settings with shorter timeouts for faster failover 190 | proxy_connect_timeout 2s; 191 | proxy_send_timeout 10s; 192 | proxy_read_timeout 10s; 193 | 194 | # Don't cache anything 195 | proxy_no_cache 1; 196 | proxy_cache_bypass 1; 197 | add_header Cache-Control "no-cache, no-store, must-revalidate"; 198 | add_header Pragma "no-cache"; 199 | add_header Expires "0"; 200 | 201 | # If proxy fails, serve loading page 202 | proxy_intercept_errors on; 203 | error_page 502 503 504 @loading; 204 | } 205 | 206 | # Loading page fallback for this domain 207 | location @loading { 208 | root /usr/share/nginx/html; 209 | try_files /loading.html =404; 210 | } 211 | } 212 | 213 | EOF 214 | #echo "✅ Successfully generated config for: $domain" 215 | #else 216 | #echo "❌ No container found for domain: $domain" 217 | fi 218 | fi 219 | done 220 | 221 | # Append the dynamic configs to the main config file 222 | if [ -f "$temp_config" ] && [ -s "$temp_config" ]; then 223 | echo "🔧 DEBUG: Appending dynamic configs to main config file" 224 | cat "$temp_config" >>"$config_file" 225 | rm "$temp_config" 226 | #echo "✅ Successfully generated dynamic configurations" 227 | #else 228 | #echo "❌ No dynamic configurations were generated" 229 | fi 230 | } 231 | 232 | # Generate NGINX configuration from services.yaml 233 | echo "Generating NGINX configuration from services.yaml..." 234 | generate_nginx_config 235 | 236 | # Ensure log file exists before starting NGINX 237 | touch $NGINX_ACCESS_LOG 238 | 239 | # Remove the symlink and create a real log file 240 | if [ -L "$NGINX_ACCESS_LOG" ]; then 241 | rm "$NGINX_ACCESS_LOG" 242 | touch "$NGINX_ACCESS_LOG" 243 | fi 244 | 245 | # Initialize NGINX - this will also create the log file if it doesn't exist 246 | nginx -g 'daemon off;' & 247 | NGINX_PID=$! 248 | echo "NGINX started with PID $NGINX_PID" 249 | 250 | # Give Nginx a moment to fully initialize 251 | sleep 5 252 | 253 | # Force reload NGINX to ensure fresh config 254 | nginx -s reload 255 | echo "NGINX configuration reloaded" 256 | 257 | echo "Monitoring NGINX access log: $NGINX_ACCESS_LOG" 258 | echo "Services configuration: $SERVICES_CONFIG" 259 | echo "Timeout set to: $TIMEOUT_MINUTES minutes" 260 | 261 | # Initialize last access times for all configured containers 262 | yq e 'keys | .[]' $SERVICES_CONFIG | while read domain; do 263 | touch_last_access_file "$domain" 264 | done 265 | 266 | # Start periodic container cleanup in background 267 | ( 268 | while true; do 269 | sleep 60 # Check every minute 270 | # Iterate over configured domains 271 | yq e 'keys | .[]' $SERVICES_CONFIG | while read domain; do 272 | container_name=$(yq e ".${domain}.container" $SERVICES_CONFIG) 273 | if [ -z "$container_name" ] || [ "$container_name" == "null" ]; then 274 | continue 275 | fi 276 | 277 | # Check if container is running 278 | if docker ps -q -f name="^${container_name}$" | grep -q .; then 279 | last_access_file="/tmp/quantixy_last_access/${container_name}" 280 | if [ -f "$last_access_file" ]; then 281 | last_access_time=$(stat -c %Y "$last_access_file") 282 | current_time=$(date +%s) 283 | inactive_time=$(((current_time - last_access_time) / 60)) 284 | 285 | if [ "$inactive_time" -ge "$TIMEOUT_MINUTES" ]; then 286 | echo "🔍 TIMEOUT CHECK: Container '$container_name' for domain '$domain' has been inactive for $inactive_time minutes (limit: $TIMEOUT_MINUTES)" 287 | stop_container "$container_name" 288 | else 289 | echo "⏰ ACTIVITY CHECK: Container '$container_name' for domain '$domain' is active (last access: $inactive_time minutes ago)" 290 | fi 291 | else 292 | # If last access file doesn't exist but container is running, 293 | # it might have been started manually or an edge case. 294 | # We'll create the access file to start tracking. 295 | echo "📝 CREATING TRACKING: Last access file for container '$container_name' (domain: '$domain') not found. Creating it now." 296 | touch_last_access_file "$domain" 297 | fi 298 | fi 299 | done 300 | done 301 | ) & 302 | 303 | # Start Python log monitoring (replacing bash monitoring) 304 | echo "🔍 Starting Python log monitoring..." 305 | python3 /app/log_monitor.py & 306 | 307 | # Start inactivity monitor in background 308 | echo "Starting inactivity monitor (timeout: ${TIMEOUT_MINUTES} minutes, verbose: ${VERBOSE_LOGGING})..." 309 | python3 /app/inactivity_monitor.py & 310 | 311 | echo "Timeout set to: $TIMEOUT_MINUTES minutes" 312 | echo "Verbose logging: $VERBOSE_LOGGING" 313 | echo "🪄 Quantixy is now running" 314 | 315 | # Keep the container running 316 | if [ "$VERBOSE_LOGGING" = "true" ]; then 317 | # Show nginx logs in verbose mode 318 | tail -f /var/log/nginx/access.log 319 | else 320 | # Keep container alive without showing logs 321 | while true; do 322 | sleep 3600 # Sleep for 1 hour, then repeat 323 | done 324 | fi 325 | -------------------------------------------------------------------------------- /github/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maskalix/quantixy/f14769cafd7ef5a4ec081b0dfae251b4c8e98415/github/logo.png -------------------------------------------------------------------------------- /html/loading.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Quantixy 7 | 11 | 12 | 13 | 17 | 218 | 219 | 220 |
221 |
222 | 229 | 235 | 240 | 241 | 242 | 243 |

Quantixy

244 | 245 |
246 |
247 | Starting services for: 248 | loading... 249 |
250 |
251 | Reloads in 8 seconds... 252 |
253 |
254 | 255 | 258 | 259 | 433 | 434 | 435 | -------------------------------------------------------------------------------- /inactivity_monitor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Inactivity Monitor for Quantixy 4 | 5 | This script monitors service inactivity and shuts down containers 6 | after a specified timeout period (TIMEOUT_MINUTES). 7 | 8 | The script runs independently in the background and does not rely on any user interaction. 9 | """ 10 | 11 | import os 12 | import time 13 | import logging 14 | import subprocess 15 | import datetime 16 | import sys 17 | from pathlib import Path 18 | 19 | # Configure logging based on VERBOSE_LOGGING environment variable 20 | VERBOSE_LOGGING = os.environ.get('VERBOSE_LOGGING', 'false').lower() in ('true', '1', 'yes') 21 | 22 | log_level = logging.INFO if VERBOSE_LOGGING else logging.WARNING 23 | 24 | logging.basicConfig( 25 | level=log_level, 26 | format='%(asctime)s - %(levelname)s - %(message)s', 27 | handlers=[logging.StreamHandler(sys.stdout)] 28 | ) 29 | logger = logging.getLogger('inactivity_monitor') 30 | 31 | # Configuration 32 | TIMEOUT_MINUTES = int(os.environ.get('TIMEOUT_MINUTES', '10')) 33 | LAST_ACCESS_DIR = Path('/tmp/quantixy_last_access') 34 | CHECK_INTERVAL = 30 # Check half minute 35 | SERVICES_CONFIG = '/etc/quantixy/services.yaml' 36 | 37 | if VERBOSE_LOGGING: 38 | logger.info(f"Inactivity monitor started with timeout: {TIMEOUT_MINUTES} minutes") 39 | logger.info(f"Verbose logging enabled: {VERBOSE_LOGGING}") 40 | else: 41 | logger.warning(f"Inactivity monitor started (timeout: {TIMEOUT_MINUTES}m, verbose: {VERBOSE_LOGGING})") 42 | 43 | def get_containers(): 44 | """Get list of container names from services.yaml using yq""" 45 | try: 46 | result = subprocess.run( 47 | ['yq', 'e', ".* | select(has(\"container\")) | .container", SERVICES_CONFIG], 48 | capture_output=True, text=True, check=True 49 | ) 50 | containers = [c.strip() for c in result.stdout.splitlines() if c.strip()] 51 | return containers 52 | except subprocess.CalledProcessError as e: 53 | logger.error(f"Failed to read containers: {e}") 54 | return [] 55 | 56 | def check_container_running(container_name): 57 | """Check if container is running using docker CLI""" 58 | try: 59 | result = subprocess.run( 60 | ['docker', 'ps', '-q', '-f', f'name=^{container_name}$'], 61 | capture_output=True, text=True, check=True 62 | ) 63 | return bool(result.stdout.strip()) 64 | except subprocess.CalledProcessError as e: 65 | logger.error(f"Failed to check container {container_name}: {e}") 66 | return False 67 | 68 | def get_last_activity(container_name): 69 | """Get timestamp of last container activity""" 70 | last_access_file = LAST_ACCESS_DIR / container_name 71 | if not last_access_file.exists(): 72 | return None 73 | 74 | try: 75 | # Get file modification time 76 | mtime = last_access_file.stat().st_mtime 77 | return datetime.datetime.fromtimestamp(mtime) 78 | except Exception as e: 79 | logger.error(f"Error getting last activity for {container_name}: {e}") 80 | return None 81 | 82 | def stop_container(container_name): 83 | """Stop a container due to inactivity""" 84 | try: 85 | logger.info(f"Stopping container {container_name} due to inactivity (timeout: {TIMEOUT_MINUTES} minutes)") 86 | subprocess.run(['docker', 'stop', container_name], check=True) 87 | logger.info(f"Container {container_name} stopped successfully") 88 | except subprocess.CalledProcessError as e: 89 | logger.error(f"Failed to stop container {container_name}: {e}") 90 | 91 | def main(): 92 | """Main monitoring loop""" 93 | # Ensure last access directory exists 94 | LAST_ACCESS_DIR.mkdir(exist_ok=True, parents=True) 95 | 96 | # Main monitoring loop 97 | while True: 98 | now = datetime.datetime.now() 99 | containers = get_containers() 100 | 101 | for container in containers: 102 | # Only check running containers 103 | if check_container_running(container): 104 | last_activity = get_last_activity(container) 105 | 106 | # If no activity record exists, create one and continue 107 | if not last_activity: 108 | logger.info(f"No activity record for {container}, creating one") 109 | (LAST_ACCESS_DIR / container).touch() 110 | continue 111 | # Calculate inactivity duration 112 | inactive_minutes = (now - last_activity).total_seconds() / 60 113 | 114 | # Log for monitoring - only when verbose logging is enabled 115 | if inactive_minutes > TIMEOUT_MINUTES / 2 and VERBOSE_LOGGING: 116 | logger.info(f"Container {container} inactive for {inactive_minutes:.1f} minutes (timeout: {TIMEOUT_MINUTES})") 117 | 118 | # Stop container if inactive for too long 119 | if inactive_minutes >= TIMEOUT_MINUTES: 120 | stop_container(container) 121 | 122 | # Wait for next check 123 | time.sleep(CHECK_INTERVAL) 124 | 125 | if __name__ == "__main__": 126 | try: 127 | main() 128 | except KeyboardInterrupt: 129 | logger.info("Inactivity monitor stopped") 130 | except Exception as e: 131 | logger.error(f"Error in inactivity monitor: {e}", exc_info=True) -------------------------------------------------------------------------------- /log_monitor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import time 3 | import subprocess 4 | import re 5 | import os 6 | import sys 7 | from pathlib import Path 8 | 9 | # Configuration 10 | SERVICES_CONFIG = "/etc/quantixy/services.yaml" 11 | NGINX_ACCESS_LOG = "/var/log/nginx/access.log" 12 | TIMEOUT_MINUTES = int(os.getenv('TIMEOUT_MINUTES', '10')) 13 | 14 | def load_services_config(): 15 | """Load and return the services configuration from YAML using yq""" 16 | try: 17 | print("🔧 Loading services config using yq...") 18 | # Use yq to get just the domain names first 19 | result = subprocess.run(['yq', 'e', 'keys | .[]', SERVICES_CONFIG], 20 | capture_output=True, text=True, timeout=10) 21 | if result.returncode != 0: 22 | print(f"❌ Failed to read domain keys: {result.stderr}") 23 | return {} 24 | 25 | domains = [line.strip() for line in result.stdout.split('\n') if line.strip()] 26 | print(f"📋 Found domains: {domains}") 27 | 28 | config = {} 29 | for domain in domains: 30 | # Get container name for this domain 31 | result = subprocess.run(['yq', 'e', f'."{domain}".container', SERVICES_CONFIG], 32 | capture_output=True, text=True, timeout=5) 33 | if result.returncode == 0 and result.stdout.strip(): 34 | container = result.stdout.strip() 35 | 36 | # Get port for this domain 37 | result = subprocess.run(['yq', 'e', f'."{domain}".port', SERVICES_CONFIG], 38 | capture_output=True, text=True, timeout=5) 39 | port = result.stdout.strip() if result.returncode == 0 else '80' 40 | 41 | config[domain] = { 42 | 'container': container, 43 | 'port': port 44 | } 45 | print(f" {domain} -> {container}:{port}") 46 | 47 | return config 48 | except Exception as e: 49 | print(f"❌ Failed to load services config: {e}") 50 | import traceback 51 | traceback.print_exc() 52 | return {} 53 | 54 | def start_container(domain, services_config): 55 | """Start a container for the given domain""" 56 | if domain not in services_config: 57 | print(f"❌ Domain {domain} not found in services config") 58 | return False 59 | 60 | container_name = services_config[domain].get('container') 61 | if not container_name: 62 | print(f"❌ No container mapping found for domain {domain}") 63 | return False 64 | 65 | #print(f"🚀 ATTEMPTING TO START: Container '{container_name}' for domain '{domain}'") 66 | 67 | # Write current domain being started to a file for the loading page 68 | try: 69 | with open('/usr/share/nginx/html/current_domain.txt', 'w') as f: 70 | f.write(domain) 71 | except Exception as e: 72 | print(f"⚠️ Could not write current domain file: {e}") 73 | 74 | # Check if container exists 75 | try: 76 | result = subprocess.run(['docker', 'ps', '-a', '-q', '-f', f'name=^{container_name}$'], 77 | capture_output=True, text=True) 78 | if not result.stdout.strip(): 79 | print(f"❌ ERROR: Container '{container_name}' does not exist for domain '{domain}'!") 80 | return False 81 | 82 | # Check if container is running 83 | result = subprocess.run(['docker', 'ps', '-q', '-f', f'name=^{container_name}$'], 84 | capture_output=True, text=True) 85 | if result.stdout.strip(): 86 | #print(f"✅ ALREADY RUNNING: Container '{container_name}' is already running for domain '{domain}'") 87 | return True 88 | 89 | # Container exists but is stopped, start it 90 | #print(f"📦 CONTAINER STATUS: '{container_name}' exists but is stopped") 91 | #print(f"⚡ STARTING: Container '{container_name}'...") 92 | 93 | result = subprocess.run(['docker', 'start', container_name], 94 | capture_output=True, text=True) 95 | if result.returncode == 0: 96 | #print(f"✅ SUCCESS: Container '{container_name}' started successfully for domain '{domain}'") 97 | return True 98 | else: 99 | print(f"❌ FAILED: Could not start container '{container_name}' for domain '{domain}'") 100 | print(f"Error: {result.stderr}") 101 | return False 102 | 103 | except Exception as e: 104 | print(f"❌ Error checking/starting container: {e}") 105 | return False 106 | 107 | def touch_last_access_file(domain, services_config): 108 | """Update the last access time for a domain's container""" 109 | if domain not in services_config: 110 | return 111 | 112 | container_name = services_config[domain].get('container') 113 | if not container_name: 114 | return 115 | 116 | try: 117 | access_dir = Path('/tmp/quantixy_last_access') 118 | access_dir.mkdir(exist_ok=True) 119 | access_file = access_dir / container_name 120 | access_file.touch() 121 | except Exception as e: 122 | print(f"⚠️ Could not update last access file: {e}") 123 | 124 | def extract_host_from_log_line(line): 125 | """Extract the host from NGINX log line with custom format""" 126 | # The host is the last field in quotes 127 | match = re.search(r'"([^"]+)"$', line) 128 | if match: 129 | return match.group(1) 130 | return None 131 | 132 | def monitor_logs(): 133 | """Monitor NGINX access logs and start containers on demand""" 134 | print("🔍 Starting Python log monitoring...") 135 | print(f"🔧 Python version: {sys.version}") 136 | 137 | # Test subprocess 138 | try: 139 | result = subprocess.run(['yq', '--version'], capture_output=True, text=True, timeout=5) 140 | print(f"✅ yq version: {result.stdout.strip()}") 141 | except Exception as e: 142 | print(f"❌ yq test failed: {e}") 143 | 144 | # Load services configuration 145 | print("📋 Loading services configuration...") 146 | services_config = load_services_config() 147 | if not services_config: 148 | print("❌ No services configuration found, exiting") 149 | return 150 | 151 | print("✅ Services config loaded:") 152 | for domain, config in services_config.items(): 153 | container = config.get('container', 'unknown') 154 | port = config.get('port', 'unknown') 155 | print(f" {domain} -> {container}:{port}") 156 | 157 | # Check if log file exists 158 | log_file = Path(NGINX_ACCESS_LOG) 159 | if not log_file.exists(): 160 | print(f"⏳ Waiting for log file {NGINX_ACCESS_LOG} to be created...") 161 | while not log_file.exists(): 162 | time.sleep(1) 163 | 164 | print(f"📝 Monitoring {NGINX_ACCESS_LOG} for new entries...") 165 | 166 | # Track last position in file 167 | last_position = log_file.stat().st_size 168 | 169 | while True: 170 | try: 171 | current_size = log_file.stat().st_size 172 | 173 | if current_size > last_position: 174 | # New content added to file 175 | with open(log_file, 'r') as f: 176 | f.seek(last_position) 177 | new_lines = f.readlines() 178 | 179 | for line in new_lines: 180 | line = line.strip() 181 | if not line: 182 | continue 183 | 184 | #print(f"📝 Log entry: {line}") 185 | 186 | # Extract host from log line 187 | host = extract_host_from_log_line(line) 188 | if not host: 189 | print("⚠️ Could not extract host from log line") 190 | continue 191 | 192 | #print(f"🌐 DOMAIN DETECTED: {host}") 193 | 194 | # Check if domain is configured 195 | if host in services_config: 196 | #print(f"✅ CONFIGURED DOMAIN: {host} is configured in services.yaml") 197 | container_name = services_config[host].get('container') 198 | #print(f"🐳 STARTING CONTAINER: {container_name} for domain {host}") 199 | 200 | # Start the container 201 | if start_container(host, services_config): 202 | touch_last_access_file(host, services_config) 203 | 204 | # Check for 502 errors 205 | if ' 502 ' in line: 206 | print(f"🚨 502 ERROR detected for host: {host}") 207 | print(f"🔄 RETRY STARTING CONTAINER: {container_name} for domain {host}") 208 | start_container(host, services_config) 209 | else: 210 | print(f"❌ UNCONFIGURED DOMAIN: {host} is not configured in services.yaml") 211 | 212 | last_position = current_size 213 | 214 | time.sleep(0.5) # Check every 500ms 215 | 216 | except Exception as e: 217 | print(f"❌ Error monitoring logs: {e}") 218 | time.sleep(5) # Wait before retrying 219 | 220 | if __name__ == "__main__": 221 | try: 222 | print("🐍 Python log monitor starting...") 223 | print(f"📁 Working directory: {os.getcwd()}") 224 | print(f"📄 Services config path: {SERVICES_CONFIG}") 225 | print(f"📄 Access log path: {NGINX_ACCESS_LOG}") 226 | 227 | # Test if files exist 228 | if os.path.exists(SERVICES_CONFIG): 229 | print(f"✅ Services config file exists") 230 | else: 231 | print(f"❌ Services config file does not exist!") 232 | 233 | if os.path.exists(NGINX_ACCESS_LOG): 234 | print(f"✅ Access log file exists") 235 | else: 236 | print(f"❌ Access log file does not exist!") 237 | 238 | monitor_logs() 239 | except Exception as e: 240 | print(f"💥 FATAL ERROR in Python monitor: {e}") 241 | import traceback 242 | traceback.print_exc() 243 | sys.exit(1) -------------------------------------------------------------------------------- /nginx/conf.d/default.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80 default_server; 3 | server_name _; 4 | 5 | # Enable access logging 6 | access_log /var/log/nginx/access.log; 7 | error_log /var/log/nginx/error.log; 8 | 9 | # Default location - serve loading page for any unmatched requests 10 | location / { 11 | try_files $uri @loading; 12 | } # Loading page fallback 13 | location @loading { 14 | root /usr/share/nginx/html; 15 | add_header Content-Type text/html; 16 | add_header Cache-Control "no-cache, no-store, must-revalidate"; 17 | try_files /loading.html =500; 18 | } 19 | 20 | # Health check endpoint 21 | location /health { 22 | access_log off; 23 | return 200 "OK\n"; 24 | add_header Content-Type text/plain; 25 | } 26 | } 27 | 28 | # Dynamic server blocks will be generated based on services.yaml 29 | # This is a placeholder - in a real implementation, you would generate 30 | # server blocks dynamically or use a more sophisticated approach 31 | 32 | # Example server block for a configured domain: 33 | # server { 34 | # listen 80; 35 | # server_name example.com; 36 | # 37 | # access_log /var/log/nginx/access.log; 38 | # error_log /var/log/nginx/error.log; 39 | # 40 | # location / { 41 | # # Try to proxy to the container 42 | # proxy_pass http://my_example_app:8000; 43 | # proxy_set_header Host $host; 44 | # proxy_set_header X-Real-IP $remote_addr; 45 | # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 46 | # proxy_set_header X-Forwarded-Proto $scheme; 47 | # 48 | # # Connection settings 49 | # proxy_connect_timeout 5s; 50 | # proxy_send_timeout 60s; 51 | # proxy_read_timeout 60s; 52 | # 53 | # # If proxy fails, serve loading page 54 | # proxy_intercept_errors on; 55 | # error_page 502 503 504 @loading; 56 | # } 57 | # 58 | # # Loading page fallback for this domain 59 | # location @loading { 60 | # root /usr/share/nginx/html; 61 | # try_files /loading.html =404; 62 | # } 63 | # } 64 | # Example WebSocket-enabled server block: 65 | # server { 66 | # listen 80; 67 | # server_name ws.example.com; 68 | # 69 | # access_log /var/log/nginx/access.log; 70 | # error_log /var/log/nginx/error.log; 71 | # 72 | # location / { 73 | # proxy_pass http://my_ws_app:3000; 74 | # proxy_set_header Host $host; 75 | # proxy_set_header X-Real-IP $remote_addr; 76 | # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 77 | # proxy_set_header X-Forwarded-Proto $scheme; 78 | # 79 | # # WebSocket support 80 | # proxy_http_version 1.1; 81 | # proxy_set_header Upgrade $http_upgrade; 82 | # proxy_set_header Connection "upgrade"; 83 | # 84 | # # Connection settings 85 | # proxy_connect_timeout 5s; 86 | # proxy_send_timeout 60s; 87 | # proxy_read_timeout 60s; 88 | # 89 | # # If proxy fails, serve loading page 90 | # proxy_intercept_errors on; 91 | # error_page 502 503 504 @loading; 92 | # } 93 | # 94 | # # Loading page fallback for this domain 95 | # location @loading { 96 | # root /usr/share/nginx/html; 97 | # try_files /loading.html =404; 98 | # } 99 | # } 100 | -------------------------------------------------------------------------------- /services.yaml: -------------------------------------------------------------------------------- 1 | domain.tld: 2 | container: name 3 | port: 1234 4 | protocol: http # https 5 | websocket: true # false 6 | --------------------------------------------------------------------------------