feat: add proxy

This commit is contained in:
Anselm Stordeur
2019-01-16 19:54:30 +01:00
committed by Rainer Killinger
commit fbe1a65cd1
23 changed files with 3656 additions and 0 deletions

65
src/cli.ts Normal file
View File

@@ -0,0 +1,65 @@
import {execSync} from 'child_process';
import * as config from 'config';
import * as Dockerode from 'dockerode';
import {readFile, writeFileSync} from 'fs-extra';
import {render} from 'mustache';
import {ConfigFile, logger} from './common';
import {getContainers, getTemplateView} from './main';
// handle unhandled promise rejections
process.on('unhandledRejection', (error: Error) => {
logger.error(error.message);
logger.info(error.stack);
process.exit(1);
});
let containerHashCache = '';
const configFile: ConfigFile = config.util.toObject();
/**
* Reads the container information from the docker socket and updates
* the nginx config if necessary
*
* The function will call itself again every 10s
*/
async function updateNginxConfig() {
const containers = await getContainers();
const containerHash = containers.map((container: Dockerode.ContainerInfo) => {
return container.Id;
}).join(',');
// if containers changed -> write config file, reload nginx
if (containerHash !== containerHashCache) {
logger.log('docker container changed');
logger.log('Generating new NGINX configuration');
// render nginx config file
const nginxConfig = render(await readFile('nginx.conf.template', 'utf8'), await getTemplateView(containers));
logger.log(`containers (${containerHash}) matched the configuration.`);
containerHashCache = containerHash;
logger.log(`Writing new config file "${configFile.output}"`);
// overwrite nginx config file with our rendered one
writeFileSync(configFile.output, nginxConfig, 'utf8');
logger.log('Executing "nginx -s reload" to tell nginx to reload the configuration file');
execSync('nginx -s reload');
}
}
function forever() {
// start the process of dynamic nginx configuration
updateNginxConfig().then(() => {
// check for changes again in 10 seconds
setTimeout(forever, 10000);
}).catch((err) => {
throw err;
});
}
// start the process that checks the docker socket periodically
forever();