UNPKG

7.11 kBJavaScriptView Raw
1/*
2 * Copyright 2018 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13'use strict';
14
15const path = require('path');
16const http = require('http');
17const https = require('https');
18const util = require('util');
19
20const fse = require('fs-extra');
21const pem = require('pem');
22const _ = require('lodash');
23const {
24 error, debug, info, rootLogger, FileLogger,
25} = require('@adobe/helix-log');
26const app = require('./app');
27const git = require('./git');
28const { resolveRepositoryPath } = require('./utils');
29
30const DEFAULT_REPO_ROOT = './repos';
31const DEFAULT_HTTP_PORT = 5000;
32const DEFAULT_HTTPS_PORT = 5443;
33const DEFAULT_HOST = '0.0.0.0';
34
35process.on('uncaughtException', (err) => {
36 error('encountered uncaught exception at process level', err);
37 // in case of fatal errors which cause process termination errors sometimes don't get logged:
38 // => print error directly to console
39 /* eslint no-console: off */
40 console.log('encountered uncaught exception at process level', err);
41});
42
43process.on('unhandledRejection', (reason, p) => {
44 error(`encountered unhandled promise rejection at process level: ${p}, reason: ${reason.stack || reason}`);
45});
46
47/**
48 * Current state of the server
49 */
50const serverState = {
51 httpSrv: null,
52 httpsSrv: null,
53};
54
55function applyDefaults(options) {
56 const opts = options || {};
57 opts.repoRoot = opts.repoRoot || DEFAULT_REPO_ROOT;
58 opts.virtualRepos = opts.virtualRepos || {};
59
60 opts.listen = opts.listen || {};
61 opts.listen.http = _.defaults(opts.listen.http, {
62 port: DEFAULT_HTTP_PORT,
63 host: DEFAULT_HOST,
64 });
65 if (opts.listen.https) {
66 opts.listen.https = _.defaults(opts.listen.https, {
67 port: DEFAULT_HTTPS_PORT,
68 host: DEFAULT_HOST,
69 });
70 }
71 return opts;
72}
73
74async function initConfiguration(rawConfig) {
75 try {
76 const config = applyDefaults(rawConfig);
77
78 // root dir of repositories
79 config.repoRoot = path.resolve(config.repoRoot);
80 await fse.ensureDir(config.repoRoot);
81
82 // configure logger
83 config.logs = config.logs || {};
84 config.logs.logsDir = path.normalize(config.logs.logsDir || 'logs');
85 await fse.ensureDir(config.logs.logsDir);
86 rootLogger.loggers.set( // Using a uuid in the name here makes collisions extremely unlikely
87 'git-server-errors-6ae5f55e-dbb3-46a0-a596-c238e713c1cc',
88 new FileLogger(path.join(config.logs.logsDir, 'error.log'), { level: config.logs.level || 'info' }),
89 );
90
91 debug(`configuration successfully read: ${config.configPath}`);
92
93 return config;
94 } catch (e) {
95 throw new Error(`unable to initialize the configuration: ${e.message}`);
96 }
97}
98
99async function readConfiguration() {
100 try {
101 let configPath = path.join(__dirname, 'config.js');
102
103 const exists = await fse.pathExists(configPath);
104 if (!exists) {
105 configPath = path.join(process.cwd(), 'config.js');
106 }
107
108 /* eslint-disable global-require */
109 /* eslint-disable import/no-dynamic-require */
110 const config = require(configPath);
111 config.configPath = configPath;
112 return config;
113 } catch (e) {
114 throw new Error(`unable to read the configuration: ${e.message}`);
115 }
116}
117
118async function startHttpServer(config) {
119 const { host, port } = config.listen.http;
120
121 return new Promise((resolve, reject) => {
122 const srv = http.createServer(app(config)).listen(port, host, (err) => {
123 if (err) {
124 reject(new Error(`unable to start start http server: ${err.message}`));
125 } else {
126 info(`[${process.pid}] HTTP: listening on port ${srv.address().port}`);
127 resolve(srv);
128 }
129 });
130 });
131}
132
133async function startHttpsServer(config) {
134 const {
135 host, port, key, cert,
136 } = config.listen.https;
137
138 const createCertificate = util.promisify(pem.createCertificate);
139
140 try {
141 let options;
142 if (key && cert) {
143 options = {
144 key: await fse.readFile(key, 'utf8'),
145 cert: await fse.readFile(cert, 'utf8'),
146 };
147 } else {
148 const keys = await createCertificate({ selfSigned: true });
149 options = {
150 key: keys.serviceKey,
151 cert: keys.certificate,
152 };
153 }
154
155 return new Promise((resolve, reject) => {
156 const srv = https.createServer(options, app(config)).listen(port, host, (err) => {
157 if (err) {
158 reject(new Error(`unable to start start https server: ${err.message}`));
159 } else {
160 info(`[${process.pid}] HTTPS: listening on port ${srv.address().port}`);
161 resolve(srv);
162 }
163 });
164 });
165 } catch (e) {
166 throw new Error(`unable to start start https server: ${e.message}`);
167 }
168}
169
170async function stopHttpServer() {
171 if (!serverState.httpSrv) {
172 return Promise.resolve();
173 }
174 return new Promise((resolve, reject) => {
175 serverState.httpSrv.close((err) => {
176 if (err) {
177 reject(new Error(`Error while stopping http server: ${err}`));
178 } else {
179 info('HTTP: server stopped.');
180 serverState.httpSrv = null;
181 resolve();
182 }
183 });
184 });
185}
186
187async function stopHttpsServer() {
188 if (!serverState.httpsSrv) {
189 return Promise.resolve();
190 }
191 return new Promise((resolve, reject) => {
192 serverState.httpsSrv.close((err) => {
193 if (err) {
194 reject(new Error(`Error while stopping https server: ${err}`));
195 } else {
196 info('HTTPS: server stopped.');
197 serverState.httpsSrv = null;
198 resolve();
199 }
200 });
201 });
202}
203
204async function start(rawConfig) {
205 const cfg = rawConfig || await readConfiguration();
206 return initConfiguration(cfg)
207 // setup and start the server
208 .then(async (config) => {
209 serverState.httpSrv = await startHttpServer(config);
210 // issue #218: https is optional
211 if (config.listen.https) {
212 serverState.httpsSrv = await startHttpsServer(config);
213 }
214 return {
215 httpPort: serverState.httpSrv.address().port,
216 httpsPort: serverState.httpsSrv ? serverState.httpsSrv.address().port : -1,
217 };
218 })
219 // handle errors during initialization
220 .catch((err) => {
221 const msg = `error during startup, exiting... : ${err.message}`;
222 error(msg);
223 throw Error(msg);
224 });
225}
226
227async function getRepoInfo(rawConfig, owner, repo) {
228 const cfg = rawConfig || await readConfiguration();
229 const repPath = resolveRepositoryPath(await initConfiguration(cfg), owner, repo);
230 const currentBranch = await git.currentBranch(repPath);
231 return { owner, repo, currentBranch };
232}
233
234async function stop() {
235 await stopHttpServer();
236 await stopHttpsServer();
237}
238
239module.exports = {
240 start,
241 stop,
242 getRepoInfo,
243};