start.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const path = require('path');
  2. const isRoot = require('is-root');
  3. const hostile = require('hostile');
  4. const colors = require('colors');
  5. const docker = require('docker-compose');
  6. const log = require('../inc/log');
  7. const ProjectEnvironment = require('../classes/ProjectEnvironment');
  8. const installHosts = (hosts) => {
  9. if (!isRoot()) {
  10. log.warn('Unable to set hosts because you need root privileges');
  11. } else {
  12. for (var ip in hosts) {
  13. const hostsString = hosts[ip].join(' ');
  14. log.log('Installing hosts for %s: %s', ip, hostsString);
  15. hostile.set(ip, hostsString);
  16. }
  17. }
  18. };
  19. const runServiceStart = (service, projectEnv) => {
  20. const env = projectEnv.getEnv();
  21. const scripts = [
  22. 'start.before',
  23. `start.before.${env}`,
  24. 'start',
  25. `start.${env}`,
  26. 'start.after',
  27. `start.after.${env}`,
  28. ];
  29. let chain = Promise.resolve();
  30. scripts.forEach(script => {
  31. chain = chain.then(() => {
  32. return new Promise(resolve => {
  33. try {
  34. const start = require(path.join(projectEnv.getCwd(), service, script));
  35. log.log(`\nExecuting %s script for %s...`, colors.bold(script), colors.bold(service));
  36. Promise
  37. .all([start({
  38. exec: (command, options) => {
  39. const opts = { ...projectEnv.getDockerOptions(), ...options };
  40. return docker.exec(service, command, opts);
  41. },
  42. log: (message) => {
  43. log.log('%s - %s', colors.bold(service), message);
  44. },
  45. env: projectEnv.getEnv()
  46. })])
  47. .catch(() => {
  48. })
  49. .then(() => {
  50. resolve();
  51. });
  52. } catch (ex) {
  53. resolve();
  54. }
  55. });
  56. });
  57. });
  58. return chain.then(() => {
  59. });
  60. };
  61. const runServices = async (projectEnv) => {
  62. await docker.buildAll(projectEnv.getDockerOptions());
  63. await docker.upAll(projectEnv.getDockerOptions());
  64. const services = await projectEnv.getServices();
  65. let promises = [];
  66. services.forEach(service => {
  67. promises.push(runServiceStart(service, projectEnv));
  68. });
  69. await Promise.all(promises);
  70. };
  71. module.exports = (env) => {
  72. try {
  73. const projectEnv = new ProjectEnvironment(process.cwd(), env);
  74. log.log("Starting project (%s environment)...", colors.bold(env));
  75. // Install hosts
  76. installHosts(projectEnv.getHosts());
  77. // Docker up services
  78. runServices(projectEnv);
  79. } catch (ex) {
  80. log.error(...ex);
  81. }
  82. };