This commit is contained in:
2024-09-26 18:32:50 +05:00
parent 9167785656
commit 86864ac19e
11 changed files with 164 additions and 175 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
SERVER_LOCATION=a1 SERVER_LOCATION=a1
SERVER_NAME=s1 SERVER_NAME=s6
SERVER_TYPE=demo SERVER_TYPE=prod
PORT=3000 PORT=3000
MONGO_URI=mongodb://root:p62Z!ZatgY25@194.26.138.94:27017 MONGO_URI=mongodb://root:p62Z!ZatgY25@194.26.138.94:27017
+52 -29
View File
@@ -30,7 +30,7 @@ require("dotenv/config");
const db_1 = __importDefault(require("./config/db")); const db_1 = __importDefault(require("./config/db"));
const express_1 = __importStar(require("express")); const express_1 = __importStar(require("express"));
const cors_1 = __importDefault(require("cors")); const cors_1 = __importDefault(require("cors"));
const os_1 = __importDefault(require("os")); const os_1 = __importStar(require("os"));
const util_1 = __importDefault(require("util")); const util_1 = __importDefault(require("util"));
const child_process_1 = require("child_process"); const child_process_1 = require("child_process");
const tree_kill_1 = __importDefault(require("tree-kill")); const tree_kill_1 = __importDefault(require("tree-kill"));
@@ -45,6 +45,10 @@ const serverLocation = process.env.SERVER_LOCATION;
const serverName = process.env.SERVER_NAME; const serverName = process.env.SERVER_NAME;
const serverType = process.env.SERVER_TYPE; const serverType = process.env.SERVER_TYPE;
const serverHostname = os_1.default.hostname(); const serverHostname = os_1.default.hostname();
const nets = (0, os_1.networkInterfaces)();
const localIP = Object.entries(nets)
.find((net) => net[0] === "Ethernet")?.[1]
?.find((obj) => obj.family === "IPv4")?.address;
async function updateSessionServerData(data) { async function updateSessionServerData(data) {
try { try {
await SessionServer_1.default.findOneAndUpdate({ hostname: serverHostname }, data); await SessionServer_1.default.findOneAndUpdate({ hostname: serverHostname }, data);
@@ -74,7 +78,6 @@ async function getGpuMemoryFree() {
async function getAvailablePorts() { async function getAvailablePorts() {
const cirrusPorts = [14000, 14001, 14002]; const cirrusPorts = [14000, 14001, 14002];
for (const cirrusPort of cirrusPorts) { for (const cirrusPort of cirrusPorts) {
console.log(cirrusPort);
const activeSession = await ActiveSession_1.default.exists({ const activeSession = await ActiveSession_1.default.exists({
location: serverLocation, location: serverLocation,
name: serverName, name: serverName,
@@ -86,8 +89,8 @@ async function getAvailablePorts() {
return { cirrusPort, uePort }; return { cirrusPort, uePort };
} }
} }
async function startSession(buildName) { async function startSession(buildName, ownerIp, endAt) {
const filePath = `C:/PixelStreaming/builds/${buildName}/${buildName}.exe`; const filePath = `C:/pixel-streaming/builds/${buildName}/${buildName}.exe`;
const availablePorts = await getAvailablePorts(); const availablePorts = await getAvailablePorts();
if (!availablePorts) { if (!availablePorts) {
console.log("No available ports"); console.log("No available ports");
@@ -95,7 +98,7 @@ async function startSession(buildName) {
} }
const { cirrusPort, uePort } = availablePorts; const { cirrusPort, uePort } = availablePorts;
const cirrusProcess = (0, child_process_1.execFile)("node", [ const cirrusProcess = (0, child_process_1.execFile)("node", [
`C:/PixelStreaming/signalling-server/cirrus.js`, `C:/pixel-streaming/signalling-server/cirrus.js`,
`--StreamerPort`, `--StreamerPort`,
`${uePort}`, `${uePort}`,
`--HttpPort`, `--HttpPort`,
@@ -127,27 +130,43 @@ async function startSession(buildName) {
console.log("UE application was not started"); console.log("UE application was not started");
return; return;
} }
const activeSession = await ActiveSession_1.default.create({ const type = serverType;
location: serverLocation, try {
name: serverName, const activeSession = await ActiveSession_1.default.create({
buildName, location: serverLocation,
cirrusPort, name: serverName,
uePort, buildName,
cirrusProcessId, type,
ueProcessId, cirrusPort,
}); uePort,
const activeSessionId = activeSession.id; cirrusProcessId,
return activeSessionId; ueProcessId,
ownerIp,
endAt,
localIP,
});
return activeSession;
}
catch (error) {
(0, tree_kill_1.default)(cirrusProcessId);
(0, tree_kill_1.default)(ueProcessId);
console.log(error.message);
}
} }
async function endSession(activeSessionId) { async function endSession(activeSessionId) {
const activeSession = await ActiveSession_1.default.findByIdAndDelete(activeSessionId); try {
if (!activeSession) { const activeSession = await ActiveSession_1.default.findByIdAndDelete(activeSessionId);
console.log("Session with this ID not found"); if (!activeSession) {
return; console.log("Session with this ID not found");
return;
}
(0, tree_kill_1.default)(activeSession.cirrusProcessId);
(0, tree_kill_1.default)(activeSession.ueProcessId);
console.log("Kill session");
}
catch (error) {
console.log(error.message);
} }
(0, tree_kill_1.default)(activeSession.cirrusProcessId);
(0, tree_kill_1.default)(activeSession.ueProcessId);
console.log("Kill session");
} }
async function init() { async function init() {
try { try {
@@ -156,6 +175,7 @@ async function init() {
name: serverName, name: serverName,
type: serverType, type: serverType,
hostname: serverHostname, hostname: serverHostname,
localIP,
}, { upsert: true, new: true }); }, { upsert: true, new: true });
getGpuMemoryFree(); getGpuMemoryFree();
} }
@@ -166,14 +186,17 @@ async function init() {
} }
} }
app.post("/start", async (req, res) => { app.post("/start", async (req, res) => {
console.log(req.query); for (const [key, value] of Object.entries(req.body)) {
const buildName = req.body.buildName; if (value === "null")
if (!buildName) { req.body[key] = undefined;
}
const { buildName, ownerIp, endAt } = req.body;
console.log("req.body", req.body);
if (!buildName || !ownerIp) {
return res.json({ error: 1 }); return res.json({ error: 1 });
} }
const result = await startSession(buildName); const activeSession = await startSession(buildName, ownerIp, endAt);
console.log("Result: ", result); res.json(activeSession);
res.json({ ok: 1 });
}); });
app.post("/end", async (req, res) => { app.post("/end", async (req, res) => {
const activeSessionId = req.body.activeSessionId; const activeSessionId = req.body.activeSessionId;
+12
View File
@@ -11,6 +11,9 @@ const activeSessionSchema = new mongoose_1.Schema({
buildName: { buildName: {
type: String, type: String,
}, },
type: {
type: String,
},
uePort: { uePort: {
type: Number, type: Number,
}, },
@@ -23,6 +26,15 @@ const activeSessionSchema = new mongoose_1.Schema({
cirrusProcessId: { cirrusProcessId: {
type: Number, type: Number,
}, },
ownerIp: {
type: String,
},
endAt: {
type: Date || null,
},
localIP: {
type: String,
},
}, { }, {
timestamps: true, timestamps: true,
toJSON: { virtuals: true }, toJSON: { virtuals: true },
+3
View File
@@ -18,6 +18,9 @@ const sessionServerSchema = new mongoose_1.Schema({
gpuMemoryFree: { gpuMemoryFree: {
type: Number, type: Number,
}, },
localIP: {
type: String,
},
}, { }, {
timestamps: true, timestamps: true,
toJSON: { virtuals: true }, toJSON: { virtuals: true },
+1 -1
View File
@@ -2,7 +2,7 @@
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express"); const express_1 = require("express");
const router = (0, express_1.Router)(); const router = (0, express_1.Router)();
router.get("/", async (req, res) => { router.get("/", async (_req, res) => {
res.json({ ok: 1 }); res.json({ ok: 1 });
}); });
const testRouter = router; const testRouter = router;
+2 -3
View File
@@ -1,9 +1,8 @@
module.exports = { module.exports = {
apps: [ apps: [
{ {
name: "session-server", name: "session-server:3000",
exec_mode: "cluster", script: "./dist",
script: "./dist/index.js",
}, },
], ],
}; };
+62 -33
View File
@@ -2,7 +2,7 @@ import "dotenv/config";
import connectDB from "./config/db"; import connectDB from "./config/db";
import express, { json } from "express"; import express, { json } from "express";
import cors from "cors"; import cors from "cors";
import os from "os"; import os, { networkInterfaces } from "os";
import util from "util"; import util from "util";
import { exec, execFile } from "child_process"; import { exec, execFile } from "child_process";
import treeKill from "tree-kill"; import treeKill from "tree-kill";
@@ -22,6 +22,12 @@ const serverName = process.env.SERVER_NAME;
const serverType = process.env.SERVER_TYPE; const serverType = process.env.SERVER_TYPE;
const serverHostname = os.hostname(); const serverHostname = os.hostname();
const nets = networkInterfaces();
const localIP = Object.entries(nets)
.find((net) => net[0] === "Ethernet")?.[1]
?.find((obj) => obj.family === "IPv4")?.address;
async function updateSessionServerData(data: any) { async function updateSessionServerData(data: any) {
try { try {
await SessionServer.findOneAndUpdate({ hostname: serverHostname }, data); await SessionServer.findOneAndUpdate({ hostname: serverHostname }, data);
@@ -59,8 +65,6 @@ async function getAvailablePorts() {
const cirrusPorts = [14000, 14001, 14002]; const cirrusPorts = [14000, 14001, 14002];
for (const cirrusPort of cirrusPorts) { for (const cirrusPort of cirrusPorts) {
console.log(cirrusPort);
const activeSession = await ActiveSession.exists({ const activeSession = await ActiveSession.exists({
location: serverLocation, location: serverLocation,
name: serverName, name: serverName,
@@ -75,8 +79,12 @@ async function getAvailablePorts() {
} }
} }
async function startSession(buildName: string) { async function startSession(
const filePath = `C:/PixelStreaming/builds/${buildName}/${buildName}.exe`; buildName: string,
ownerIp: string,
endAt?: string
) {
const filePath = `C:/pixel-streaming/builds/${buildName}/${buildName}.exe`;
const availablePorts = await getAvailablePorts(); const availablePorts = await getAvailablePorts();
@@ -88,7 +96,7 @@ async function startSession(buildName: string) {
const { cirrusPort, uePort } = availablePorts; const { cirrusPort, uePort } = availablePorts;
const cirrusProcess = execFile("node", [ const cirrusProcess = execFile("node", [
`C:/PixelStreaming/signalling-server/cirrus.js`, `C:/pixel-streaming/signalling-server/cirrus.js`,
`--StreamerPort`, `--StreamerPort`,
`${uePort}`, `${uePort}`,
`--HttpPort`, `--HttpPort`,
@@ -126,33 +134,50 @@ async function startSession(buildName: string) {
return; return;
} }
const activeSession = await ActiveSession.create({ const type = serverType;
location: serverLocation,
name: serverName,
buildName,
cirrusPort,
uePort,
cirrusProcessId,
ueProcessId,
});
const activeSessionId = activeSession.id; try {
const activeSession = await ActiveSession.create({
location: serverLocation,
name: serverName,
buildName,
type,
cirrusPort,
uePort,
cirrusProcessId,
ueProcessId,
ownerIp,
endAt,
localIP,
});
return activeSessionId; return activeSession;
} catch (error) {
treeKill(cirrusProcessId);
treeKill(ueProcessId);
console.log((error as Error).message);
}
} }
async function endSession(activeSessionId: string) { async function endSession(activeSessionId: string) {
const activeSession = await ActiveSession.findByIdAndDelete(activeSessionId); try {
const activeSession = await ActiveSession.findByIdAndDelete(
activeSessionId
);
if (!activeSession) { if (!activeSession) {
console.log("Session with this ID not found"); console.log("Session with this ID not found");
return; return;
}
treeKill(activeSession.cirrusProcessId as number);
treeKill(activeSession.ueProcessId as number);
console.log("Kill session");
} catch (error) {
console.log((error as Error).message);
} }
treeKill(activeSession.cirrusProcessId as number);
treeKill(activeSession.ueProcessId as number);
console.log("Kill session");
} }
async function init() { async function init() {
@@ -164,6 +189,7 @@ async function init() {
name: serverName, name: serverName,
type: serverType, type: serverType,
hostname: serverHostname, hostname: serverHostname,
localIP,
}, },
{ upsert: true, new: true } { upsert: true, new: true }
); );
@@ -177,18 +203,21 @@ async function init() {
} }
app.post("/start", async (req, res) => { app.post("/start", async (req, res) => {
console.log(req.query); for (const [key, value] of Object.entries(req.body)) {
const buildName: string = req.body.buildName; if (value === "null") req.body[key] = undefined;
}
if (!buildName) { const { buildName, ownerIp, endAt } = req.body;
console.log("req.body", req.body);
if (!buildName || !ownerIp) {
return res.json({ error: 1 }); return res.json({ error: 1 });
} }
const result = await startSession(buildName); const activeSession = await startSession(buildName, ownerIp, endAt);
console.log("Result: ", result); res.json(activeSession);
res.json({ ok: 1 });
}); });
app.post("/end", async (req, res) => { app.post("/end", async (req, res) => {
+12
View File
@@ -11,6 +11,9 @@ const activeSessionSchema = new Schema(
buildName: { buildName: {
type: String, type: String,
}, },
type: {
type: String,
},
uePort: { uePort: {
type: Number, type: Number,
}, },
@@ -23,6 +26,15 @@ const activeSessionSchema = new Schema(
cirrusProcessId: { cirrusProcessId: {
type: Number, type: Number,
}, },
ownerIp: {
type: String,
},
endAt: {
type: Date || null,
},
localIP: {
type: String,
},
}, },
{ {
timestamps: true, timestamps: true,
+3
View File
@@ -18,6 +18,9 @@ const sessionServerSchema = new Schema(
gpuMemoryFree: { gpuMemoryFree: {
type: Number, type: Number,
}, },
localIP: {
type: String,
},
}, },
{ {
timestamps: true, timestamps: true,
+1 -1
View File
@@ -2,7 +2,7 @@ import { Router } from "express";
const router = Router(); const router = Router();
router.get("/", async (req, res) => { router.get("/", async (_req, res) => {
res.json({ ok: 1 }); res.json({ ok: 1 });
}); });
+14 -106
View File
@@ -1,110 +1,18 @@
{ {
"compilerOptions": { "compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */ "target": "ESNext",
"module": "CommonJS",
/* Projects */ "moduleResolution": "Node",
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ "outDir": "./dist",
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ "esModuleInterop": true,
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ "forceConsistentCasingInFileNames": true,
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ "strict": true,
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ "noUnusedLocals": true,
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ "noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* Language and Environment */ "skipLibCheck": true
"target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
"rootDir": "./src" /* Specify the root folder within your source files. */,
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
"resolveJsonModule": true /* Enable importing .json files. */,
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}, },
"include": ["src"] "ts-node": {
"transpileOnly": true
}
} }