瀏覽代碼

Fixati percorsi e aggiunti file mancanti

Mirko Domenici 4 年之前
父節點
當前提交
75c223c784
共有 7 個文件被更改,包括 295 次插入8 次删除
  1. 29 0
      .gitignore
  2. 94 0
      bin/classes/ProjectEnvironment.js
  3. 0 0
      bin/cmd.js
  4. 130 0
      bin/commands/start.js
  5. 34 0
      bin/commands/stop.js
  6. 0 0
      bin/inc/log.js
  7. 8 8
      package.json

+ 29 - 0
.gitignore

@@ -0,0 +1,29 @@
+# ---> Node
+# Logs
+logs
+*.log
+npm-debug.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+
+# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (http://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directory
+# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
+node_modules

+ 94 - 0
bin/classes/ProjectEnvironment.js

@@ -0,0 +1,94 @@
+const path = require('path');
+const colors = require('colors');
+const fs = require('fs');
+const docker = require('docker-compose');
+
+class ProjectEnvironment {
+  constructor(cwd, env) {
+    this._cwd = cwd;
+    this._env = env;
+
+    this._dockerOptions = {
+      cwd: cwd,
+      config: [
+        'docker-compose.yml'
+      ],
+      log: true
+    };
+
+    this._setEnvironment(env);
+  }
+
+  _setEnvironment(env) {
+    if (
+      !this._loadConfigFile() ||
+      !this._loadDockerComposeFile()
+    ) {
+      throw [`Unable to load %s environment`, colors.bold(env)];
+    }
+  }
+
+  _loadConfigFile() {
+    const configFilename = `config.${this._env}.json`;
+    const configFilepath = path.join(this._cwd, configFilename);
+
+    console.log(configFilepath);
+
+    if (!fs.existsSync(configFilepath)) {
+      return false;
+    }
+
+    try {
+      const config = JSON.parse(fs.readFileSync(configFilepath, 'utf8'));
+      this._config = config;
+    } catch (ex) {
+      return false;
+    }
+
+    return true;
+  }
+
+  _loadDockerComposeFile() {
+    const dockerComposeFilename = `docker-compose.${this._env}.yml`;
+    const dockerComposeFilepath = path.join(this._cwd, dockerComposeFilename);
+
+    if (!fs.existsSync(dockerComposeFilepath)) {
+      return false;
+    }
+
+    this._dockerOptions.config.push(dockerComposeFilename);
+
+    return true;
+  }
+
+  setDockerOptions(options) {
+    this._dockerOptions = { ...this._dockerOptions, ...options };
+  }
+
+  getDockerOptions() {
+    return this._dockerOptions;
+  }
+
+  getCwd() {
+    return this._cwd;
+  }
+
+  getEnv() {
+    return this._env;
+  }
+
+  getHosts() {
+    return this._config['hosts'] || {};
+  }
+
+  async getServices() {
+    const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } });
+
+    const services = data.out.split('\n');
+    services.pop();
+
+    return services;
+  }
+}
+
+module.exports = ProjectEnvironment;

+ 0 - 0
cmd.js → bin/cmd.js


+ 130 - 0
bin/commands/start.js

@@ -0,0 +1,130 @@
+const path = require('path');
+const isRoot = require('is-root');
+const hostile = require('hostile');
+const colors = require('colors');
+const docker = require('docker-compose');
+const log = require('../inc/log');
+const shell = require('shelljs');
+const ProjectEnvironment = require('../classes/ProjectEnvironment');
+
+const installHosts = (hosts) => {
+  if (!isRoot()) {
+    log.warn('Unable to set hosts because you need root privileges');
+  } else {
+    for (var ip in hosts) {
+      const hostsString = hosts[ip].join(' ');
+
+      log.log('Installing hosts for %s: %s', ip, hostsString);
+      hostile.set(ip, hostsString);
+    }
+  }
+};
+
+const runServiceHook = (hook, service, projectEnv) => {
+  const env = projectEnv.getEnv();
+  const scripts = [
+    `${hook}.before`,
+    `${hook}.before.${env}`,
+    `${hook}`,
+    `${hook}.${env}`,
+    `${hook}.after`,
+    `${hook}.after.${env}`,
+  ];
+
+  let scriptArgument = {
+    service: service,
+    log: (message) => {
+      log.log('%s - %s', colors.bold(service), message);
+    },
+    env: projectEnv.getEnv(),
+    shell: (cmd) => {
+      shell.cd(path.join(projectEnv.getCwd(), service));
+      const ret = shell.exec(cmd, { fatal: true });
+      if (ret.code !== 0) {
+        throw ret.code;
+      }
+    }
+  };
+
+  switch (hook) {
+    case "start":
+      scriptArgument.exec = (command, options) => {
+        const opts = { ...projectEnv.getDockerOptions(), ...options };
+        return docker.exec(service, command, opts);
+      };
+      break;
+    default:
+      break;
+  }
+
+  let chain = Promise.resolve();
+
+  scripts.forEach(script => {
+    chain = chain.then(() => {
+      return new Promise((resolve, reject) => {
+        try {
+          const scriptFunction = require(path.join(projectEnv.getCwd(), service, script));
+          log.log(`\nExecuting %s script for %s...`, colors.bold(script), colors.bold(service));
+
+          try {
+            Promise
+              .all([scriptFunction({ ...scriptArgument })])
+              .then(() => {
+                resolve();
+              })
+              .catch((e) => {
+                reject(e);
+              });
+          } catch (ex) {
+            reject(ex);
+          }
+        } catch (ex) {
+          resolve();
+        }
+      });
+    });
+  });
+
+  return chain.then(() => { });
+};
+
+const runServices = async (projectEnv) => {
+  const services = await projectEnv.getServices();
+
+  let preparePromises = [];
+  services.forEach(service => {
+    preparePromises.push(runServiceHook("prepare", service, projectEnv));
+  });
+  try {
+    await Promise.all(preparePromises);
+  } catch (e) {
+    log.error(e);
+    return;
+  }
+
+  await docker.buildAll(projectEnv.getDockerOptions());
+  await docker.upAll(projectEnv.getDockerOptions());
+
+  let startPromises = [];
+  services.forEach(service => {
+    startPromises.push(runServiceHook("start", service, projectEnv));
+  });
+  await Promise.all(startPromises);
+};
+
+module.exports = (env) => {
+  try {
+    const projectEnv = new ProjectEnvironment(process.cwd(), env);
+
+    log.log("Starting project (%s environment)...", colors.bold(env));
+
+    // Install hosts
+    installHosts(projectEnv.getHosts());
+
+    // Docker up services
+    runServices(projectEnv);
+
+  } catch (ex) {
+    log.error(...ex);
+  }
+};

