Repository: apocas/dockerode-compose Branch: main Commit: b6578214cce0 Files: 39 Total size: 82.7 KB Directory structure: gitextract_raunf6ca/ ├── .github/ │ └── workflows/ │ └── node.js.yml ├── .gitignore ├── .prettierrc.json ├── LICENSE ├── README.md ├── compose.js ├── examples/ │ ├── down.js │ ├── pull.js │ └── up.js ├── lib/ │ ├── configs.js │ ├── networks.js │ ├── secrets.js │ ├── services.js │ ├── servicesTools.js │ ├── tools.js │ └── volumes.js ├── package.json └── test/ ├── assets/ │ ├── complex_example/ │ │ ├── 2-nodejs-projects/ │ │ │ ├── app2.yml │ │ │ ├── docker-compose.yml │ │ │ ├── simple-node-app/ │ │ │ │ └── Dockerfile │ │ │ └── simple-node-app-1235/ │ │ │ ├── Dockerfile │ │ │ ├── app4.yml │ │ │ └── simple-node-app-1236/ │ │ │ └── Dockerfile │ │ └── docker-compose.yml │ ├── depends.yml │ ├── ghost.yml │ ├── mysql.yml │ ├── mysql_extends.yml │ ├── secret.txt │ ├── test_build/ │ │ ├── backend/ │ │ │ └── Dockerfile │ │ ├── backend.Dockerfile │ │ ├── build_things/ │ │ │ └── Dockerfile │ │ └── docker-compose.yml │ ├── wordpress.yml │ ├── wordpress_long.yml │ └── wordpress_original.yml ├── compose.js ├── spec_helper.js └── tools.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/node.js.yml ================================================ # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions name: CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build_nodejs: runs-on: ubuntu-latest strategy: matrix: node-version: [14.x, 16.x, 18.x, 19.x] steps: - uses: actions/checkout@v3 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - name: Provisioning run: | docker --version node -v docker pull ubuntu - name: NPM install run: npm install - name: Nodejs Tests run: npm test build_bun: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: oven-sh/setup-bun@v1 - name: Provisioning run: | docker --version bun -v - name: Bun install run: bun install - name: Bun Tests run: bun run test ================================================ FILE: .gitignore ================================================ examples/reset.sh # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # Next.js build output .next # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and *not* Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port .DS_Store ================================================ FILE: .prettierrc.json ================================================ { "singleQuote": true } ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # dockerode-compose `docker-compose` in Node.js using [dockerode](https://github.com/apocas/dockerode). Everything is executed programmatically using `dockerode`, consequently Docker's API. ### ToDo: * Finish compose spec * User friendly functions (partial deploys, etc) needs to be implemented. ## Installation `npm install dockerode-compose` ### Getting started To use `dockerode-compose` first you need to instantiate it: ``` js var Dockerode = require('dockerode'); var DockerodeCompose = require('dockerode-compose'); var docker = new Dockerode(); var compose = new DockerodeCompose(docker, './test/wordpress.yml', 'wordpress'); (async () => { await compose.pull(); var state = await compose.up(); console.log(state); })(); ``` ## Documentation - new DockerodeCompose(dockerode, file, project_name) - compose.up() - compose.pull(service, options) - omit service to pull all images, options.streams return the streams without waiting, options.verbose pipe the streams to stdout. ## Tests * Tests are implemented using `mocha` and `chai`. Run them with `npm test`. ## Examples Check the examples folder for more specific use cases examples. ## License Pedro Dias - [@pedromdias](https://twitter.com/pedromdias) Licensed under the Apache license, version 2.0 (the "license"); You may not use this file except in compliance with the license. You may obtain a copy of the license at: http://www.apache.org/licenses/LICENSE-2.0.html Unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "as is" basis, without warranties or conditions of any kind, either express or implied. See the license for the specific language governing permissions and limitations under the license. ================================================ FILE: compose.js ================================================ const yaml = require('js-yaml'); const fs = require('fs'); const stream = require('stream'); const secrets = require('./lib/secrets'); const volumes = require('./lib/volumes'); const configs = require('./lib/configs'); const networks = require('./lib/networks'); const services = require('./lib/services'); const tools = require('./lib/tools'); class Compose { constructor(dockerode, file, projectName) { this.docker = dockerode; if (file === undefined || projectName === undefined) { throw new Error('please specify a file and a project name'); } this.file = file; this.projectName = projectName; try { this.recipe = yaml.load(fs.readFileSync(file, 'utf8')); } catch (e) { throw e; } } async down(options) { var output = {}; try { output.file = this.file; output.services = await services.down(this.docker, this.projectName, this.recipe, output, options); output.networks = await networks.down(this.docker, this.projectName, this.recipe, output); if (options !== undefined) { if (options.volumes) { output.volumes = await volumes.down(this.docker, this.projectName, this.recipe, output); } } return output; } catch (e) { throw e; } } async up(options) { var output = {}; try { output.file = this.file; output.secrets = await secrets(this.docker, this.projectName, this.recipe, output); output.volumes = await volumes.up(this.docker, this.projectName, this.recipe, output); output.configs = await configs(this.docker, this.projectName, this.recipe, output); output.networks = await networks.up(this.docker, this.projectName, this.recipe, output); output.services = await services.up(this.docker, this.projectName, this.recipe, output, options); return output; } catch (e) { throw e; } } async pull(serviceN, options) { options = options || {}; var streams = []; var serviceNames = (serviceN === undefined || serviceN === null) ? tools.sortServices(this.recipe) : [serviceN]; for (var serviceName of serviceNames) { var service = this.recipe.services[serviceName]; try { var streami = await this.docker.pull(service.image); streams.push(streami); if (options.verbose === true) { streami.pipe(process.stdout); } if (options.streams !== true) { if (options.verbose === true) { streami.pipe(process.stdout); } else { streami.pipe(stream.PassThrough()); } await new Promise(fulfill => streami.once('end', fulfill)); } } catch (e) { throw e; } } return streams; } } module.exports = Compose; ================================================ FILE: examples/down.js ================================================ var Dockerode = require('dockerode'); var DockerodeCompose = require('../compose'); var docker = new Dockerode(); var yamlFile = './test/assets/wordpress_original.yml' var projectName = 'wordpress' if (process.argv.length > 2) { if (process.argv[2] !== undefined) { yamlFile = process.argv[2] } if (process.argv[3] !== undefined) { projectName = process.argv[3] } } var compose = new DockerodeCompose(docker, yamlFile, projectName); (async () => { var state = await compose.down({ volumes: true }); console.log(state); })(); ================================================ FILE: examples/pull.js ================================================ var Dockerode = require('dockerode'); var DockerodeCompose = require('../compose'); var docker = new Dockerode(); var yamlFile = './test/assets/wordpress_original.yml' var projectName = 'wordpress' if (process.argv.length > 2) { if (process.argv[2] !== undefined) { yamlFile = process.argv[2] } if (process.argv[3] !== undefined) { projectName = process.argv[3] } } var compose = new DockerodeCompose(docker, yamlFile, projectName); (async () => { console.log(await compose.pull()); })(); ================================================ FILE: examples/up.js ================================================ var Dockerode = require('dockerode'); var DockerodeCompose = require('../compose'); var docker = new Dockerode(); var yamlFile = './test/assets/wordpress_original.yml' var projectName = 'wordpress' if (process.argv.length > 2) { if (process.argv[2] !== undefined) { yamlFile = process.argv[2] } if (process.argv[3] !== undefined) { projectName = process.argv[3] } } var compose = new DockerodeCompose(docker, yamlFile, projectName); (async () => { var state = await compose.up(); console.log(state); })(); ================================================ FILE: lib/configs.js ================================================ module.exports = async function (docker, projectName, recipe, output) { var configs = []; var configNames = Object.keys(recipe.configs || []); for (var configName of configNames) { var config = recipe.configs[configName]; if (config.external === true) continue; var opts = { 'Name': projectName + '_' + configName, 'Data': fs.readFileSync(config.file, 'utf8') }; if (config.name !== undefined) { opts.Name = configName; } configs.push(await docker.createConfig(opts)); } return configs; } ================================================ FILE: lib/networks.js ================================================ async function down(docker, projectName, recipe) { var networks = []; var networkNames = Object.keys(recipe.networks || { default: null }); for (var networkName of networkNames) { try { var network = await docker.getNetwork(projectName + '_' + networkName); } catch (e) {} try { await network.remove(); } catch (e) {} } return networks; } async function up(docker, projectName, recipe, output) { var networks = []; var networkNames = Object.keys(recipe.networks || []); for (var networkName of networkNames) { var network = recipe.networks[networkName]; if (network === null) { try { networks.push({ name: projectName + '_' + networkName, network: await docker.createNetwork({ Name: projectName + '_' + networkName, CheckDuplicate: true, }), }); } catch (err) { if ( err.statusCode == 409 && err.json.message.includes('already exists') ) { let returnedNetwork = await docker.listNetworks({ filters: { name: [projectName + '_' + networkName] }, }); networks.push({ name: projectName + '_' + networkName, network: await docker.getNetwork(returnedNetwork[0].Id), }); } else { throw err; } } continue; } if (network.external === true) continue; var opts = { Name: projectName + '_' + networkName, Driver: network.driver, DriverOpts: network.driver_opts, Labels: { ...network.labels, ...{ 'com.docker.compose.network': 'default', 'com.docker.compose.project': projectName, }, }, Attachable: network.attachable, EnableIPv6: network.enable_ipv6, Internal: network.internal, CheckDuplicate: true, }; if (network.name !== undefined) { opts.Name = networkName; } if (network.ipam !== undefined) { opts.IPAM = { Driver: network.ipam.driver, Options: network.ipam.options, }; if (network.ipam.config !== undefined) { opts.IPAM['Config'] = { Subnet: network.ipam.config.subnet, IPRange: network.ipam.config.ip_range, Gateway: network.ipam.config.gateway, AuxAddress: network.ipam.config.aux_addresses, }; } } //if exists we have to compare with the existing network networks.push({ name: projectName + '_' + networkName, network: await docker.createNetwork(opts), }); } if (networks.length === 0) { try { networks.push({ name: projectName + '_default', network: await docker.createNetwork({ Name: projectName + '_default', CheckDuplicate: true, }), }); } catch (err) { if ( err.statusCode == 409 && err.json.message.includes('already exists') ) { let returnedNetwork = await docker.listNetworks({ filters: { name: [projectName + '_default'] }, }); networks.push({ name: projectName + '_' + networkName, network: await docker.getNetwork(returnedNetwork[0].Id), }); } else { throw err; } } } return networks; } module.exports = { down, up, }; ================================================ FILE: lib/secrets.js ================================================ const fs = require('fs'); module.exports = async function (docker, projectName, recipe, output) { var secrets = []; var secretNames = Object.keys(recipe.secrets || []); for (var secretName of secretNames) { var secret = recipe.secrets[secretName]; if (secret.external === true) continue; var opts = { 'Name': projectName + '_' + secretName, 'Data': fs.readFileSync(secret.file, 'utf8') }; if (secret.name !== undefined) { opts.Name = secretName; } secrets.push(await docker.createSecret(opts)); } return secrets; } ================================================ FILE: lib/services.js ================================================ const tools = require('./tools'); const servicesTools = require('./servicesTools'); const fs = require('fs'); const yaml = require('js-yaml'); const path = require('path'); async function down(docker, projectName, recipe, output, options) { var services = []; var serviceNames = tools.sortServices(recipe); for (var serviceName of serviceNames) { let container = docker.getContainer(projectName + '_' + serviceName + '_1'); try { await container.stop(); } catch (e) {} try { await container.remove(); } catch (e) {} } return services; } async function up(docker, projectName, recipe, output, options) { var services = []; var serviceNames = tools.sortServices(recipe); const cwdPath = path.dirname(output.file); for (var serviceName of serviceNames) { var pathScope = {}; pathScope.file = output.file; var networksToAttach = []; var service = recipe.services[serviceName]; if (service.extends !== undefined) { if (service.extends.service !== undefined) { service = extendsServices(service, recipe, pathScope); } else { throw new Error('Service key in extends is required!'); } } if (service.build !== undefined) { var absolutePath = path.dirname(pathScope.file); var obj = {}; if (service.image !== undefined) { obj['t'] = service.image; } else { obj['t'] = projectName + '_' + serviceName; service.image = projectName + '_' + serviceName; } if (typeof service.build === 'object') { if (service.build.context !== undefined) { var buildContextPath = path.resolve( path.join(absolutePath, service.build.context) ); if (fs.existsSync(buildContextPath)) { if (service.build.args !== undefined) { var out = {}; if (Array.isArray(service.build.args)) { for (let arg_line of service.build.args) { var arg = arg_line.split('='); out[arg[0]] = arg[1]; } } else { var argNames = Object.keys(service.build.args); for (var argName of argNames) { out[argName] = service.build.args[argName]; } } obj['buildargs'] = out; } if (service.build.cache_from !== undefined) { obj['cachefrom'] = service.build.cache_from; } if (service.build.extra_hosts !== undefined) { obj['extrahosts'] = service.build.extra_hosts; } if (service.build.labels !== undefined) { if (service.build.labels.length > 0) { let labels = {}; for (let labelsb of service.build.labels) { let p = labelsb.split('='); if (p[1] === undefined) { p[1] = ''; } labels[p[0]] = p[1]; } obj['labels'] = labels; } else { obj['labels'] = service.build.labels; } } if (service.build.shm_size !== undefined) { // RE ARRAGE the function "convertSizeStringToByteValue" to a generic one obj['shmsize'] = servicesTools.convertSizeStringToByteValue([ { path: '', rate: service.build.shm_size }, ]).Rate; } if (service.build.target !== undefined) { obj['target'] = service.build.target; } if (service.build.dockerfile === undefined) { await servicesTools.buildDockerImage( docker, buildContextPath, obj, null, options ); } else { await servicesTools.buildDockerImage( docker, buildContextPath, obj, service.build.dockerfile, options ); } } else { throw new Error( `build path ${buildContextPath} either does not exist, is not accessible, or is not a valid URL.` ); } } else { throw new Error('Build context is required!'); } } else { var dockerFilePath = path.resolve( path.join(absolutePath, service.build) ); if (fs.existsSync(dockerFilePath)) { await servicesTools.buildDockerImage( docker, dockerFilePath, obj, null, options ); } else { throw new Error( `build path ${dockerFilePath} either does not exist, is not accessible, or is not a valid URL.` ); } } } var opts = { name: projectName + '_' + serviceName + '_1', Image: service.image, HostConfig: servicesTools.buildHostConfig( projectName, service, recipe, cwdPath ), Env: servicesTools.buildEnvVars(service), NetworkingConfig: { EndpointsConfig: {}, }, Labels: { 'com.docker.compose.project': projectName, 'com.docker.compose.service': serviceName, }, }; if (service.networks !== undefined) { servicesTools.buildNetworks(projectName, serviceName, service.networks, networksToAttach, opts, recipe.networks); } else { opts.HostConfig.NetworkMode = projectName + '_default'; opts.NetworkingConfig.EndpointsConfig[projectName + '_default'] = { IPAMConfig: null, Links: null, Aliases: [serviceName], }; } // Can be used VolumesFrom from API DIRECTLY inside HostConfig :( if (service.volumes_from) { for (var volume_from of service.volumes_from) { var vf = volume_from.split(':'); var svf = recipe.services[vf[0]]; servicesTools.buildVolumes(svf.volumes, opts); } } if (service.volumes) { servicesTools.buildVolumes(service.volumes, opts); } if (service.container_name !== undefined) { opts.name = service.container_name; } if (service.domainname !== undefined) { opts.Domainname = service.domainname; } if (service.hostname !== undefined) { opts.Hostname = service.hostname; } if (service.mac_address !== undefined) { opts.MacAddress = service.mac_address; } if (service.stdin_open !== undefined) { opts.OpenStdin = service.stdin_open; } if (service.stop_grace_period !== undefined) { let period = parseInt(service.stop_grace_period); if (service.stop_grace_period == period) { opts.StopTimeout = service.stop_grace_period; } else if ( service.stop_grace_period.includes('m') && service.stop_grace_period.includes('s') ) { let minutes = parseInt( service.stop_grace_period.substring( 0, service.stop_grace_period.indexOf('m') ) ); let seconds = parseInt( service.stop_grace_period.substring( service.stop_grace_period.indexOf('m') + 1, service.stop_grace_period.indexOf('s') ) ); opts.StopTimeout = minutes * 60 + seconds; } else { opts.StopTimeout = service.stop_grace_period.substring( 0, service.stop_grace_period.length - 2 ); } } if (service.stop_signal !== undefined) { opts.StopSignal = service.stop_signal; } if (service.expose !== undefined) { var ports = {}; for (var port of service.expose) { ports[port + '/tcp'] = {}; } opts.ExposedPorts = ports; } if (service.tty !== undefined) { opts.Tty = service.tty; } if (service.user !== undefined) { opts.User = service.user; } if (service.working_dir !== undefined) { opts.WorkingDir = service.working_dir; } if (service.labels !== undefined) { if (service.labels.length > 0) { let labels = {}; for (let labelsb of service.labels) { let p = labelsb.split('='); if (p[1] === undefined) { p[1] = ''; } labels[p[0]] = p[1]; } opts.Labels = labels; } else { opts.Labels = service.labels; } } if (service.healthcheck !== undefined) { let healthcheck = {}; healthcheck.Test = service.healthcheck.test; healthcheck.Interval = convertFancyDurationToMs( service.healthcheck.interval ); healthcheck.Timeout = convertFancyDurationToMs( service.healthcheck.timeout ); healthcheck.Retries = service.healthcheck.retries; healthcheck.StartPeriod = convertFancyDurationToMs( service.healthcheck.start_period ); opts.Healthcheck = healthcheck; } if (service.command !== undefined) { opts.Cmd = service.command; } if (service.entrypoint !== undefined) { if (Array.isArray(service.entrypoint)) { opts.Entrypoint = service.entrypoint; } else { let entrypoint = []; entrypoint.push(service.entrypoint); opts.Entrypoint = entrypoint; } } var container = await docker.createContainer(opts); if (networksToAttach.length > 1) { let networkNames = Object.keys(networksToAttach[0]); await findNetwork(output, networkNames[0]).disconnect({ Container: container.id, }); let networksToAttachSorted = tools.sortNetworksToAttach(networksToAttach); for (var networkToAttach of networksToAttachSorted) { let networkName = Object.keys(networkToAttach); await findNetwork(output, networkName).connect({ Container: container.id, EndpointConfig: networkToAttach[networkName], }); } } await container.start(); services.push(container); } return services; } var findNetwork = function (output, name) { for (var network of output.networks) { if (network.name == name) return network.network; } }; var convertFancyDurationToMs = function (value) { let interval = parseInt(value); if (value == interval) { return value; } else if (value.includes('m') && value.includes('s')) { let minutes = parseInt(value.substring(0, value.indexOf('m'))); let seconds = parseInt( value.substring(value.indexOf('m') + 1, value.indexOf('s')) ); return (minutes * 60 + seconds) * 1000 * 1000000; } else { return parseInt(value.substring(0, value.length - 2)) * 1000 * 1000000; } }; // https://github.com/compose-spec/compose-spec/blob/master/spec.md#extends var extendsServices = function (service, recipe, pathScope) { // https://github.com/compose-spec/compose-spec/blob/master/spec.md#finding-referenced-service if (service.extends.file === undefined) { // EXTENDS OF THE SAME RECIPE return buildExtendsService( service, service.extends.service, recipe, pathScope ); } else { // EXTENDS OF ANOTHER RECIPE var absolutePath = path.dirname(pathScope.file); var extendsRecipe = yaml.load( fs.readFileSync( path.resolve(path.join(absolutePath, service.extends.file)), 'utf8' ) ); return buildExtendsService( service, service.extends.service, extendsRecipe, pathScope ); } }; var buildExtendsService = function ( service, extendsServiceName, recipe, pathScope ) { var extend = false; var extendsRecipeServiceNames = Object.keys(recipe.services); for (var extendsRecipeServiceName of extendsRecipeServiceNames) { if (extendsRecipeServiceName == extendsServiceName) { var extendsService = recipe.services[extendsRecipeServiceName]; //deep copy //var oldService = JSON.parse(JSON.stringify(service)); var oldService = service; service = extendsService; var serviceKeys = Object.keys(service); for (let key of serviceKeys) { verifyRestrictions(key); if (key == 'extends') { extend = true; } } var oldServiceKeys = Object.keys(oldService); for (let key of oldServiceKeys) { if (key != 'extends') { mergingService(key, service, oldService); } } if (oldService.extends.file) { var absolutePath = path.dirname(pathScope.file); pathScope.file = path.resolve( path.join(absolutePath, oldService.extends.file) ); } if (extend) service = extendsServices(service, recipe, pathScope); return service; } } throw new Error('Extends service not found'); }; // https://github.com/compose-spec/compose-spec/blob/master/spec.md#restrictions var verifyRestrictions = function (key) { var restrictions = [ 'links', 'volumes_from', 'depends_on', 'ipc', 'pid', 'network_mode', //'net' ]; if (restrictions.includes(key)) { throw new Error('This extends service cannot be used as a base'); } }; // https://github.com/compose-spec/compose-spec/blob/master/spec.md#merging-service-definitions var mergingService = function (key, service, oldService) { var mappings = [ 'environment', //'healthcheck', 'labels', 'sysctls', 'extra_hosts', 'ulimits', ]; var objectMappings = { build: { args: '', labels: '', extra_hosts: '' }, deploy: { labels: '', update_config: '', rollback_config: '', restart_policy: '', resources: { limits: '' }, }, blkio_config: { device_read_bps: '', device_read_iops: '', device_write_bps: '', device_write_iops: '', }, logging: { options: '' }, }; var sequences = [ 'cap_add', 'cap_drop', //'configs', // not implemented yet 'device_cgroup_rules', 'expose', //'external_links', // not implemented yet 'ports', //'secrets', // not fully implemented yet 'security_opt', ]; var objectSequences = { deploy: { placement: { constraints: '', preferences: '' }, reservations: { generic_resources: '' }, }, }; // https://github.com/compose-spec/compose-spec/blob/master/spec.md#mappings - MAPPINGS if ( key == 'build' || key == 'deploy' || key == 'blkio_config' || key == 'logging' ) { // one object level missing in deploy resources var objectMappingsKeys = Object.keys(objectMappings[key]); for (let objectMappingsKey of objectMappingsKeys) { if (oldService[key][objectMappingsKey] !== undefined) { service[key][objectMappingsKey] = oldService[key][objectMappingsKey]; } } } else if (mappings.includes(key) && service[key] !== undefined) { // TRICKY TRICKY (bugs can appear because long and short syntaxes) if (Array.isArray(oldService[key]) || Array.isArray(service[key])) { if (!Array.isArray(service[key])) { let tempService = []; let envsNames = Object.keys(service[key]); for (let envName of envsNames) { tempService.push(envName + '=' + service[key][envName]); } service[key] = tempService; } if (!Array.isArray(oldService[key])) { var tempOldService = []; let envsNames = Object.keys(oldService[key]); for (let envName of envsNames) { tempOldService.push(envName + '=' + oldService[key][envName]); } oldService[key] = tempOldService; } for (let oldServiceLine of oldService[key]) { for (let serviceLine of service[key]) { if ( serviceLine.split('=')[0] == oldServiceLine.split('=')[0] || serviceLine.split(':')[0] == oldServiceLine.split(':')[0] ) { service[key].splice( service[key].indexOf(serviceLine), 1, oldServiceLine ); } } if (!service[key].includes(oldServiceLine)) { service[key].push(oldServiceLine); } } } else { Object.assign(service[key], oldService[key]); } // https://github.com/compose-spec/compose-spec/blob/master/spec.md#sequences - SEQUENCES } else if ( key == 'dns' || key == 'dns_search' || key == 'env_file' || key == 'tmpfs' ) { if (Array.isArray(oldService[key]) || Array.isArray(service[key])) { if (!Array.isArray(service[key])) { let tempService = []; if (service[key] !== undefined) { tempService.push(service[key]); } service[key] = tempService; } if (!Array.isArray(oldService[key])) { oldService[key] = [oldService[key]]; } service[key] = service[key].concat(oldService[key]); } else { service[key] = []; service[key].push(service[key]); service[key].push(oldService[key]); } } else if (key == 'deploy') { var objectSequencesKeys = Object.keys(objectSequences[key]); for (let objectSequencesKey of objectSequencesKeys) { if (oldService[key][objectSequencesKey] !== undefined) { service[key][objectSequencesKey] = oldService[key][objectSequencesKey]; } } } else if (sequences.includes(key) && service[key] !== undefined) { if (Array.isArray(oldService[key]) || Array.isArray(service[key])) { for (let oldServiceLine of oldService[key]) { if (!service[key].includes(oldServiceLine)) { service[key].push(oldServiceLine); } } } // else !!! for now all keys are arrays with future implementations can maybe change !!! } else { // https://github.com/compose-spec/compose-spec/blob/master/spec.md#scalars - SCALARS service[key] = oldService[key]; } }; module.exports = { down, up, }; ================================================ FILE: lib/servicesTools.js ================================================ const fs = require('fs'); const tar = require('tar-fs'); const path = require('path'); const stream = require('stream'); /** * if host path in the volume string (e.g. `./mylocal/file:/container/file`) is not absolute path, * this function will convert it to an absolute path using `cwd` (current working directory) parameter. * Otherwise, it will return volume string as it is. * * @param {*} volumeStr * @param {*} cwd */ function standardizeVolumeStr(volumeStr, cwd) { if (typeof volumeStr !== 'string' || volumeStr.length < 1) { return volumeStr; } volumeStr = volumeStr.trim(); if ( volumeStr.substring(0, 2) !== './' && volumeStr.substring(0, 3) !== '../' ) { return volumeStr; } const parts = volumeStr.split(':'); if (parts.length !== 2) { return volumeStr; } if (!cwd) { throw new Error( 'Current working dir path not available when local path is a relative path: ' + parts[0] ); } const localPath = parts[0]; return path.resolve(cwd, localPath) + ':' + parts[1]; } module.exports = { buildPorts: function (servicePorts, output) { var ports = {}; if (typeof servicePorts[0] === 'object') { // LONG SYNTAX // !!! INCOMPLETE - NOT USING DIFFERENT MODES - `mode`: `host` for publishing a host port on each node, or `ingress` for a port to be load balanced. for (let port of servicePorts) { ports[port.target + '/' + port.protocol] = [ { HostPort: port.published.toString() }, ]; } output['PortBindings'] = ports; } else { // SHORT SYNTAX // TODO: SIMPLIFY THIS BLOCK OF CODE! MAYBE! for (let port of servicePorts) { var port_split = port.split(':'); if (port_split.length == 2) { // "xxxx:xxxx" if (port_split[1].includes('-')) { // "9090-9091:8080-8081" let split_port_split0 = port_split[0].split('-'); let split_port_split0_array = []; split_port_split0_array = fillPortArray( parseInt(split_port_split0[0]), parseInt(split_port_split0[1]) ); let split_port_split1 = port_split[1].split('-'); let split_port_split1_array = []; split_port_split1_array = fillPortArray( parseInt(split_port_split1[0]), parseInt(split_port_split1[1]) ); for (let index in split_port_split0_array) { ports[split_port_split1_array[index] + '/tcp'] = [ { HostPort: split_port_split0_array[index].toString(), }, ]; } } else if (port_split[0].includes('-')) { // "3000-3005" let split_port_split = port_split[0].split('-'); ports[port_split[1] + '/tcp'] = []; for (let i = split_port_split[0]; i <= split_port_split[1]; i++) { ports[port_split[1] + '/tcp'].push({ HostPort: i.toString(), }); } } else if (port_split[1].includes('/')) { // "6060:6060/udp" ports[port_split[1]] = [{ HostPort: port_split[0] }]; } else { // "8000:8000" ports[port_split[1] + '/tcp'] = [{ HostPort: port_split[0] }]; } } else if (port_split.length == 3) { // "x.x.x.x:xxxx:xxxx" if (port_split[2].includes('-')) { // "127.0.0.1:5000-5010:5000-5010" let split_port_split1 = port_split[1].split('-'); let split_port_split1_array = []; split_port_split1_array = fillPortArray( parseInt(split_port_split1[0]), parseInt(split_port_split1[1]) ); let split_port_split2 = port_split[2].split('-'); let split_port_split2_array = []; split_port_split2_array = fillPortArray( parseInt(split_port_split2[0]), parseInt(split_port_split2[1]) ); for (let index in split_port_split1_array) { ports[split_port_split2_array[index] + '/tcp'] = [ { HostPort: split_port_split1_array[index].toString(), HostIp: port_split[0], }, ]; } } else if (port_split[1] == '') { // "127.0.0.1::5000 ports[port_split[2] + '/tcp'] = [ { HostPort: port_split[2], HostIp: port_split[0] }, ]; } else { // "127.0.0.1:8001:8001" ports[port_split[2] + '/tcp'] = [ { HostPort: port_split[1], HostIp: port_split[0] }, ]; } } else { // "xxxx" if (port_split[0].includes('-')) { // "3000-3005" let split_port_split = port_split[0].split('-'); for (let i = split_port_split[0]; i <= split_port_split[1]; i++) { ports[i + '/tcp'] = [{ HostPort: i.toString() }]; } } else { // "3000" ports[port + '/tcp'] = [{ HostPort: port }]; } } } output['PortBindings'] = ports; } }, //ToDo: complete the compose specification buildHostConfig: function (projectName, service, recipe, cwd) { var output = { RestartPolicy: { Name: service.restart }, }; if (service.volumes_from !== undefined) { for (var volume_from of service.volumes_from) { var vf = volume_from.split(':'); var svf = recipe.services[vf[0]]; this.buildVolumesHostconfig( projectName, svf.volumes, output, vf[1], cwd ); } } if (service.volumes !== undefined) { this.buildVolumesHostconfig( projectName, service.volumes, output, undefined, cwd ); } if (service.ports !== undefined) { this.buildPorts(service.ports, output); } if (service.devices !== undefined) { output.Devices = service.devices.map((device) => ({ CgroupPermissions: "mrw", PathInContainer: device, PathOnHost: device, })); } if (service.cpu_count !== undefined) { output.CpuCount = service.cpu_count; } if (service.cpu_percent !== undefined) { output.CpuPercent = service.cpu_percent; } if (service.cpu_shares !== undefined) { output.CpuShares = service.cpu_shares; } if (service.cpu_period !== undefined) { output.CpuPeriod = service.cpu_period; } if (service.cpu_quota !== undefined) { output.CpuQuota = service.cpu_quota; } if (service.cpu_rt_runtime !== undefined) { output.CpuRealtimeRuntime = service.cpu_rt_runtime; } if (service.cpu_rt_period !== undefined) { output.CpuRealtimePeriod = service.cpu_rt_period; } if (service.cpuset !== undefined) { output.CpusetCpus = service.cpuset; } if (service.cap_add !== undefined) { output.CapAdd = service.cap_add; } if (service.cap_drop !== undefined) { output.CapDrop = service.cap_drop; } if (service.cgroup_parent !== undefined) { output.CgroupParent = service.cgroup_parent; } if (service.device_cgroup_rules !== undefined) { output.DeviceCgroupRules = service.device_cgroup_rules; } if (service.dns !== undefined) { output.Dns = service.dns; } if (service.dns_opt !== undefined) { output.DnsOptions = service.dns_opt; } if (service.dns_search !== undefined) { output.DnsSearch = service.dns_search; } if (service.extra_hosts !== undefined) { output.ExtraHosts = service.extra_hosts; } if (service.group_add !== undefined) { output.GroupAdd = service.group_add; } if (service.init !== undefined) { output.Init = service.init; } if (service.ipc !== undefined) { output.IpcMode = service.ipc; } if (service.isolation !== undefined) { output.Isolation = service.isolation; } if (service.mem_swappiness !== undefined) { output.MemorySwappiness = service.mem_swappiness; } if (service.oom_kill_disable !== undefined) { output.OomKillDisable = service.oom_kill_disable; } if (service.oom_score_adj !== undefined) { output.OomScoreAdj = service.oom_score_adj; } if (service.pid !== undefined) { output.PidMode = service.pid; } if (service.pids_limit !== undefined) { output.PidsLimit = service.pids_limit; } if (service.privileged !== undefined) { output.Privileged = service.privileged; } if (service.read_only !== undefined) { output.ReadonlyRootfs = service.read_only; } if (service.runtime !== undefined) { output.Runtime = service.runtime; } if (service.security_opt !== undefined) { output.SecurityOpt = service.security_opt; } if (service.shm_size !== undefined) { output.ShmSize = service.shm_size; } if (service.storage_opt !== undefined) { output.StorageOpt = service.storage_opt; } if (service.sysctls !== undefined) { if (service.sysctls.length > 0) { var sysctls = {}; for (var sysctlsb of service.sysctls) { let p = sysctlsb.split('='); sysctls[p[0]] = p[1]; } output.Sysctls = sysctls; } else { let sysctlKeys = Object.keys(service.sysctls); let newSysctls = {}; for (let key of sysctlKeys) { newSysctls[key] = service.sysctls[key].toString(); } output.Sysctls = newSysctls; } } if (service.userns_mode !== undefined) { output.UsernsMode = service.userns_mode; } if (service.tmpfs !== undefined) { var tmpfs = {}; if (Array.isArray(service.tmpfs)) { for (var tmpfsb of service.tmpfs) { let p = tmpfsb.split(':'); if (p[1] === undefined) { p[1] = ''; } tmpfs[p[0]] = p[1]; } output.Tmpfs = tmpfs; } else { let p = service.tmpfs.split(':'); if (p[1] === undefined) { p[1] = ''; } tmpfs[p[0]] = p[1]; output.Tmpfs = tmpfs; } } if (service.ulimits !== undefined) { let ulimitsKeys = Object.keys(service.ulimits); let ulimitsArray = []; for (let key of ulimitsKeys) { let ulimitsObject = {}; if (typeof service.ulimits[key] === 'object') { ulimitsObject.Name = key; ulimitsObject.Soft = service.ulimits[key].soft; ulimitsObject.Hard = service.ulimits[key].hard; ulimitsArray.push(ulimitsObject); } else { ulimitsObject.Name = key; ulimitsObject.Soft = service.ulimits[key]; ulimitsObject.Hard = service.ulimits[key]; ulimitsArray.push(ulimitsObject); } } output.Ulimits = ulimitsArray; } if (service.blkio_config !== undefined) { if (service.blkio_config.weight !== undefined) { output.BlkioWeight = service.blkio_config.weight; } if (service.blkio_config.weight_device !== undefined) { let weight_device = [{}]; weight_device[0]['Path'] = service.blkio_config.weight_device[0].path; weight_device[0]['Weight'] = service.blkio_config.weight_device[0].weight; output.BlkioWeightDevice = weight_device; } if (service.blkio_config.device_read_bps !== undefined) { output.BlkioDeviceReadBps = convertSizeStringToByteValue( service.blkio_config.device_read_bps ); } if (service.blkio_config.device_read_iops !== undefined) { let device_read_iops = [{}]; device_read_iops[0]['Path'] = service.blkio_config.device_read_iops[0].path; device_read_iops[0]['Rate'] = service.blkio_config.device_read_iops[0].rate; output.BlkioDeviceReadIOps = device_read_iops; } if (service.blkio_config.device_write_bps !== undefined) { output.BlkioDeviceWriteBps = convertSizeStringToByteValue( service.blkio_config.device_write_bps ); } if (service.blkio_config.device_write_iops !== undefined) { let device_write_iops = [{}]; device_write_iops[0]['Path'] = service.blkio_config.device_write_iops[0].path; device_write_iops[0]['Rate'] = service.blkio_config.device_write_iops[0].rate; output.BlkioDeviceWriteIOps = device_write_iops; } } if (service.logging !== undefined) { let logging = {}; logging.Type = service.logging.driver; logging.Config = service.logging.options; output.LogConfig = logging; } return output; }, buildVolumesHostconfig: function (projectName, volumes, output, type, cwd) { if (output['Binds'] === undefined) { output['Binds'] = []; } for (var volume of volumes) { if (typeof volume === 'string' || volume instanceof String) { if ( volume.substring(0, 2) === './' || volume.substring(0, 3) === '../' || volume[0] === '/' ) { const stdVolume = standardizeVolumeStr(volume, cwd); let aux = stdVolume; if (type == 'ro') { aux += ':ro'; } output['Binds'].push(aux); } else { var aux = projectName + '_' + volume; if (type == 'ro') { aux += ':ro'; } output['Binds'].push(aux); } } else { var volumestr = ''; if (volume.source && volume.target) { if ( volume.source.substring(0, 2) === './' || volume.source.substring(0, 3) === '../' || volume.source[0] === '/' ) { volumestr += standardizeVolumeStr( volume.source + ':' + volume.target, cwd ); } else { volumestr += projectName + '_' + volume.source + ':' + volume.target + ':'; } } if (volume.read_only || type == 'ro') { volumestr += 'ro,'; } if (volume.volume && volume.volume.nocopy) { volumestr += 'nocopy,'; } if (volume.bind && volume.bind.propagation) { volumestr += volume.bind.propagation + ','; } volumestr = volumestr.slice(0, -1); output['Binds'].push(volumestr); } } }, buildVolumes: function (volumes, opts) { if (opts['Volumes'] === undefined) { opts['Volumes'] = {}; } for (var volume of volumes) { if (volume.substring(0, 2) === './' || volume[0] === '/') { continue; } if (typeof volume === 'string' || volume instanceof String) { var v = volume.split(':'); opts['Volumes'][v[1]] = {}; } else { if (volume.target) { opts['Volumes'][volume.target] = {}; } } } }, buildEnvVars: function (service) { var output = []; if (service.env_file !== undefined) { if (Array.isArray(service.env_file)) { for (let env_file_path of service.env_file) { this.buildEnvVarsFromFile(env_file_path, output); } } else { this.buildEnvVarsFromFile(service.env_file, output); } } if (service.environment !== undefined) { if (Array.isArray(service.environment)) { for (let environment_line of service.environment) { output.push(environment_line); } } else { var envsNames = Object.keys(service.environment); for (var envName of envsNames) { output.push(envName + '=' + service.environment[envName]); } } } return output; }, buildNetworks: function (projectName, serviceName, serviceNetworks, networksToAttach, opts, toplevelNetworks) { if (Array.isArray(serviceNetworks)) { for (let index = 0; index < serviceNetworks.length; index++) { let networkName = projectName + '_' + serviceNetworks[index]; // check if network is external if (toplevelNetworks !== undefined) { if (Object.keys(toplevelNetworks).includes(serviceNetworks[index])) { if (toplevelNetworks[serviceNetworks[index]].external === true) { // it is external network networkName = toplevelNetworks[serviceNetworks[index]].name } } } let networkTemplate = { NetworkingConfig: { EndpointsConfig: {}, }, }; networkTemplate.NetworkingConfig.EndpointsConfig[networkName] = {}; networkTemplate.NetworkingConfig.EndpointsConfig[networkName][ 'Aliases' ] = [serviceName]; if (index === 0) opts.NetworkingConfig.EndpointsConfig = networkTemplate.NetworkingConfig.EndpointsConfig; networksToAttach.push(networkTemplate.NetworkingConfig.EndpointsConfig); } } else { let networkNames = Object.keys(serviceNetworks); for (let index = 0; index < networkNames.length; index++) { let network = serviceNetworks[networkNames[index]] || {}; let networkName = projectName + '_' + serviceNetworks[index]; // check if network is external if (toplevelNetworks !== undefined) { if (Object.keys(toplevelNetworks).includes(networkNames[index])) { if (toplevelNetworks[networkNames[index]].external === true) { // it is external network networkName = toplevelNetworks[networkNames[index]].name } } } let networkTemplate = { NetworkingConfig: { EndpointsConfig: {}, }, }; networkTemplate.NetworkingConfig.EndpointsConfig[networkName] = {}; networkTemplate.NetworkingConfig.EndpointsConfig[networkName][ 'IPAMConfig' ] = {}; if (network.aliases !== undefined) { networkTemplate.NetworkingConfig.EndpointsConfig[networkName][ 'Aliases' ] = network.aliases; } if (network.ipv4_address !== undefined) { networkTemplate.NetworkingConfig.EndpointsConfig[ networkName ].IPAMConfig['IPv4Address'] = network.ipv4_address; } if (network.ipv6_address !== undefined) { networkTemplate.NetworkingConfig.EndpointsConfig[ networkName ].IPAMConfig['IPv6Address'] = network.ipv6_address; } if (network.link_local_ips !== undefined) { networkTemplate.NetworkingConfig.EndpointsConfig[ networkName ].IPAMConfig['LinkLocalIPs'] = network.link_local_ips; } if (network.priority !== undefined) { networkTemplate.NetworkingConfig.EndpointsConfig[ networkName ].priority = network.priority; } else { networkTemplate.NetworkingConfig.EndpointsConfig[ networkName ].priority = 0; } if (index === 0) { opts.NetworkingConfig.EndpointsConfig = networkTemplate.NetworkingConfig.EndpointsConfig; } networksToAttach.push(networkTemplate.NetworkingConfig.EndpointsConfig); } } }, // TODO: OPTIMIZE! convertSizeStringToByteValue: function (obj) { let rate = obj[0].rate.toLowerCase(); let new_obj = [{}]; if (rate.includes('k')) { if (rate.indexOf('k') == rate.length - 1) { rate = rate.replace('k', ''); } else if (rate.indexOf('k') == rate.length - 2) { rate = rate.replace('kb', ''); } new_obj[0]['Path'] = obj[0].path; new_obj[0]['Rate'] = rate * 1024; return new_obj; } else if (rate.includes('m')) { if (rate.indexOf('m') == rate.length - 1) { rate = rate.replace('m', ''); } else if (rate.indexOf('m') == rate.length - 2) { rate = rate.replace('mb', ''); } new_obj[0]['Path'] = obj[0].path; new_obj[0]['Rate'] = rate * 1024 * 1024; return new_obj; } else if (rate.includes('g')) { if (rate.indexOf('g') == rate.length - 1) { rate = rate.replace('g', ''); } else if (rate.indexOf('g') == rate.length - 2) { rate = rate.replace('gb', ''); } new_obj[0]['Path'] = obj[0].path; new_obj[0]['Rate'] = rate * 1024 * 1024 * 1024; return new_obj; } }, buildEnvVarsFromFile: function (env_file_path, output) { // Each line in an env file MUST be in `VAR=VAL` format. let env_file = fs .readFileSync(env_file_path, 'utf8') .toString() .split('\n'); for (let env_line of env_file) { // Lines beginning with `#` MUST be ignored. Blank lines MUST also be ignored. if (env_line != '' && env_line.indexOf('#') != 0) { let env_line_split = env_line.split('='); // `VAL` MAY be omitted, sin such cases the variable value is empty string. `=VAL` MAY be omitted, in such cases the variable is **unset**. if (env_line_split[0] != '' && env_line_split[1] != '') { output.push(env_line); } } } }, fillPortArray: function (start, end) { return Array(end - start + 1) .fill() .map((_, idx) => start + idx); }, buildDockerImage: async function ( docker, buildPath, obj, dockerfile, options ) { options = options || {}; if (dockerfile !== null) { obj['dockerfile'] = path.basename(dockerfile); let streami = await docker.buildImage( { context: buildPath, src: [dockerfile], }, obj ); if (options.verbose === true) { streami.pipe(process.stdout); } else { streami.pipe(stream.PassThrough()); } await new Promise((fulfill) => streami.once('end', fulfill)); } else { var tarStream = tar.pack(buildPath); let streami = await docker.buildImage(tarStream, obj); if (options.verbose === true) { streami.pipe(process.stdout); } else { streami.pipe(stream.PassThrough()); } await new Promise((fulfill) => streami.once('end', fulfill)); } }, }; ================================================ FILE: lib/tools.js ================================================ module.exports = { 'getImages': function (recipe) { var images = []; var serviceNames = Object.keys(recipe.services || []); for (var serviceName of serviceNames) { if (recipe.services[serviceName].image) { images.push(recipe.services[serviceName].image); } } return images; }, 'sortServices': function (recipe) { var order = []; var serviceNames = Object.keys(recipe.services || []); while (order.length !== serviceNames.length) { for (var serviceName of serviceNames) { if (order.indexOf(serviceName) === -1) { let depends_on = recipe.services[serviceName].depends_on; if (typeof depends_on === "object" && !Array.isArray(depends_on)) { // if we are using Long Syntax https://github.com/compose-spec/compose-spec/blob/master/spec.md#long-syntax-1 // we will need to get keys from object and use them as dependencies depends_on = Object.keys(depends_on) } insertService(serviceName, depends_on || [], order); } } } return order; }, 'sortNetworksToAttach': function (networksToAttach) { var networksToAttachSorted = []; for (let i = 0; i < networksToAttach.length; i++) { let networkName = Object.keys(networksToAttach[i]); if (i === 0) { networksToAttachSorted.push(networksToAttach[i]); } else { let aux = 0; for (let j = 0; j < networksToAttachSorted.length; j++) { let networkNameSorted = Object.keys(networksToAttachSorted[j]); if (networksToAttachSorted[j][networkNameSorted].priority > networksToAttach[i][networkName].priority) { aux += j + 1; } else if (networksToAttachSorted[j][networkNameSorted].priority < networksToAttach[i][networkName].priority) { aux += j - 1; } else { aux += j + 1; } } if (aux < 0) aux = 0; networksToAttachSorted.splice(aux, 0, networksToAttach[i]); } } return networksToAttachSorted; } } function insertService(serviceName, depends_on, order) { var position = -1; for (var serviceDep of depends_on) { var p = order.indexOf(serviceDep); if (p === -1) return; if (p > position) position = p; } order.splice(position + 1, 0, serviceName); } ================================================ FILE: lib/volumes.js ================================================ async function down(docker, projectName, recipe, output) { var volumes = []; var volumeNames = Object.keys(recipe.volumes || []); for (var volumeName of volumeNames) { try { var volume = await docker.getVolume(projectName + '_' + volumeName); } catch (e) {} try { await volume.remove(); } catch (e) {} } return volumes; } async function up(docker, projectName, recipe, output) { var volumes = []; var volumeNames = Object.keys(recipe.volumes || []); for (var volumeName of volumeNames) { var volume = recipe.volumes[volumeName]; if (volume === null) volume = {}; if (volume.external === true) continue; var opts = { Name: projectName + '_' + volumeName, Driver: volume.driver, DriverOpts: volume.driver_opts, Labels: { ...volume.labels, ...{ 'com.docker.compose.project': projectName, 'com.docker.compose.volume': volumeName, }, }, }; if (volume.name !== undefined) { opts.Name = volume.name; } volumes.push(await docker.createVolume(opts)); } return volumes; } module.exports = { down, up, }; ================================================ FILE: package.json ================================================ { "name": "dockerode-compose", "version": "1.4.0", "description": "docker-compose in nodejs using dockerode", "main": "./compose.js", "scripts": { "test": "./node_modules/mocha/bin/mocha.js -R spec --exit" }, "repository": { "type": "git", "url": "git+https://github.com/apocas/dockerode-compose.git" }, "author": "Pedro Dias ", "license": "Apache-2.0", "bugs": { "url": "https://github.com/apocas/dockerode-compose/issues" }, "keywords": [ "docker", "docker-compose" ], "homepage": "https://github.com/apocas/dockerode-compose#readme", "dependencies": { "dockerode": "^4.0.0", "js-yaml": "^4.0.0", "tar-fs": "^2.1.1" }, "devDependencies": { "chai": "~4.2.0", "memorystream": "~0.3.0", "mocha": "^10.2.0" } } ================================================ FILE: test/assets/complex_example/2-nodejs-projects/app2.yml ================================================ version: '3' services: app2: build: ./simple-node-app-1235 volumes: db_data: {} ================================================ FILE: test/assets/complex_example/2-nodejs-projects/docker-compose.yml ================================================ version: '3' services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test MYSQL_USER: test MYSQL_PASSWORD: testpassword app1: build: ./simple-node-app environment: DB_HOST: db DB_DATABASE: test DB_USER: teste DB_PASSWORD: testpassword app2: extends: file: ./app2.yml service: app2 app3: extends: service: app1 app4: extends: file: ./simple-node-app-1235/app4.yml service: app4 volumes: db_data: {} ================================================ FILE: test/assets/complex_example/2-nodejs-projects/simple-node-app/Dockerfile ================================================ FROM ubuntu RUN \ apt-get update && \ apt-get install -y nginx && service nginx start && echo "BACKEND" CMD ["bash"] ================================================ FILE: test/assets/complex_example/2-nodejs-projects/simple-node-app-1235/Dockerfile ================================================ FROM ubuntu RUN \ apt-get update && \ apt-get install -y nginx && service nginx start && echo "BACKEND" CMD ["bash"] ================================================ FILE: test/assets/complex_example/2-nodejs-projects/simple-node-app-1235/app4.yml ================================================ version: '3' services: app4: build: ./simple-node-app-1236 volumes: db_data: {} ================================================ FILE: test/assets/complex_example/2-nodejs-projects/simple-node-app-1235/simple-node-app-1236/Dockerfile ================================================ FROM ubuntu RUN \ apt-get update && \ apt-get install -y nginx && service nginx start && echo "BACKEND" CMD ["bash"] ================================================ FILE: test/assets/complex_example/docker-compose.yml ================================================ version: '3' services: db: extends: file: ./2-nodejs-projects/docker-compose.yml service: db volumes: - db_data:/var/lib/mysql expose: - "3306" app1: extends: file: ./2-nodejs-projects/docker-compose.yml service: app1 depends_on: - db ports: - "5001-5005:5000" app2: extends: file: ./2-nodejs-projects/docker-compose.yml service: app2 ports: - "5006-5010:5000" app3: extends: file: ./2-nodejs-projects/docker-compose.yml service: app3 ports: - "5006-5010:5000" app4: extends: file: ./2-nodejs-projects/docker-compose.yml service: app4 ports: - "5006-5010:5000" app5: extends: service: app4 app6: extends: service: app3 app7: extends: service: app2 volumes: db_data: {} ================================================ FILE: test/assets/depends.yml ================================================ version: "3.9" services: wordpress4: image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress wordpress5: depends_on: - wordpress4 - db - wordpress2 image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress wordpress6: depends_on: db: condition: service_started wordpress2: condition: service_started image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress2: depends_on: - wordpress1 image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress wordpress1: depends_on: - db image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress wordpress3: image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: db_data: {} secrets: server-secret: file: ./test/secret.txt server-secret-external: external: true ================================================ FILE: test/assets/ghost.yml ================================================ version: '2' services: gost-db: image: geodan/gost-db volumes: - postgis:/var/lib/postgresql/data environment: POSTGRES_DB: gost POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres gost: image: geodan/gost volumes: - gost_conf:/gostserver/config depends_on: - gost-db environment: GOST_LOG_VERBOSE_FLAG: 1 GOST_DB_HOST: gost-db GOST_SERVER_EXTERNAL_URI: "http://localhost:8080" dashboard: image: geodan/gost-dashboard ports: - "8080:8080" depends_on: - gost volumes: postgis: {} gost_conf: {} ================================================ FILE: test/assets/mysql.yml ================================================ version: '3' services: db: extends: file: ./test/assets/mysql_extends.yml service: db volumes: - db_data:/var/lib/mysql expose: - "3306" db1: extends: file: ./test/assets/mysql_extends.yml service: db_ext volumes: - db_data:/var/lib/mysql expose: - "3306" volumes: db_data: {} ================================================ FILE: test/assets/mysql_extends.yml ================================================ version: '3' services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: testdatabase MYSQL_USER: testdatabase MYSQL_PASSWORD: testdatabase12345 db_ext: extends: service: db volumes: - db_data:/var/lib/mysql expose: - "3306" volumes: db_data: {} ================================================ FILE: test/assets/secret.txt ================================================ xpto ================================================ FILE: test/assets/test_build/backend/Dockerfile ================================================ FROM ubuntu RUN \ apt-get update && \ apt-get install -y nginx && service nginx start && echo "BACKEND" CMD ["bash"] ================================================ FILE: test/assets/test_build/backend.Dockerfile ================================================ FROM ubuntu RUN \ apt-get update && \ apt-get install -y nginx && service nginx start CMD ["bash"] ================================================ FILE: test/assets/test_build/build_things/Dockerfile ================================================ FROM ubuntu RUN \ apt-get update && \ apt-get install -y nginx && service nginx start CMD ["bash"] ================================================ FILE: test/assets/test_build/docker-compose.yml ================================================ services: frontend: build: ./build_things backend: build: context: backend cache_from: - ubuntu args: GIT_COMMIT: cdc3b19 futureend: build: context: backend cache_from: - ubuntu args: GIT_COMMIT: cdc3b19 dockerfile: ../backend.Dockerfile ================================================ FILE: test/assets/wordpress.yml ================================================ version: "3.9" services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest ports: - "8000:80" restart: always volumes_from: - db:ro environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: db_data: {} ================================================ FILE: test/assets/wordpress_long.yml ================================================ version: "3.9" services: db: image: mysql:5.7 volumes: - source: db_data target: /var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: db_data: {} ================================================ FILE: test/assets/wordpress_original.yml ================================================ version: "3.3" services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress volumes: db_data: ================================================ FILE: test/compose.js ================================================ const expect = require('chai').expect, assert = require('assert'); var compose = require('./spec_helper').compose; var compose_complex = require('./spec_helper').compose_complex; var compose_build = require('./spec_helper').compose_build; var docker = require('./spec_helper').docker; describe('compose', function () { describe('#pull', function () { it("should pull all needed images with verbose", function (done) { this.timeout(600000); (async () => { await compose.pull(null, { 'verbose': true }); done(); })(); }); it("should pull all needed images silently", function (done) { this.timeout(600000); (async () => { await compose.pull(); done(); })(); }); it("should pull all needed images returning streams", function (done) { this.timeout(600000); (async () => { var streams = await compose.pull(null, { 'streams': true }); expect(streams).to.be.ok; done(); })(); }); }); describe('#up', function () { it("should do compose up", function (done) { this.timeout(60000); (async () => { var report = await compose.up(); expect(report.services).to.be.ok; done(); })(); }); afterEach('clean up', function (done) { this.timeout(60000); (async () => { await compose.down({ volumes: true }); done(); })(); }); }); describe('#down', function () { beforeEach('bring up', function (done) { this.timeout(20000); (async () => { await compose.up(); done(); })(); }); it("should do compose down", function (done) { this.timeout(60000); (async () => { await compose.down({volumes: true}); let listContainers = await docker.listContainers({ 'all': true, 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}); expect(listContainers).to.be.empty let listVolumes = await docker.listVolumes({ 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}) expect(listVolumes.Volumes).to.be.empty expect(listVolumes.Warnings).to.be.null let listNetworks = await docker.listNetworks({ 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}) expect(listNetworks).to.be.empty done(); })(); }); }); describe('#up_complex', function () { it("should do compose up complex example with extends and build", function (done) { this.timeout(300000); (async () => { var report = await compose_complex.up(); expect(report.services).to.be.ok; done(); })(); }); afterEach('clean up', function (done) { this.timeout(60000); (async () => { await compose_complex.down({ volumes: true }); done(); })(); }); }); describe('#down_complex', function () { beforeEach('bring up', function (done) { this.timeout(300000); (async () => { await compose_complex.up(); done(); })(); }); it("should do compose down complex example with extends and build", function (done) { this.timeout(60000); (async () => { await compose_complex.down({volumes: true}); let listContainers = await docker.listContainers({ 'all': true, 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}); expect(listContainers).to.be.empty let listVolumes = await docker.listVolumes({ 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}) expect(listVolumes.Volumes).to.be.empty expect(listVolumes.Warnings).to.be.null let listNetworks = await docker.listNetworks({ 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}) expect(listNetworks).to.be.empty done(); })(); }); }); describe('#up_build', function () { it("should do compose up example with build", function (done) { this.timeout(300000); (async () => { var report = await compose_build.up(); expect(report.services).to.be.ok; done(); })(); }); it("should do compose up example with build(verbose)", function (done) { this.timeout(300000); (async () => { var report = await compose_build.up({ 'verbose': true }); expect(report.services).to.be.ok; done(); })(); }); afterEach('clean up', function (done) { this.timeout(60000); (async () => { await compose_build.down({ volumes: true }); done(); })(); }); }); describe('#down_build', function () { beforeEach('bring up', function (done) { this.timeout(300000); (async () => { await compose_build.up(); done(); })(); }); it("should do compose down example with build", function (done) { this.timeout(60000); (async () => { await compose_build.down({volumes: true}); let listContainers = await docker.listContainers({ 'all': true, 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}); expect(listContainers).to.be.empty let listVolumes = await docker.listVolumes({ 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}) expect(listVolumes.Volumes).to.be.empty expect(listVolumes.Warnings).to.be.null let listNetworks = await docker.listNetworks({ 'filters': {"label":[`com.docker.compose.project=${compose.projectName}`]}}) expect(listNetworks).to.be.empty done(); })(); }); }); }); ================================================ FILE: test/spec_helper.js ================================================ var Dockerode = require('dockerode'); var DockerodeCompose = require('../compose'); var docker = new Dockerode(); var compose = new DockerodeCompose(docker, './test/assets/wordpress_original.yml', 'dockerodec_wordpress'); var compose_complex = new DockerodeCompose(docker, './test/assets/complex_example/docker-compose.yml', 'dockerodec_complex'); var compose_build = new DockerodeCompose(docker, './test/assets/test_build/docker-compose.yml', 'dockerodec_build'); module.exports = { 'docker': docker, 'compose': compose, 'compose_complex': compose_complex, 'compose_build': compose_build } ================================================ FILE: test/tools.js ================================================ const expect = require('chai').expect; const tools = require('../lib/tools'); const yaml = require('js-yaml'); const fs = require('fs'); describe('tools', function () { describe('#sortservices', function () { it("should sort services", function (done) { var recipe = yaml.load(fs.readFileSync('./test/assets/depends.yml', 'utf8')); expect(tools.sortServices(recipe)).to.eql([ 'wordpress3', 'db', 'wordpress1', 'wordpress2', 'wordpress6', 'wordpress4', 'wordpress5' ]); done(); }); }); });