feat: 초기 프로젝트 설정 및 룰.md 파일 추가

This commit is contained in:
2025-07-28 09:53:31 +09:00
commit 09a4d38512
8165 changed files with 1021855 additions and 0 deletions

View File

@@ -0,0 +1,122 @@
var path = require('path');
var fs = require('fs');
var os = require('os');
var spawn = require('child_process').spawn;
var chalk = require('chalk');
var parallel = require('async/parallel');
var Configuration = require('../../Configuration.js');
var cst = require('../../../constants.js');
var Common = require('../../Common');
var Utility = require('../../Utility.js');
var readline = require('readline')
var INTERNAL_MODULES = {
'deep-monitoring': {
dependencies: [{name: 'v8-profiler-node8'}, {name: 'gc-stats'}, {name: 'event-loop-inspector'}]
},
'gc-stats': {name: 'gc-stats'},
'event-loop-inspector': {name: 'event-loop-inspector'},
'v8-profiler': {name: 'v8-profiler-node8'},
'profiler': {name: 'v8-profiler-node8'},
'typescript': {dependencies: [{name: 'typescript'}, {name: 'ts-node@latest'}]},
'livescript': {name: 'livescript'},
'coffee-script': {name: 'coffee-script', message: 'Coffeescript v1 support'},
'coffeescript': {name: 'coffeescript', message: 'Coffeescript v2 support'}
};
module.exports = {
install,
INTERNAL_MODULES,
installMultipleModules
}
function install(module, cb, verbose) {
if (!module || !module.name || module.name.length === 0) {
return cb(new Error('No module name !'));
}
if (typeof verbose === 'undefined') {
verbose = true;
}
installLangModule(module.name, function (err) {
var display = module.message || module.name;
if (err) {
if (verbose) { Common.printError(cst.PREFIX_MSG_MOD_ERR + chalk.bold.green(display + ' installation has FAILED (checkout previous logs)')); }
return cb(err);
}
if (verbose) { Common.printOut(cst.PREFIX_MSG + chalk.bold.green(display + ' ENABLED')); }
return cb();
});
}
function installMultipleModules(modules, cb, post_install) {
var functionList = [];
for (var i = 0; i < modules.length; i++) {
functionList.push((function (index) {
return function (callback) {
var module = modules[index];
if (typeof modules[index] === 'string') {
module = {name: modules[index]};
}
install(module, function ($post_install, err, $index, $modules) {
try {
var install_instance = spawn(post_install[modules[index]], {
stdio : 'inherit',
windowsHide: true,
env: process.env,
shell : true,
cwd : process.cwd()
});
Common.printOut(cst.PREFIX_MSG_MOD + 'Running configuraton script.');
}
catch(e)
{
Common.printOut(cst.PREFIX_MSG_MOD + 'No configuraton script found.');
}
callback(null, { module: module, err: err });
}, false);
};
})(i));
}
parallel(functionList, function (err, results) {
for (var i = 0; i < results.length; i++) {
var display = results[i].module.message || results[i].module.name;
if (results[i].err) {
err = results[i].err;
Common.printError(cst.PREFIX_MSG_MOD_ERR + chalk.bold.green(display + ' installation has FAILED (checkout previous logs)'));
} else {
Common.printOut(cst.PREFIX_MSG + chalk.bold.green(display + ' ENABLED'));
}
}
if(cb) cb(err);
});
};
function installLangModule(module_name, cb) {
var node_module_path = path.resolve(path.join(__dirname, '../../../'));
Common.printOut(cst.PREFIX_MSG_MOD + 'Calling ' + chalk.bold.red('[NPM]') + ' to install ' + module_name + ' ...');
var install_instance = spawn(cst.IS_WINDOWS ? 'npm.cmd' : 'npm', ['install', module_name, '--loglevel=error'], {
stdio : 'inherit',
env: process.env,
shell : true,
cwd : node_module_path
});
install_instance.on('close', function(code) {
if (code > 0)
return cb(new Error('Module install failed'));
return cb(null);
});
install_instance.on('error', function (err) {
console.error(err.stack || err);
});
};

View File

