summaryrefslogtreecommitdiff
path: root/src/index.ts
blob: e5171a38f6178696f3cb958a366c20680e39fe04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
 * Misskey Core Entory Point!
 */

Error.stackTraceLimit = Infinity;

/**
 * Module dependencies
 */
import * as fs from 'fs';
import * as os from 'os';
import * as cluster from 'cluster';
const prominence = require('prominence');
import { log } from './utils/logger';
import * as chalk from 'chalk';
const git = require('git-last-commit');
const portUsed = require('tcp-port-used');
import ProgressBar from './utils/cli/progressbar';
import initdb from './db/mongodb';
import checkDependencies from './utils/check-dependencies';

// Init babel
require('babel-core/register');
require('babel-polyfill');

const env = process.env.NODE_ENV;
const IS_PRODUCTION = env === 'production';
const IS_DEBUG = !IS_PRODUCTION;

global.config = require('./config').default(`${__dirname}/../.config/config.yml`);

/**
 * Initialize state
 */
enum State {
	success,
	warn,
	failed
}

// Set process title
process.title = 'Misskey';

// Start app
main();

/**
 * Init proccess
 */
function main(): void {
	// Master
	if (cluster.isMaster) {
		master();
	} else { // Workers
		worker();
	}
}

/**
 * Init master proccess
 */
async function master(): Promise<void> {
	let state: State;

	try {
		// initialize app
		state = await init();
	} catch (e) {
		console.error(e);
		process.exit(1);
	}

	switch (state) {
		case State.failed:
			log('Error', chalk.red('Fatal error occurred :('));
			process.exit();
			return;
		case State.warn:
			log('Warn', chalk.yellow('Some problem(s) :|'));
			break;
		case State.success:
			log('Info', chalk.green('OK :)'));
			break;
	}

	// Spawn workers
	spawn(() => {
		console.log(chalk.bold.green(`\nMisskey Core is now running. [port:${config.port}]`));

		// Listen new workers
		cluster.on('fork', worker => {
			console.log(`Process forked: [${worker.id}]`);
		});

		// Listen online workers
		cluster.on('online', worker => {
			console.log(`Process is now online: [${worker.id}]`);
		});

		// Listen for dying workers
		cluster.on('exit', worker => {
			// Replace the dead worker,
			// we're not sentimental
			console.log(chalk.red(`[${worker.id}] died :(`));
			cluster.fork();
		});
	});
}

/**
 * Init worker proccess
 */
function worker(): void {
	// Register config
	global.config = config;

	// Init mongo
	initdb().then(db => {
		global.db = db;

		// start server
		require('./server');
	}, err => {
		console.error(err);
		process.exit(0);
	});
}

/**
 * Init app
 */
async function init(): Promise<State> {
	log('Info', 'Welcome to Misskey!');

	log('Info', chalk.bold('Misskey Core <aoi>'));

	let warn = false;

	// Get commit info
	try {
		const commit = await prominence(git).getLastCommit();
		log('Info', `commit: ${commit.shortHash} ${commit.author.name} <${commit.author.email}>`);
		log('Info', `        ${new Date(parseInt(commit.committedOn, 10) * 1000)}`);
	} catch (e) {
		// noop
	}

	log('Info', 'Initializing...');

	if (IS_DEBUG) {
		log('Warn', 'It is not in the Production mode. Do not use in the Production environment.');
	}

	log('Info', `environment: ${env}`);

	// Get machine info
	const totalmem = (os.totalmem() / 1024 / 1024 / 1024).toFixed(1);
	const freemem = (os.freemem() / 1024 / 1024 / 1024).toFixed(1);
	log('Info', `MACHINE: ${os.hostname()}`);
	log('Info', `MACHINE: CPU: ${os.cpus().length}core`);
	log('Info', `MACHINE: MEM: ${totalmem}GB (available: ${freemem}GB)`);

	if (!fs.existsSync(`${__dirname}/../.config/config.yml`)) {
		log('Error', 'Configuration not found');
		return State.failed;
	}

	log('Info', 'Success to load configuration');
	log('Info', `maintainer: ${config.maintainer}`);

	checkDependencies();

	// Check if a port is being used
	if (await portUsed.check(config.port)) {
		log('Error', `Port: ${config.port} is already used!`);
		return State.failed;
	}

	// Try to connect to MongoDB
	try {
		const db = await initdb(config);
		log('Info', 'Success to connect to MongoDB');
		db.close();
	} catch (e) {
		log('Error', `MongoDB: ${e}`);
		return State.failed;
	}

	return warn ? State.warn : State.success;
}

/**
 * Spawn workers
 */
function spawn(callback: any): void {
	// Count the machine's CPUs
	const cpuCount = os.cpus().length;

	const progress = new ProgressBar(cpuCount, 'Starting workers');

	// Create a worker for each CPU
	for (let i = 0; i < cpuCount; i++) {
		const worker = cluster.fork();
		worker.on('message', message => {
			if (message === 'ready') {
				progress.increment();
			}
		});
	}

	// On all workers started
	progress.on('complete', () => {
		callback();
	});
}

// Dying away...
process.on('exit', () => {
	log('Info', 'Bye.');
});