UNPKG

@deploystack/docker-to-iac

Version:

Translate docker run and docker compose file to Infrastructure as Code

380 lines (379 loc) 18.2 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.runTest2 = runTest2; const index_1 = require("../../src/index"); const base_parser_1 = require("../../src/parsers/base-parser"); const fs_1 = require("fs"); const path_1 = require("path"); const yaml = __importStar(require("yaml")); const render_1 = require("./assertions/render"); const port_assertions_1 = require("./assertions/port-assertions"); const digitalocean_1 = require("./assertions/digitalocean"); const do_port_assertions_1 = require("./assertions/do-port-assertions"); // Constants for directories const DOCKER_RUN_DIR = (0, path_1.join)(__dirname, 'docker-run-files'); const DOCKER_COMPOSE_DIR = (0, path_1.join)(__dirname, 'docker-compose-files'); const OUTPUT_DIR = (0, path_1.join)(__dirname, 'output'); /** * Run the port mapping test using Docker run command */ async function runDockerRunPortTest() { console.log('\n--- Running Docker Run Port Mapping Test ---'); // Create output directory for this subtest const testOutputDir = (0, path_1.join)(OUTPUT_DIR, 'test2', 'docker-run'); if (!(0, fs_1.existsSync)(testOutputDir)) { (0, fs_1.mkdirSync)(testOutputDir, { recursive: true }); } let testPassed = true; try { // Read and normalize the docker run command const dockerRunPath = (0, path_1.join)(DOCKER_RUN_DIR, 'test2.txt'); const command = (0, fs_1.readFileSync)(dockerRunPath, 'utf8') .replace(/\\\n/g, ' ') // Remove line continuations .replace(/\s+/g, ' ') // Normalize whitespace .trim(); // Remove leading/trailing whitespace console.log(`Running test for command: ${command}`); // Test translation to Render console.log('Testing translation to Render...'); const renderTranslationResult = (0, index_1.translate)(command, { source: 'run', target: 'RND', templateFormat: base_parser_1.TemplateFormat.yaml }); // Create directory for Render output const renderOutputDir = (0, path_1.join)(testOutputDir, 'rnd'); if (!(0, fs_1.existsSync)(renderOutputDir)) { (0, fs_1.mkdirSync)(renderOutputDir, { recursive: true }); } // Save all files with proper directory structure Object.entries(renderTranslationResult.files).forEach(([path, fileData]) => { const fullPath = (0, path_1.join)(renderOutputDir, path); const dir = (0, path_1.dirname)(fullPath); if (!(0, fs_1.existsSync)(dir)) { (0, fs_1.mkdirSync)(dir, { recursive: true }); } (0, fs_1.writeFileSync)(fullPath, fileData.content); console.log(`✓ Created Render output: ${path}`); }); // Run assertions for Render const renderYamlPath = (0, path_1.join)(renderOutputDir, 'render.yaml'); if ((0, fs_1.existsSync)(renderYamlPath)) { const renderYaml = yaml.parse((0, fs_1.readFileSync)(renderYamlPath, 'utf8')); try { // 1. Validate YAML structure (0, render_1.assertRenderYamlStructure)(renderYaml); console.log('✓ Render YAML structure validation passed'); // 2. Check for port mapping via PORT env var - Docker run creates a service named 'default' const portMappingValid = (0, port_assertions_1.validatePortEnvironmentVariable)(renderYaml, 'default', '8080'); if (portMappingValid) { console.log('✓ Port mapping validation passed'); } else { testPassed = false; console.error('❌ Port mapping validation failed'); } } catch (error) { testPassed = false; console.error('❌ Render YAML validation failed:', error); } } else { testPassed = false; console.error('❌ Render YAML file not found'); } // Test translation to DigitalOcean console.log('\nTesting translation to DigitalOcean...'); const doTranslationResult = (0, index_1.translate)(command, { source: 'run', target: 'DOP', templateFormat: base_parser_1.TemplateFormat.yaml }); // Create directory for DigitalOcean output const doOutputDir = (0, path_1.join)(testOutputDir, 'dop'); if (!(0, fs_1.existsSync)(doOutputDir)) { (0, fs_1.mkdirSync)(doOutputDir, { recursive: true }); } // Save all files with proper directory structure Object.entries(doTranslationResult.files).forEach(([path, fileData]) => { const fullPath = (0, path_1.join)(doOutputDir, path); const dir = (0, path_1.dirname)(fullPath); if (!(0, fs_1.existsSync)(dir)) { (0, fs_1.mkdirSync)(dir, { recursive: true }); } (0, fs_1.writeFileSync)(fullPath, fileData.content); console.log(`✓ Created DigitalOcean output: ${path}`); }); // Run assertions for DigitalOcean const doYamlPath = (0, path_1.join)(doOutputDir, '.do/deploy.template.yaml'); if ((0, fs_1.existsSync)(doYamlPath)) { const doYaml = yaml.parse((0, fs_1.readFileSync)(doYamlPath, 'utf8')); try { // 1. Validate YAML structure (0, digitalocean_1.assertDigitalOceanYamlStructure)(doYaml); console.log('✓ DigitalOcean YAML structure validation passed'); // 2. Check for port mapping - service name may be different due to DO naming requirements const serviceName = doYaml.spec.services[0].name; // In DigitalOcean, the http_port should be set to 8080 const portMappingValid = (0, do_port_assertions_1.validatePortMappingInDigitalOcean)(doYaml, serviceName, 8080); if (portMappingValid) { console.log('✓ DigitalOcean port mapping validation passed'); } else { // Check if there's a PORT environment variable as a fallback const portEnvValid = (0, do_port_assertions_1.validatePortEnvironmentVariable)(doYaml, serviceName, '8080'); if (portEnvValid) { console.log('✓ DigitalOcean PORT environment variable validation passed'); } else { testPassed = false; console.error('❌ DigitalOcean port mapping validation failed'); } } } catch (error) { testPassed = false; console.error('❌ DigitalOcean YAML validation failed:', error); } } else { testPassed = false; console.error('❌ DigitalOcean YAML file not found'); } } catch (error) { testPassed = false; console.error('❌ Test execution error:', error); } console.log(`--- Docker Run Port Test ${testPassed ? 'PASSED ✓' : 'FAILED ❌'} ---`); return testPassed; } /** * Run the port mapping test using Docker Compose */ async function runDockerComposePortTest() { console.log('\n--- Running Docker Compose Port Mapping Test ---'); // Create output directory for this subtest const testOutputDir = (0, path_1.join)(OUTPUT_DIR, 'test2', 'docker-compose'); if (!(0, fs_1.existsSync)(testOutputDir)) { (0, fs_1.mkdirSync)(testOutputDir, { recursive: true }); } let testPassed = true; try { // Read the docker compose file const dockerComposePath = (0, path_1.join)(DOCKER_COMPOSE_DIR, 'test2.yml'); const composeContent = (0, fs_1.readFileSync)(dockerComposePath, 'utf8'); console.log('Testing Docker Compose translation to Render...'); const renderTranslationResult = (0, index_1.translate)(composeContent, { source: 'compose', target: 'RND', templateFormat: base_parser_1.TemplateFormat.yaml }); // Create directory for Render output const renderOutputDir = (0, path_1.join)(testOutputDir, 'rnd'); if (!(0, fs_1.existsSync)(renderOutputDir)) { (0, fs_1.mkdirSync)(renderOutputDir, { recursive: true }); } // Save all files with proper directory structure Object.entries(renderTranslationResult.files).forEach(([path, fileData]) => { const fullPath = (0, path_1.join)(renderOutputDir, path); const dir = (0, path_1.dirname)(fullPath); if (!(0, fs_1.existsSync)(dir)) { (0, fs_1.mkdirSync)(dir, { recursive: true }); } (0, fs_1.writeFileSync)(fullPath, fileData.content); console.log(`✓ Created Render output: ${path}`); }); // Run assertions for Render const renderYamlPath = (0, path_1.join)(renderOutputDir, 'render.yaml'); if ((0, fs_1.existsSync)(renderYamlPath)) { const renderYaml = yaml.parse((0, fs_1.readFileSync)(renderYamlPath, 'utf8')); try { // 1. Validate YAML structure (0, render_1.assertRenderYamlStructure)(renderYaml); console.log('✓ Render YAML structure validation passed'); // 2. Check for port mappings via PORT env vars across multiple services const webPortValid = (0, port_assertions_1.validatePortEnvironmentVariable)(renderYaml, 'web', '80'); const apiPortValid = (0, port_assertions_1.validatePortEnvironmentVariable)(renderYaml, 'api', '8080'); if (webPortValid && apiPortValid) { console.log('✓ Multiple port mappings validation passed'); } else { testPassed = false; console.error('❌ Multiple port mappings validation failed'); } // 3. Check database service - this should be in the databases section for Render const hasDatabase = renderYaml.databases && Array.isArray(renderYaml.databases) && renderYaml.databases.some((db) => db.name.includes('db')); if (hasDatabase) { console.log('✓ Database service validation passed'); } else { testPassed = false; console.error('❌ Database service validation failed - expected PostgreSQL to be in databases section'); } } catch (error) { testPassed = false; console.error('❌ Render YAML validation failed:', error); } } else { testPassed = false; console.error('❌ Render YAML file not found'); } // Test translation to DigitalOcean console.log('\nTesting Docker Compose translation to DigitalOcean...'); const doTranslationResult = (0, index_1.translate)(composeContent, { source: 'compose', target: 'DOP', templateFormat: base_parser_1.TemplateFormat.yaml }); // Create directory for DigitalOcean output const doOutputDir = (0, path_1.join)(testOutputDir, 'dop'); if (!(0, fs_1.existsSync)(doOutputDir)) { (0, fs_1.mkdirSync)(doOutputDir, { recursive: true }); } // Save all files with proper directory structure Object.entries(doTranslationResult.files).forEach(([path, fileData]) => { const fullPath = (0, path_1.join)(doOutputDir, path); const dir = (0, path_1.dirname)(fullPath); if (!(0, fs_1.existsSync)(dir)) { (0, fs_1.mkdirSync)(dir, { recursive: true }); } (0, fs_1.writeFileSync)(fullPath, fileData.content); console.log(`✓ Created DigitalOcean output: ${path}`); }); // Run assertions for DigitalOcean const doYamlPath = (0, path_1.join)(doOutputDir, '.do/deploy.template.yaml'); if ((0, fs_1.existsSync)(doYamlPath)) { const doYaml = yaml.parse((0, fs_1.readFileSync)(doYamlPath, 'utf8')); try { // 1. Validate YAML structure (0, digitalocean_1.assertDigitalOceanYamlStructure)(doYaml); console.log('✓ DigitalOcean YAML structure validation passed'); // 2. Check for port mappings // Find web service - may have normalized name let webServiceName = ''; let apiServiceName = ''; for (const service of doYaml.spec.services) { if (service.image && service.image.repository && service.image.repository.toLowerCase().includes('nginx')) { webServiceName = service.name; } else if (service.image && service.image.repository && service.image.repository.toLowerCase().includes('node')) { apiServiceName = service.name; } } let portMappingsValid = true; if (!webServiceName) { portMappingsValid = false; console.error('❌ Web service not found in DigitalOcean YAML'); } else { // Validate web service port (should be 80 or PORT env) const webPortValid = (0, do_port_assertions_1.validatePortMappingInDigitalOcean)(doYaml, webServiceName, 80); if (!webPortValid) { portMappingsValid = false; console.error('❌ Web service port mapping validation failed'); } } if (!apiServiceName) { portMappingsValid = false; console.error('❌ API service not found in DigitalOcean YAML'); } else { // Validate API service port (should be 8080) const apiPortValid = (0, do_port_assertions_1.validatePortMappingInDigitalOcean)(doYaml, apiServiceName, 8080); if (!apiPortValid) { portMappingsValid = false; console.error('❌ API service port mapping validation failed'); } } if (portMappingsValid) { console.log('✓ Multiple port mappings validation passed'); } else { testPassed = false; console.error('❌ Multiple port mappings validation failed'); } // 3. Check for database service - this should be in the databases section const hasPostgresDb = (0, digitalocean_1.validateDatabaseService)(doYaml, 'PG'); if (hasPostgresDb) { console.log('✓ DigitalOcean database service validation passed'); } else { testPassed = false; console.error('❌ DigitalOcean database service validation failed'); } } catch (error) { testPassed = false; console.error('❌ DigitalOcean YAML validation failed:', error); } } else { testPassed = false; console.error('❌ DigitalOcean YAML file not found'); } } catch (error) { testPassed = false; console.error('❌ Test execution error:', error); } console.log(`--- Docker Compose Port Test ${testPassed ? 'PASSED ✓' : 'FAILED ❌'} ---`); return testPassed; } /** * Main test runner for Test 2: Port Mappings */ async function runTest2() { console.log('\n=== Running Test 2: Port Mappings ==='); // Create output directory for this test const testOutputDir = (0, path_1.join)(OUTPUT_DIR, 'test2'); if (!(0, fs_1.existsSync)(testOutputDir)) { (0, fs_1.mkdirSync)(testOutputDir, { recursive: true }); } // Run both subtests const dockerRunTestPassed = await runDockerRunPortTest(); const dockerComposeTestPassed = await runDockerComposePortTest(); // Overall test passes if both subtests pass const overallTestPassed = dockerRunTestPassed && dockerComposeTestPassed; console.log(`=== Test 2 ${overallTestPassed ? 'PASSED ✓' : 'FAILED ❌'} ===`); return overallTestPassed; }