@@ -0,0 +1,148 @@
/**
* Copyright 2013-2022 the PM2 project authors. All rights reserved.
* Use of this source code is governed by a license that
* can be found in the LICENSE file.
*/
var path = require('path');
var eachLimit = require('async/eachLimit');
var forEachLimit = require('async/forEachLimit');
var Configuration = require('../../Configuration.js');
var cst = require('../../../constants.js');
var Common = require('../../Common');
var NPM = require('./NPM.js')
var TAR = require('./TAR.js')
var LOCAL = require('./LOCAL.js')
var Modularizer = module.exports = {};
/**
* PM2 Module System.
*/
Modularizer.install = function (CLI, module_name, opts, cb) {
module_name = module_name.replace(/[;`|]/g, "");
if (typeof(opts) == 'function') {
cb = opts;
opts = {};
}
if (LOCAL.INTERNAL_MODULES.hasOwnProperty(module_name)) {
Common.logMod(`Adding dependency ${module_name} to PM2 Runtime`);
var currentModule = LOCAL.INTERNAL_MODULES[module_name];
if (currentModule && currentModule.hasOwnProperty('dependencies')) {
LOCAL.installMultipleModules(currentModule.dependencies, cb);
} else {
LOCAL.install(currentModule, cb);
}
}
else if (module_name == '.') {
Common.logMod(`Installing local NPM module`);
return NPM.localStart(CLI, opts, cb)
}
else if (opts.tarball || /\.tar\.gz$/i.test(module_name)) {
Common.logMod(`Installing TAR module`);
TAR.install(CLI, module_name, opts, cb)
}
else {
Common.logMod(`Installing NPM ${module_name} module`);
NPM.install(CLI, module_name, opts, cb)
}
};
/**
* Launch All Modules
* Used PM2 at startup
*/
Modularizer.launchModules = function(CLI, cb) {
var modules = Modularizer.listModules();
if (!modules) return cb();
// 1#
function launchNPMModules(cb) {
if (!modules.npm_modules) return launchTARModules(cb)
eachLimit(Object.keys(modules.npm_modules), 1, function(module_name, next) {
NPM.start(CLI, modules, module_name, next)
}, function() {
launchTARModules(cb)
});
}
// 2#
function launchTARModules(cb) {
if (!modules.tar_modules) return cb()
eachLimit(Object.keys(modules.tar_modules), 1, function(module_name, next) {
TAR.start(CLI, module_name, next)
}, function() {
return cb ? cb(null) : false;
});
}
launchNPMModules(cb)
}
Modularizer.package = function(CLI, module_path, cb) {
var fullpath = process.cwd()
if (module_path)
fullpath = require('path').resolve(module_path)
TAR.package(fullpath, process.cwd(), cb)
}
/**
* Uninstall module
*/
Modularizer.uninstall = function(CLI, module_name, cb) {
Common.printOut(cst.PREFIX_MSG_MOD + 'Uninstalling module ' + module_name);
var modules_list = Modularizer.listModules();
if (module_name == 'all') {
if (!modules_list) return cb();
return forEachLimit(Object.keys(modules_list.npm_modules), 1, function(module_name, next) {
NPM.uninstall(CLI, module_name, next)
}, () => {
forEachLimit(Object.keys(modules_list.tar_modules), 1, function(module_name, next) {
TAR.uninstall(CLI, module_name, next)
}, cb)
});
}
if (modules_list.npm_modules[module_name]) {
NPM.uninstall(CLI, module_name, cb)
} else if (modules_list.tar_modules[module_name]) {
TAR.uninstall(CLI, module_name, cb)
}
else {
Common.errMod('Unknown module')
CLI.exitCli(1)
}
};
/**
* List modules based on modules present in ~/.pm2/modules/ folder
*/
Modularizer.listModules = function() {
return {
npm_modules: Configuration.getSync(cst.MODULE_CONF_PREFIX) || {},
tar_modules: Configuration.getSync(cst.MODULE_CONF_PREFIX_TAR) || {}
}
};
Modularizer.getAdditionalConf = function(app_name) {
return NPM.getModuleConf(app_name)
};
Modularizer.publish = function(PM2, folder, opts, cb) {
if (opts.npm == true) {
NPM.publish(opts, cb)
}
else {
TAR.publish(PM2, folder, cb)
}
};
Modularizer.generateSample = function(app_name, cb) {
NPM.generateSample(app_name, cb)
};

437
api.hyungi.net/node_modules/pm2/lib/API/Modules/NPM.js generated vendored Normal file
View File

@@ -0,0 +1,437 @@
const path = require('path');
const fs = require('fs');
const os = require('os');
const spawn = require('child_process').spawn;
const chalk = require('chalk');
const readline = require('readline')
const which = require('../../tools/which.js')
const sexec = require('../../tools/sexec.js')
const copydirSync = require('../../tools/copydirSync.js')
const deleteFolderRecursive = require('../../tools/deleteFolderRecursive.js')
var Configuration = require('../../Configuration.js');
var cst = require('../../../constants.js');
var Common = require('../../Common');
var Utility = require('../../Utility.js');
module.exports = {
install,
uninstall,
start,
publish,
generateSample,
localStart,
getModuleConf
}
/**
* PM2 Module System.
* Features:
* - Installed modules are listed separately from user applications
* - Always ON, a module is always up along PM2, to stop it, you need to uninstall it
* - Install a runnable module from NPM/Github/HTTP (require a package.json only)
* - Some modules add internal PM2 depencencies (like typescript, profiling...)
* - Internally it uses NPM install (https://docs.npmjs.com/cli/install)
* - Auto discover script to launch (first it checks the apps field, then bin and finally main attr)
* - Generate sample module via pm2 module:generate <module_name>
*/
function localStart(PM2, opts, cb) {
var proc_path = '',
cmd = '',
conf = {};
Common.printOut(cst.PREFIX_MSG_MOD + 'Installing local module in DEVELOPMENT MODE with WATCH auto restart');
proc_path = process.cwd();
cmd = path.join(proc_path, cst.DEFAULT_MODULE_JSON);
Common.extend(opts, {
cmd : cmd,
development_mode : true,
proc_path : proc_path
});
return StartModule(PM2, opts, function(err, dt) {
if (err) return cb(err);
Common.printOut(cst.PREFIX_MSG_MOD + 'Module successfully installed and launched');
return cb(null, dt);
});
}
function generateSample(app_name, cb) {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function samplize(module_name) {
var cmd1 = 'git clone https://github.com/pm2-hive/sample-module.git ' + module_name + '; cd ' + module_name + '; rm -rf .git';
var cmd2 = 'cd ' + module_name + ' ; sed -i "s:sample-module:'+ module_name +':g" package.json';
var cmd3 = 'cd ' + module_name + ' ; npm install';
Common.printOut(cst.PREFIX_MSG_MOD + 'Getting sample app');
sexec(cmd1, function(err) {
if (err) Common.printError(cst.PREFIX_MSG_MOD_ERR + err.message);
sexec(cmd2, function(err) {
console.log('');
sexec(cmd3, function(err) {
console.log('');
Common.printOut(cst.PREFIX_MSG_MOD + 'Module sample created in folder: ', path.join(process.cwd(), module_name));
console.log('');
Common.printOut('Start module in development mode:');
Common.printOut('$ cd ' + module_name + '/');
Common.printOut('$ pm2 install . ');
console.log('');
Common.printOut('Module Log: ');
Common.printOut('$ pm2 logs ' + module_name);
console.log('');
Common.printOut('Uninstall module: ');
Common.printOut('$ pm2 uninstall ' + module_name);
console.log('');
Common.printOut('Force restart: ');
Common.printOut('$ pm2 restart ' + module_name);
return cb ? cb() : false;
});
});
});
}
if (app_name) return samplize(app_name);
rl.question(cst.PREFIX_MSG_MOD + "Module name: ", function(module_name) {
samplize(module_name);
});
}
function publish(opts, cb) {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var semver = require('semver');
var package_file = path.join(process.cwd(), 'package.json');
var package_json = require(package_file);
package_json.version = semver.inc(package_json.version, 'minor');
Common.printOut(cst.PREFIX_MSG_MOD + 'Incrementing module to: %s@%s',
package_json.name,
package_json.version);
rl.question("Write & Publish? [Y/N]", function(answer) {
if (answer != "Y")
return cb();
fs.writeFile(package_file, JSON.stringify(package_json, null, 2), function(err, data) {
if (err) return cb(err);
Common.printOut(cst.PREFIX_MSG_MOD + 'Publishing module - %s@%s',
package_json.name,
package_json.version);
sexec('npm publish', function(code) {
Common.printOut(cst.PREFIX_MSG_MOD + 'Module - %s@%s successfully published',
package_json.name,
package_json.version);
Common.printOut(cst.PREFIX_MSG_MOD + 'Pushing module on Git');
sexec('git add . ; git commit -m "' + package_json.version + '"; git push origin master', function(code) {
Common.printOut(cst.PREFIX_MSG_MOD + 'Installable with pm2 install %s', package_json.name);
return cb(null, package_json);
});
});
});
});
}
function moduleExistInLocalDB(CLI, module_name, cb) {
var modules = Configuration.getSync(cst.MODULE_CONF_PREFIX);
if (!modules) return cb(false);
var module_name_only = Utility.getCanonicModuleName(module_name)
modules = Object.keys(modules);
return cb(modules.indexOf(module_name_only) > -1 ? true : false);
};
function install(CLI, module_name, opts, cb) {
moduleExistInLocalDB(CLI, module_name, function (exists) {
if (exists) {
Common.logMod('Module already installed. Updating.');
Rollback.backup(module_name);
return uninstall(CLI, module_name, function () {
return continueInstall(CLI, module_name, opts, cb);
});
}
return continueInstall(CLI, module_name, opts, cb);
})
}
// Builtin Node Switch
function getNPMCommandLine(module_name, install_path) {
if (which('npm')) {
return spawn.bind(this, cst.IS_WINDOWS ? 'npm.cmd' : 'npm', ['install', module_name, '--loglevel=error', '--prefix', `"${install_path}"` ], {
stdio : 'inherit',
env: process.env,
windowsHide: true,
shell : true
})
}
else {
return spawn.bind(this, cst.BUILTIN_NODE_PATH, [cst.BUILTIN_NPM_PATH, 'install', module_name, '--loglevel=error', '--prefix', `"${install_path}"`], {
stdio : 'inherit',
env: process.env,
windowsHide: true,
shell : true
})
}
}
function continueInstall(CLI, module_name, opts, cb) {
Common.printOut(cst.PREFIX_MSG_MOD + 'Calling ' + chalk.bold.red('[NPM]') + ' to install ' + module_name + ' ...');
var canonic_module_name = Utility.getCanonicModuleName(module_name);
var install_path = path.join(cst.DEFAULT_MODULE_PATH, canonic_module_name);
require('mkdirp')(install_path)
.then(function() {
process.chdir(os.homedir());
var install_instance = getNPMCommandLine(module_name, install_path)();
install_instance.on('close', finalizeInstall);
install_instance.on('error', function (err) {
console.error(err.stack || err);
});
});
function finalizeInstall(code) {
if (code != 0) {
// If install has failed, revert to previous module version
return Rollback.revert(CLI, module_name, function() {
return cb(new Error('Installation failed via NPM, module has been restored to prev version'));
});
}
Common.printOut(cst.PREFIX_MSG_MOD + 'Module downloaded');
var proc_path = path.join(install_path, 'node_modules', canonic_module_name);
var package_json_path = path.join(proc_path, 'package.json');
// Append default configuration to module configuration
try {
var conf = JSON.parse(fs.readFileSync(package_json_path).toString()).config;
if (conf) {
Object.keys(conf).forEach(function(key) {
Configuration.setSyncIfNotExist(canonic_module_name + ':' + key, conf[key]);
});
}
} catch(e) {
Common.printError(e);
}
opts = Common.extend(opts, {
cmd : package_json_path,
development_mode : false,
proc_path : proc_path
});
Configuration.set(cst.MODULE_CONF_PREFIX + ':' + canonic_module_name, {
uid : opts.uid,
gid : opts.gid
}, function(err, data) {
if (err) return cb(err);
StartModule(CLI, opts, function(err, dt) {
if (err) return cb(err);
if (process.env.PM2_PROGRAMMATIC === 'true')
return cb(null, dt);
CLI.conf(canonic_module_name, function() {
Common.printOut(cst.PREFIX_MSG_MOD + 'Module successfully installed and launched');
Common.printOut(cst.PREFIX_MSG_MOD + 'Checkout module options: `$ pm2 conf`');
return cb(null, dt);
});
});
});
}
}
function start(PM2, modules, module_name, cb) {
Common.printOut(cst.PREFIX_MSG_MOD + 'Starting NPM module ' + module_name);
var install_path = path.join(cst.DEFAULT_MODULE_PATH, module_name);
var proc_path = path.join(install_path, 'node_modules', module_name);
var package_json_path = path.join(proc_path, 'package.json');
var opts = {};
// Merge with embedded configuration inside module_conf (uid, gid)
Common.extend(opts, modules[module_name]);
// Merge meta data to start module properly
Common.extend(opts, {
// package.json path
cmd : package_json_path,
// starting mode
development_mode : false,
// process cwd
proc_path : proc_path
});
StartModule(PM2, opts, function(err, dt) {
if (err) console.error(err);
return cb();
})
}
function uninstall(CLI, module_name, cb) {
var module_name_only = Utility.getCanonicModuleName(module_name)
var proc_path = path.join(cst.DEFAULT_MODULE_PATH, module_name_only);
Configuration.unsetSync(cst.MODULE_CONF_PREFIX + ':' + module_name_only);
CLI.deleteModule(module_name_only, function(err, data) {
console.log('Deleting', proc_path)
if (module_name != '.' && proc_path.includes('modules') === true) {
deleteFolderRecursive(proc_path)
}
if (err) {
Common.printError(err);
return cb(err);
}
return cb(null, data);
});
}
function getModuleConf(app_name) {
if (!app_name) throw new Error('No app_name defined');
var module_conf = Configuration.getAllSync();
var additional_env = {};
if (!module_conf[app_name]) {
additional_env = {};
additional_env[app_name] = {};
}
else {
additional_env = Common.clone(module_conf[app_name]);
additional_env[app_name] = JSON.stringify(module_conf[app_name]);
}
return additional_env;
}
function StartModule(CLI, opts, cb) {
if (!opts.cmd && !opts.package) throw new Error('module package.json not defined');
if (!opts.development_mode) opts.development_mode = false;
var package_json = require(opts.cmd || opts.package);
/**
* Script file detection
* 1- *apps* field (default pm2 json configuration)
* 2- *bin* field
* 3- *main* field
*/
if (!package_json.apps && !package_json.pm2) {
package_json.apps = {};
if (package_json.bin) {
var bin = Object.keys(package_json.bin)[0];
package_json.apps.script = package_json.bin[bin];
}
else if (package_json.main) {
package_json.apps.script = package_json.main;
}
}
Common.extend(opts, {
cwd : opts.proc_path,
watch : opts.development_mode,
force_name : package_json.name,
started_as_module : true
});
// Start the module
CLI.start(package_json, opts, function(err, data) {
if (err) return cb(err);
if (opts.safe) {
Common.printOut(cst.PREFIX_MSG_MOD + 'Monitoring module behavior for potential issue (5secs...)');
var time = typeof(opts.safe) == 'boolean' ? 3000 : parseInt(opts.safe);
return setTimeout(function() {
CLI.describe(package_json.name, function(err, apps) {
if (err || apps[0].pm2_env.restart_time > 2) {
return Rollback.revert(CLI, package_json.name, function() {
return cb(new Error('New Module is instable, restored to previous version'));
});
}
return cb(null, data);
});
}, time);
}
return cb(null, data);
});
};
var Rollback = {
revert : function(CLI, module_name, cb) {
var canonic_module_name = Utility.getCanonicModuleName(module_name);
var backup_path = path.join(require('os').tmpdir(), canonic_module_name);
var module_path = path.join(cst.DEFAULT_MODULE_PATH, canonic_module_name);
try {
fs.statSync(backup_path)
} catch(e) {
return cb(new Error('no backup found'));
}
Common.printOut(cst.PREFIX_MSG_MOD + chalk.bold.red('[[[[[ Module installation failure! ]]]]]'));
Common.printOut(cst.PREFIX_MSG_MOD + chalk.bold.red('[RESTORING TO PREVIOUS VERSION]'));
CLI.deleteModule(canonic_module_name, function() {
// Delete failing module
if (module_name.includes('modules') === true)
deleteFolderRecursive(module_path)
// Restore working version
copydirSync(backup_path, path.join(cst.DEFAULT_MODULE_PATH, canonic_module_name));
var proc_path = path.join(module_path, 'node_modules', canonic_module_name);
var package_json_path = path.join(proc_path, 'package.json');
// Start module
StartModule(CLI, {
cmd : package_json_path,
development_mode : false,
proc_path : proc_path
}, cb);
});
},
backup : function(module_name) {
// Backup current module
var tmpdir = require('os').tmpdir();
var canonic_module_name = Utility.getCanonicModuleName(module_name);
var module_path = path.join(cst.DEFAULT_MODULE_PATH, canonic_module_name);
copydirSync(module_path, path.join(tmpdir, canonic_module_name));
}
}

362
api.hyungi.net/node_modules/pm2/lib/API/Modules/TAR.js generated vendored Normal file
View File

@@ -0,0 +1,362 @@
var Configuration = require('../../Configuration.js');
var cst = require('../../../constants.js');
var Common = require('../../Common');
var forEachLimit = require('async/forEachLimit');
const sexec = require('../../tools/sexec.js');
const deleteFolderRecursive = require('../../tools/deleteFolderRecursive.js');
var path = require('path');
var fs = require('fs');
var os = require('os');
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
var execSync = require('child_process').execSync;
module.exports = {
install,
uninstall,
start,
publish,
packager
}
/**
* Module management to manage tarball packages
*
* pm2 install http.tar.gz
* pm2 uninstall http
*
* - the first and only folder in the tarball must be called module (tar zcvf http module/)
* - a package.json must be present with attribute "name", "version" and "pm2" to declare apps to run
*/
function install(PM2, module_filepath, opts, cb) {
// Remote file retrieval
if (module_filepath.includes('http') === true) {
var target_file = module_filepath.split('/').pop()
var target_filepath = path.join(os.tmpdir(), target_file)
opts.install_url = module_filepath
return retrieveRemote(module_filepath, target_filepath, (err) => {
if (err) {
Common.errMod(err)
process.exit(1)
}
installLocal(PM2, target_filepath, opts, cb)
})
}
// Local install
installLocal(PM2, module_filepath, opts, cb)
}
function retrieveRemote(url, dest, cb) {
Common.logMod(`Retrieving remote package ${url}...`)
var wget = spawn('wget', [url, '-O', dest, '-q'], {
stdio : 'inherit',
env: process.env,
windowsHide: true,
shell : true
})
wget.on('error', (err) => {
console.error(err.stack || err)
})
wget.on('close', (code) => {
if (code !== 0)
return cb(new Error('Could not download'))
return cb(null)
})
}
function installLocal(PM2, module_filepath, opts, cb) {
Common.logMod(`Installing package ${module_filepath}`)
// Get module name by unpacking the module/package.json only and read the name attribute
getModuleName(module_filepath, function(err, module_name) {
if (err) return cb(err)
Common.logMod(`Module name is ${module_name}`)
Common.logMod(`Depackaging module...`)
var install_path = path.join(cst.DEFAULT_MODULE_PATH, module_name);
require('mkdirp').sync(install_path)
var install_instance = spawn('tar', ['zxf', module_filepath, '-C', install_path, '--strip-components 1'], {
stdio : 'inherit',
env: process.env,
shell : true
})
install_instance.on('close', function(code) {
Common.logMod(`Module depackaged in ${install_path}`)
if (code == 0)
return runInstall(PM2, install_path, module_name, opts, cb)
return PM2.exitCli(1)
});
install_instance.on('error', function (err) {
console.error(err.stack || err);
});
})
}
function deleteModulePath(module_name) {
var sanitized = module_name.replace(/\./g, '')
deleteFolderRecursive(path.join(cst.DEFAULT_MODULE_PATH, module_name));
}
function runInstall(PM2, target_path, module_name, opts, cb) {
var config_file = path.join(target_path, 'package.json')
var conf
try {
conf = require(config_file)
module_name = conf.name
} catch(e) {
Common.errMod(new Error('Cannot find package.json file with name attribute at least'));
}
// Force with the name in the package.json
opts.started_as_module = true
opts.cwd = target_path
if (needPrefix(conf))
opts.name_prefix = module_name
if (opts.install) {
Common.logMod(`Running YARN install...`)
sexec(`cd ${target_path} ; yarn install`, {silent: false}, function(code) {
// Start apps under "apps" or "pm2" attribute
Common.logMod(`Starting ${target_path}`)
PM2.start(conf, opts, function(err, data) {
if (err) return cb(err)
Configuration.setSync(`${cst.MODULE_CONF_PREFIX_TAR}:${module_name}`, {
source: 'tarball',
install_url: opts.install_url,
installed_at: Date.now()
})
Common.logMod(`Module INSTALLED and STARTED`)
return cb(null, 'Module installed & Started')
})
})
}
else {
PM2.start(conf, opts, function(err, data) {
if (err) return cb(err)
Configuration.setSync(`${cst.MODULE_CONF_PREFIX_TAR}:${module_name}`, {
source: 'tarball',
install_url: opts.install_url,
installed_at: Date.now()
})
Common.logMod(`Module INSTALLED and STARTED`)
return cb(null, 'Module installed & Started')
})
}
}
function start(PM2, module_name, cb) {
var module_path = path.join(cst.DEFAULT_MODULE_PATH, module_name);
Common.printOut(cst.PREFIX_MSG_MOD + 'Starting TAR module ' + module_name);
var package_json_path = path.join(module_path, 'package.json');
var module_conf = Configuration.getSync(`${cst.MODULE_CONF_PREFIX_TAR}:${module_name}`)
try {
var conf = require(package_json_path)
} catch(e) {
Common.printError(`Could not find package.json as ${package_json_path}`)
return cb()
}
var opts = {};
opts.started_as_module = true
opts.cwd = module_path
if (module_conf.install_url)
opts.install_url = module_conf.install_url
if (needPrefix(conf))
opts.name_prefix = module_name
PM2.start(conf, opts, function(err, data) {
if (err) {
Common.printError(`Could not start ${module_name} ${module_path}`)
return cb()
}
Common.printOut(`${cst.PREFIX_MSG_MOD} Module ${module_name} STARTED`)
return cb();
})
}
/**
* Retrieve from module package.json the name of each application
* delete process and delete folder
*/
function uninstall(PM2, module_name, cb) {
var module_path = path.join(cst.DEFAULT_MODULE_PATH, module_name);
Common.logMod(`Removing ${module_name} from auto startup`)
try {
var pkg = require(path.join(module_path, 'package.json'))
} catch(e) {
Common.errMod('Could not retrieve module package.json');
return cb(e)
}
var apps = pkg.apps || pkg.pm2
apps = [].concat(apps);
/**
* Some time a module can have multiple processes
*/
forEachLimit(apps, 1, (app, next) => {
var app_name
if (!app.name) {
Common.renderApplicationName(app)
}
if (apps.length > 1)
app_name = `${module_name}:${app.name}`
else if (apps.length == 1 && pkg.name != apps[0].name)
app_name = `${module_name}:${app.name}`
else
app_name = app.name
PM2._operate('deleteProcessId', app_name, () => {
deleteModulePath(module_name)
next()
})
}, () => {
Configuration.unsetSync(`${cst.MODULE_CONF_PREFIX_TAR}:${module_name}`)
cb(null)
})
}
/**
* Uncompress only module/package.json and retrieve the "name" attribute in the package.json
*/
function getModuleName(module_filepath, cb) {
var tmp_folder = path.join(os.tmpdir(), cst.MODULE_BASEFOLDER)
var install_instance = spawn('tar', ['zxf', module_filepath, '-C', os.tmpdir(), `${cst.MODULE_BASEFOLDER}/package.json`], {
stdio : 'inherit',
env: process.env,
shell : true
})
install_instance.on('close', function(code) {
try {
var pkg = JSON.parse(fs.readFileSync(path.join(tmp_folder, `package.json`)))
return cb(null, pkg.name)
} catch(e) {
return cb(e)
}
});
}
function packager(module_path, target_path, cb) {
var base_folder = path.dirname(module_path)
var module_folder_name = path.basename(module_path)
var pkg = require(path.join(module_path, 'package.json'))
var pkg_name = `${module_folder_name}-v${pkg.version.replace(/\./g, '-')}.tar.gz`
var target_fullpath = path.join(target_path, pkg_name)
var cmd = `tar zcf ${target_fullpath} -C ${base_folder} --transform 's,${module_folder_name},module,' ${module_folder_name}`
Common.logMod(`Gziping ${module_path} to ${target_fullpath}`)
var tar = exec(cmd, (err, sto, ste) => {
if (err) {
console.log(sto.toString().trim())
console.log(ste.toString().trim())
}
})
tar.on('close', function (code) {
cb(code == 0 ? null : code, {
package_name: pkg_name,
path: target_fullpath
})
})
}
function publish(PM2, folder, cb) {
var target_folder = folder ? path.resolve(folder) : process.cwd()
try {
var pkg = JSON.parse(fs.readFileSync(path.join(target_folder, 'package.json')).toString())
} catch(e) {
Common.errMod(`${process.cwd()} module does not contain any package.json`)
process.exit(1)
}
if (!pkg.name) throw new Error('Attribute name should be present')
if (!pkg.version) throw new Error('Attribute version should be present')
if (!pkg.pm2 && !pkg.apps) throw new Error('Attribute apps should be present')
var current_path = target_folder
var module_name = path.basename(current_path)
var target_path = os.tmpdir()
Common.logMod(`Starting publishing procedure for ${module_name}@${pkg.version}`)
packager(current_path, target_path, (err, res) => {
if (err) {
Common.errMod('Can\'t package, exiting')
process.exit(1)
}
Common.logMod(`Package [${pkg.name}] created in path ${res.path}`)
var data = {
module_data: {
file: res.path,
content_type: 'content/gzip'
},
id: pkg.name,
name: pkg.name,
version: pkg.version
};
var uri = `${PM2.pm2_configuration.registry}/api/v1/modules`
Common.logMod(`Sending Package to remote ${pkg.name} ${uri}`)
require('needle')
.post(uri, data, { multipart: true }, function(err, res, body) {
if (err) {
Common.errMod(err)
process.exit(1)
}
if (res.statusCode !== 200) {
Common.errMod(`${pkg.name}-${pkg.version}: ${res.body.msg}`)
process.exit(1)
}
Common.logMod(`Module ${module_name} published under version ${pkg.version}`)
process.exit(0)
})
})
}
function needPrefix(conf) {
if ((conf.apps && conf.apps.length > 1) ||
(conf.pm2 && conf.pm2.length > 1) ||
(conf.apps.length == 1 && conf.name != conf.apps[0].name))
return true
return false
}

View File

@@ -0,0 +1,46 @@
var fs = require('fs');
var conf = require('../../../constants.js');
function find_extensions(folder, ext, ret)
{
try {
fs.accessSync(folder, fs.constants.R_OK);
} catch (err) {
return;
}
if(fs.statSync(folder).isDirectory() && folder.indexOf('node_modules') == -1 && (fs.statSync(folder)["mode"] & 4))
{
fs.readdirSync(folder).forEach(file => {
var tmp;
if(Number.parseInt(folder.lastIndexOf('/') + 1) === folder.length)
tmp = folder + file;
else
tmp = folder + '/' + file;
if(fs.statSync(tmp).isDirectory())
find_extensions(tmp, ext, ret);
else
{
var p = true;
for(var i = 0; i < ext.length;i++)
if(ext[i].test(file))
p = false;
if(p)
ret.push(folder + '/' + file);
}
});
}
}
module.exports.make_available_extension = function make_available_extension(opts, ret)
{
if(typeof opts == 'object' && typeof ret == 'object')
{
var mas = opts.ext.split(',');
for(var i = 0;i < mas.length;i++)
mas[i] = '.' + mas[i];
var res = [];
for(var i = 0;i < mas.length;i++)
res[i] = new RegExp(mas[i] + '$');
find_extensions(process.cwd(), res, ret);
}
}

View File

@@ -0,0 +1,120 @@
/***************************
*
* Module methods
*
**************************/
var cst = require('../../../constants.js');
var Common = require('../../Common.js');
var chalk = require('chalk');
var forEachLimit = require('async/forEachLimit');
var Modularizer = require('./Modularizer.js');
module.exports = function(CLI) {
/**
* Install / Update a module
*/
CLI.prototype.install = function(module_name, opts, cb) {
var that = this;
if (typeof(opts) == 'function') {
cb = opts;
opts = {};
}
Modularizer.install(this, module_name, opts, function(err, data) {
if (err) {
Common.printError(cst.PREFIX_MSG_ERR + (err.message || err));
return cb ? cb(Common.retErr(err)) : that.speedList(cst.ERROR_EXIT);
}
return cb ? cb(null, data) : that.speedList(cst.SUCCESS_EXIT);
});
};
/**
* Uninstall a module
*/
CLI.prototype.uninstall = function(module_name, cb) {
var that = this;
Modularizer.uninstall(this, module_name, function(err, data) {
if (err)
return cb ? cb(Common.retErr(err)) : that.speedList(cst.ERROR_EXIT);
return cb ? cb(null, data) : that.speedList(cst.SUCCESS_EXIT);
});
};
CLI.prototype.launchAll = function(CLI, cb) {
Modularizer.launchModules(CLI, cb);
};
CLI.prototype.package = function(module_path, cb) {
Modularizer.package(this, module_path, (err, res) => {
if (err) {
Common.errMod(err)
return cb ? cb(err) : this.exitCli(1)
}
Common.logMod(`Module packaged in ${res.path}`)
return cb ? cb(err) : this.exitCli(0)
})
};
/**
* Publish module on NPM + Git push
*/
CLI.prototype.publish = function(folder, opts, cb) {
var that = this;
Modularizer.publish(this, folder, opts, function(err, data) {
if (err)
return cb ? cb(Common.retErr(err)) : that.speedList(cst.ERROR_EXIT);
return cb ? cb(null, data) : that.speedList(cst.SUCCESS_EXIT);
});
};
/**
* Publish module on NPM + Git push
*/
CLI.prototype.generateModuleSample = function(app_name, cb) {
var that = this;
Modularizer.generateSample(app_name, function(err, data) {
if (err)
return cb ? cb(Common.retErr(err)) : that.exitCli(cst.ERROR_EXIT);
return cb ? cb(null, data) : that.exitCli(cst.SUCCESS_EXIT);
});
};
/**
* Special delete method
*/
CLI.prototype.deleteModule = function(module_name, cb) {
var that = this;
var found_proc = [];
this.Client.getAllProcess(function(err, procs) {
if (err) {
Common.printError('Error retrieving process list: ' + err);
return cb(Common.retErr(err));
}
procs.forEach(function(proc) {
if (proc.pm2_env.name == module_name && proc.pm2_env.pmx_module) {
found_proc.push(proc.pm_id);
}
});
if (found_proc.length == 0)
return cb();
that._operate('deleteProcessId', found_proc[0], function(err) {
if (err) return cb(Common.retErr(err));
Common.printOut('In memory process deleted');
return cb();
});
});
};
};