|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * configure-traefik.js |
| 4 | + * |
| 5 | + * Background job script that generates Traefik static configuration and |
| 6 | + * manages the Traefik container lifecycle for a site. |
| 7 | + * |
| 8 | + * Usage: node bin/configure-traefik.js --site-id=<id> |
| 9 | + * |
| 10 | + * The script will: |
| 11 | + * 1. Load site configuration including external domains and transport services |
| 12 | + * 2. Generate Traefik CLI flags for static configuration |
| 13 | + * 3. Create or update the Traefik container: |
| 14 | + * - If container doesn't exist: create it and queue a create-container job |
| 15 | + * - If container exists: update entrypoint and queue a reconfigure-container job |
| 16 | + * |
| 17 | + * All output is logged to STDOUT for capture by the job-runner. |
| 18 | + * Exit code 0 = success, non-zero = failure. |
| 19 | + */ |
| 20 | + |
| 21 | +const path = require('path'); |
| 22 | + |
| 23 | +// Load models from parent directory |
| 24 | +const db = require(path.join(__dirname, '..', 'models')); |
| 25 | +const { Site, Node, Container, Service, TransportService, ExternalDomain, Job } = db; |
| 26 | + |
| 27 | +// Load utilities |
| 28 | +const { parseArgs } = require(path.join(__dirname, '..', 'utils', 'cli')); |
| 29 | +const { |
| 30 | + getBaseUrl, |
| 31 | + getSystemContainerOwner, |
| 32 | + buildTraefikCliFlags |
| 33 | +} = require(path.join(__dirname, '..', 'utils', 'traefik')); |
| 34 | + |
| 35 | +const TRAEFIK_HOSTNAME = 'traefik'; |
| 36 | +const TRAEFIK_IMAGE = 'docker.io/library/traefik:v3.0'; |
| 37 | + |
| 38 | +/** |
| 39 | + * Main function |
| 40 | + */ |
| 41 | +async function main() { |
| 42 | + const args = parseArgs(); |
| 43 | + |
| 44 | + if (!args['site-id']) { |
| 45 | + console.error('Usage: node configure-traefik.js --site-id=<id>'); |
| 46 | + process.exit(1); |
| 47 | + } |
| 48 | + |
| 49 | + const siteId = parseInt(args['site-id'], 10); |
| 50 | + console.log(`Starting Traefik configuration for site ID: ${siteId}`); |
| 51 | + |
| 52 | + // Load site with all necessary associations |
| 53 | + const site = await Site.findByPk(siteId, { |
| 54 | + include: [ |
| 55 | + { |
| 56 | + model: ExternalDomain, |
| 57 | + as: 'externalDomains' |
| 58 | + }, |
| 59 | + { |
| 60 | + model: Node, |
| 61 | + as: 'nodes', |
| 62 | + include: [{ |
| 63 | + model: Container, |
| 64 | + as: 'containers', |
| 65 | + include: [{ |
| 66 | + model: Service, |
| 67 | + as: 'services', |
| 68 | + include: [{ |
| 69 | + model: TransportService, |
| 70 | + as: 'transportService' |
| 71 | + }] |
| 72 | + }] |
| 73 | + }] |
| 74 | + } |
| 75 | + ] |
| 76 | + }); |
| 77 | + |
| 78 | + if (!site) { |
| 79 | + console.error(`Site with ID ${siteId} not found`); |
| 80 | + process.exit(1); |
| 81 | + } |
| 82 | + |
| 83 | + console.log(`Site: ${site.name} (${site.internalDomain})`); |
| 84 | + console.log(`External domains: ${site.externalDomains?.length || 0}`); |
| 85 | + |
| 86 | + // Get base URL for HTTP provider |
| 87 | + const baseUrl = await getBaseUrl(); |
| 88 | + console.log(`Base URL: ${baseUrl}`); |
| 89 | + |
| 90 | + // Build Traefik CLI flags |
| 91 | + const cliFlags = await buildTraefikCliFlags(siteId, site, baseUrl); |
| 92 | + console.log(`Generated ${cliFlags.length} CLI flags`); |
| 93 | + |
| 94 | + // Build entrypoint command |
| 95 | + const entrypoint = `traefik ${cliFlags.join(' ')}`; |
| 96 | + console.log(`Entrypoint: ${entrypoint.substring(0, 100)}...`); |
| 97 | + |
| 98 | + // Build environment variables for Cloudflare DNS challenge |
| 99 | + const envVars = {}; |
| 100 | + for (const domain of site.externalDomains || []) { |
| 101 | + if (domain.cloudflareApiEmail && domain.cloudflareApiKey) { |
| 102 | + envVars['CF_API_EMAIL'] = domain.cloudflareApiEmail; |
| 103 | + envVars['CF_API_KEY'] = domain.cloudflareApiKey; |
| 104 | + break; // Traefik uses global env vars for Cloudflare |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + // Find existing Traefik container for this site |
| 109 | + let traefikContainer = null; |
| 110 | + for (const node of site.nodes || []) { |
| 111 | + const existing = node.containers?.find(c => c.hostname === TRAEFIK_HOSTNAME); |
| 112 | + if (existing) { |
| 113 | + traefikContainer = existing; |
| 114 | + break; |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + if (traefikContainer) { |
| 119 | + console.log(`Found existing Traefik container (ID: ${traefikContainer.id}, Node: ${traefikContainer.nodeId})`); |
| 120 | + |
| 121 | + // Update the container's entrypoint and environment variables |
| 122 | + await traefikContainer.update({ |
| 123 | + entrypoint, |
| 124 | + environmentVars: Object.keys(envVars).length > 0 ? JSON.stringify(envVars) : null |
| 125 | + }); |
| 126 | + console.log('Updated container configuration'); |
| 127 | + |
| 128 | + // Queue a reconfigure job to restart the container |
| 129 | + const reconfigureJob = await Job.create({ |
| 130 | + command: `node bin/reconfigure-container.js --container-id=${traefikContainer.id}`, |
| 131 | + createdBy: 'system', |
| 132 | + serialGroup: `traefik-config-${siteId}` |
| 133 | + }); |
| 134 | + console.log(`Queued reconfigure job ${reconfigureJob.id}`); |
| 135 | + |
| 136 | + } else { |
| 137 | + console.log('No existing Traefik container found, creating new one'); |
| 138 | + |
| 139 | + // Find a node in this site to run the container |
| 140 | + const availableNode = site.nodes?.[0]; |
| 141 | + if (!availableNode) { |
| 142 | + console.error('No nodes available in this site'); |
| 143 | + process.exit(1); |
| 144 | + } |
| 145 | + console.log(`Selected node: ${availableNode.name} (ID: ${availableNode.id})`); |
| 146 | + |
| 147 | + // Get owner for the container |
| 148 | + const owner = await getSystemContainerOwner(); |
| 149 | + if (!owner) { |
| 150 | + console.error('No admin users found to assign as container owner'); |
| 151 | + process.exit(1); |
| 152 | + } |
| 153 | + console.log(`Container owner: ${owner}`); |
| 154 | + |
| 155 | + // Create the container record |
| 156 | + const newContainer = await Container.create({ |
| 157 | + hostname: TRAEFIK_HOSTNAME, |
| 158 | + username: owner, |
| 159 | + status: 'pending', |
| 160 | + template: TRAEFIK_IMAGE, |
| 161 | + nodeId: availableNode.id, |
| 162 | + entrypoint, |
| 163 | + environmentVars: Object.keys(envVars).length > 0 ? JSON.stringify(envVars) : null |
| 164 | + }); |
| 165 | + console.log(`Created container record (ID: ${newContainer.id})`); |
| 166 | + |
| 167 | + // Queue a create-container job |
| 168 | + const createJob = await Job.create({ |
| 169 | + command: `node bin/create-container.js --container-id=${newContainer.id}`, |
| 170 | + createdBy: 'system', |
| 171 | + serialGroup: `traefik-config-${siteId}` |
| 172 | + }); |
| 173 | + console.log(`Queued create-container job ${createJob.id}`); |
| 174 | + |
| 175 | + // Link the creation job to the container |
| 176 | + await newContainer.update({ creationJobId: createJob.id }); |
| 177 | + } |
| 178 | + |
| 179 | + console.log('Traefik configuration completed successfully!'); |
| 180 | + process.exit(0); |
| 181 | +} |
| 182 | + |
| 183 | +// Run the main function |
| 184 | +main().catch(err => { |
| 185 | + console.error('Unhandled error:', err); |
| 186 | + process.exit(1); |
| 187 | +}); |
0 commit comments