+ 34 - 0
bin/commands/stop.js

@@ -0,0 +1,34 @@
+const path = require('path');
+const isRoot = require('is-root');
+const hostile = require('hostile');
+const colors = require('colors');
+const docker = require('docker-compose');
+const log = require('../inc/log');
+const ProjectEnvironment = require('../classes/ProjectEnvironment');
+
+const uninstallHosts = (hosts) => {
+  if (!isRoot()) {
+    log.warn('Unable to unset hosts because you need root privileges');
+  } else {
+    for (var ip in hosts) {
+      const hostsString = hosts[ip].join(' ');
+
+      log.log('Uninstalling hosts for %s: %s', ip, hostsString);
+      hostile.remove(ip, hostsString);
+    }
+  }
+};
+
+const stopServices = async (projectEnv) => {
+  await docker.down(projectEnv.getDockerOptions());
+};
+
+module.exports = (env) => {
+  const projectEnv = new ProjectEnvironment(process.cwd(), env);
+
+  log.log("Shutting down project (%s environment)...", colors.bold(env));
+
+  uninstallHosts(projectEnv.getHosts());
+
+  stopServices(projectEnv);
+};

+ 0 - 0
log.js → bin/inc/log.js


+ 8 - 8
package.json

@@ -1,5 +1,5 @@
 {
-  "_from": "git+https://git.iamdev.it/IAMdev/dockerize-project.git#v2.1.1",
+  "_from": "git+http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
   "_id": "dockerize-project@2.1.1",
   "_inBundle": false,
   "_integrity": "",
@@ -7,19 +7,19 @@
   "_phantomChildren": {},
   "_requested": {
     "type": "git",
-    "raw": "dockerize-project@git+https://git.iamdev.it/IAMdev/dockerize-project.git#v2.1.1",
+    "raw": "dockerize-project@git+http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
     "name": "dockerize-project",
     "escapedName": "dockerize-project",
-    "rawSpec": "git+https://git.iamdev.it/IAMdev/dockerize-project.git#v2.1.1",
-    "saveSpec": "git+https://git.iamdev.it/IAMdev/dockerize-project.git#v2.1.1",
-    "fetchSpec": "https://git.iamdev.it/IAMdev/dockerize-project.git",
+    "rawSpec": "git+http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
+    "saveSpec": "git+http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
+    "fetchSpec": "http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
     "gitCommittish": "v2.1.1"
   },
   "_requiredBy": [
     "#DEV:/"
   ],
-  "_resolved": "git+https://git.iamdev.it/IAMdev/dockerize-project.git#b9e32ba2b10816123a58dd8def112dcfc13282c8",
-  "_spec": "dockerize-project@git+https://git.iamdev.it/IAMdev/dockerize-project.git#v2.1.1",
+  "_resolved": "git+http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
+  "_spec": "dockerize-project@git+http://git.makemoneyorganization.com:3000/si/dockerize-project.git",
   "_where": "/home/mdomenici/Progetti/bc",
   "author": {
     "name": "IAMdev"
@@ -42,7 +42,7 @@
   "name": "dockerize-project",
   "repository": {
     "type": "git",
-    "url": "https://git.dev.iamdev.it/IAMdev/dockerize-project.git"
+    "url": "http://git.dev.makemoneyorganization.com:3000/si/dockerize-project.git"
   },
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1"