Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Added 'start box' on cli daemon commands #4

Merged
merged 2 commits into from
Jul 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions packages/tcore-api/src/Helpers/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ import { ESocketRoom } from "@tago-io/tcore-sdk/types";
import chalk from "chalk";
import ora from "ora";
import { getSystemName } from "@tago-io/tcore-shared";
import boxen from "boxen";
import { getMainSettings } from "../Services/Settings";
import { plugins } from "../Plugins/Host";
import { io } from "../Socket/SocketServer";
import { getLocalIPs } from "../Services/Hardware";
// @ts-ignore
import pkg from "../../../../package.json";

/**
* Contains a history of all logs in the application and in the plugins.
Expand Down Expand Up @@ -79,3 +84,25 @@ export function internalLog(channel: string, ...args: any[]) {
console.log(colored, ...args);
}
}

/**
* Logs the "start box" with the localhost and internal ips.
*/
export async function logSystemStart(port?: number | string | null) {
const systemName = getSystemName();
const systemVers = pkg?.version;

const settings = await getMainSettings();
const realPort = port || settings.port;

const lines = [`${systemName} v${systemVers} is ready!`, "", `- Local: http://localhost:${realPort}`];

const netAddresses = getLocalIPs();
if (netAddresses[0]) {
lines.push(`- On your network: http://${netAddresses[0]}:${realPort}`);
}

console.log("");
console.log(chalk.green(boxen(lines.join("\n"), { padding: 1 })));
console.log("");
}
3 changes: 2 additions & 1 deletion packages/tcore-api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { installPlugin } from "./Plugins/Install";
import { uninstallPlugin, uninstallPluginByFolder } from "./Plugins/Uninstall";
import { startServer } from "./server";
import { log, logError } from "./Helpers/log";
import { log, logError, logSystemStart } from "./Helpers/log";
import { getPlatformAndArch } from "./Helpers/Platform";
import { downloadFile } from "./Helpers/Download";
import Plugin from "./Plugins/Plugin/Plugin";
Expand All @@ -16,6 +16,7 @@ export {
installPlugin,
log,
logError,
logSystemStart,
Plugin,
startServer,
uninstallPlugin,
Expand Down
15 changes: 3 additions & 12 deletions packages/tcore-api/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createServer } from "http";
import path from "path";
import express from "express";
import boxen from "boxen";
import cors from "cors";
import chalk from "chalk";
import ora from "ora";
Expand All @@ -25,10 +24,10 @@ import { getMainSettings } from "./Services/Settings";
import HardwareController from "./Controllers/Hardware";
import { setupSocketServer } from "./Socket/SocketServer";
import { shutdown } from "./Helpers/shutdown";
import { getLocalIPs } from "./Services/Hardware";
import { getModuleList } from "./Services/Plugins";
import { startCallbackInterval } from "./Plugins/Worker/Worker";
import { startActionScheduleTimer } from "./Services/ActionScheduler";
import { logSystemStart } from "./Helpers/log";

const app = express();
const httpServer = createServer(app);
Expand Down Expand Up @@ -141,19 +140,11 @@ async function listenOnApplicationPort() {

httpServer
.listen(port, () => {
const lines = [`${systemName} is ready!`, "", `- Local: http://localhost:${port}`];

const netAddresses = getLocalIPs();
if (netAddresses[0]) {
lines.push(`- On your network: http://${netAddresses[0]}:${port}`);
}

console.log("");
console.log(chalk.green(boxen(lines.join("\n"), { padding: 1 })));
console.log("");
logSystemStart();
})
.on("error", () => {
ora(chalk.redBright(`Could not start ${systemName} on port ${port}`)).fail();
ora(chalk.redBright(`Check if the port is not being used by another application`)).fail();
process.exit(1);
});
}
Expand Down
8 changes: 8 additions & 0 deletions packages/tcore-cli/src/Commands/Restart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from "path";
import fs from "fs";
import * as API from "@tago-io/tcore-api";
import chalk from "chalk";
import { IEnvironmentVariables } from "@tago-io/tcore-sdk/types";
import { getSystemName } from "@tago-io/tcore-shared";
import { pm2Connect, pm2Disconnect, pm2Restart, pm2GetApp } from "../Helpers/PM2";
import { log } from "../Helpers/Log";
Expand All @@ -20,11 +21,18 @@ export async function restart() {
const pm2LogPath = path.join(settingsPath, "tcore.log");
await fs.promises.unlink(pm2LogPath).catch(() => null);

// generate a type to access TCORE_PORT without `any`
type Pm2TCoreEnvironment = typeof app.pm2_env & IEnvironmentVariables;

// store the env in a variable to make it easier to access
const env = app.pm2_env as Pm2TCoreEnvironment;

await pm2Restart();

const newApp = await pm2GetApp();
if (newApp) {
log(`${getSystemName()} Server was ${chalk.green("successfully restarted")} with PID`, newApp.pid);
API.logSystemStart(env?.TCORE_PORT);
} else {
log(`${getSystemName()} Server ${chalk.redBright("could not be started")}.`);
log(`You can check the logs by running ${chalk.cyan("tcore logs")}`);
Expand Down
4 changes: 3 additions & 1 deletion packages/tcore-cli/src/Commands/Start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ async function startWithDaemon(opts: IStartOptions) {
try {
const systemName = getSystemName();
const exeName = path.basename(process.execPath);
const env = getEnv(opts);

await pm2Connect();

Expand Down Expand Up @@ -86,7 +87,7 @@ async function startWithDaemon(opts: IStartOptions) {
name: PM2_APP_NAME,
output: pm2LogPath,
error: pm2LogPath,
env: getEnv(opts),
env,
};

await pm2Start(startOptions);
Expand All @@ -95,6 +96,7 @@ async function startWithDaemon(opts: IStartOptions) {
if (newApp?.pm2_env?.status === "online") {
// successfully started new process
log(`${systemName} Server successfully ${chalk.green("started")} with PID`, newApp.pid);
API.logSystemStart(env.TCORE_PORT);
} else {
// for some reason pm2 could not start the script
log(`${systemName} Server ${chalk.redBright("could not be started")}.`);
Expand Down
12 changes: 12 additions & 0 deletions packages/tcore-sdk/src/Types/Common/Common.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,18 @@ export const zTagsAutoGen = z
.nullish()
.transform((e) => e ?? []); // use transform instead of `default` because `default` doesn't apply to `null`.

/**
* Environment variables for the application.
*/
export const zEnvironmentVariables = z.object({
TCORE_PORT: z.string().nullish(),
TCORE_DAEMON: z.string().nullish(),
TCORE_PLUGIN_FOLDER: z.string().nullish(),
TCORE_SETTINGS_FOLDER: z.string().nullish(),
TCORE_DATABASE_PLUGIN: z.string().nullish(),
});

export type IEnvironmentVariables = z.infer<typeof zEnvironmentVariables>;
export type TGenericID = string;
export type TGenericToken = string;
export type TDate = Date | number | null;
Expand Down