From 86864ac19e91fa87f697bc88d5466a84fab8b011 Mon Sep 17 00:00:00 2001 From: inmake Date: Thu, 26 Sep 2024 18:32:50 +0500 Subject: [PATCH] upd --- .env | 4 +- dist/index.js | 81 ++++++++++++++--------- dist/models/ActiveSession.js | 12 ++++ dist/models/SessionServer.js | 3 + dist/routes/test.js | 2 +- ecosystem.config.js | 5 +- src/index.ts | 95 +++++++++++++++++---------- src/models/ActiveSession.ts | 12 ++++ src/models/SessionServer.ts | 3 + src/routes/test.ts | 2 +- tsconfig.json | 120 ++++------------------------------- 11 files changed, 164 insertions(+), 175 deletions(-) diff --git a/.env b/.env index 1296afe..a303baa 100644 --- a/.env +++ b/.env @@ -1,5 +1,5 @@ SERVER_LOCATION=a1 -SERVER_NAME=s1 -SERVER_TYPE=demo +SERVER_NAME=s6 +SERVER_TYPE=prod PORT=3000 MONGO_URI=mongodb://root:p62Z!ZatgY25@194.26.138.94:27017 \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index a45c1d3..4fab8a0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -30,7 +30,7 @@ require("dotenv/config"); const db_1 = __importDefault(require("./config/db")); const express_1 = __importStar(require("express")); 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 child_process_1 = require("child_process"); 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 serverType = process.env.SERVER_TYPE; 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) { try { await SessionServer_1.default.findOneAndUpdate({ hostname: serverHostname }, data); @@ -74,7 +78,6 @@ async function getGpuMemoryFree() { async function getAvailablePorts() { const cirrusPorts = [14000, 14001, 14002]; for (const cirrusPort of cirrusPorts) { - console.log(cirrusPort); const activeSession = await ActiveSession_1.default.exists({ location: serverLocation, name: serverName, @@ -86,8 +89,8 @@ async function getAvailablePorts() { return { cirrusPort, uePort }; } } -async function startSession(buildName) { - const filePath = `C:/PixelStreaming/builds/${buildName}/${buildName}.exe`; +async function startSession(buildName, ownerIp, endAt) { + const filePath = `C:/pixel-streaming/builds/${buildName}/${buildName}.exe`; const availablePorts = await getAvailablePorts(); if (!availablePorts) { console.log("No available ports"); @@ -95,7 +98,7 @@ async function startSession(buildName) { } const { cirrusPort, uePort } = availablePorts; const cirrusProcess = (0, child_process_1.execFile)("node", [ - `C:/PixelStreaming/signalling-server/cirrus.js`, + `C:/pixel-streaming/signalling-server/cirrus.js`, `--StreamerPort`, `${uePort}`, `--HttpPort`, @@ -127,27 +130,43 @@ async function startSession(buildName) { console.log("UE application was not started"); return; } - const activeSession = await ActiveSession_1.default.create({ - location: serverLocation, - name: serverName, - buildName, - cirrusPort, - uePort, - cirrusProcessId, - ueProcessId, - }); - const activeSessionId = activeSession.id; - return activeSessionId; + const type = serverType; + try { + const activeSession = await ActiveSession_1.default.create({ + location: serverLocation, + name: serverName, + buildName, + type, + cirrusPort, + uePort, + cirrusProcessId, + 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) { - const activeSession = await ActiveSession_1.default.findByIdAndDelete(activeSessionId); - if (!activeSession) { - console.log("Session with this ID not found"); - return; + try { + const activeSession = await ActiveSession_1.default.findByIdAndDelete(activeSessionId); + if (!activeSession) { + 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() { try { @@ -156,6 +175,7 @@ async function init() { name: serverName, type: serverType, hostname: serverHostname, + localIP, }, { upsert: true, new: true }); getGpuMemoryFree(); } @@ -166,14 +186,17 @@ async function init() { } } app.post("/start", async (req, res) => { - console.log(req.query); - const buildName = req.body.buildName; - if (!buildName) { + for (const [key, value] of Object.entries(req.body)) { + if (value === "null") + req.body[key] = undefined; + } + const { buildName, ownerIp, endAt } = req.body; + console.log("req.body", req.body); + if (!buildName || !ownerIp) { return res.json({ error: 1 }); } - const result = await startSession(buildName); - console.log("Result: ", result); - res.json({ ok: 1 }); + const activeSession = await startSession(buildName, ownerIp, endAt); + res.json(activeSession); }); app.post("/end", async (req, res) => { const activeSessionId = req.body.activeSessionId; diff --git a/dist/models/ActiveSession.js b/dist/models/ActiveSession.js index dc26be5..2926bbd 100644 --- a/dist/models/ActiveSession.js +++ b/dist/models/ActiveSession.js @@ -11,6 +11,9 @@ const activeSessionSchema = new mongoose_1.Schema({ buildName: { type: String, }, + type: { + type: String, + }, uePort: { type: Number, }, @@ -23,6 +26,15 @@ const activeSessionSchema = new mongoose_1.Schema({ cirrusProcessId: { type: Number, }, + ownerIp: { + type: String, + }, + endAt: { + type: Date || null, + }, + localIP: { + type: String, + }, }, { timestamps: true, toJSON: { virtuals: true }, diff --git a/dist/models/SessionServer.js b/dist/models/SessionServer.js index 57978a5..5770648 100644 --- a/dist/models/SessionServer.js +++ b/dist/models/SessionServer.js @@ -18,6 +18,9 @@ const sessionServerSchema = new mongoose_1.Schema({ gpuMemoryFree: { type: Number, }, + localIP: { + type: String, + }, }, { timestamps: true, toJSON: { virtuals: true }, diff --git a/dist/routes/test.js b/dist/routes/test.js index 8f410d5..fbb36b1 100644 --- a/dist/routes/test.js +++ b/dist/routes/test.js @@ -2,7 +2,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = require("express"); const router = (0, express_1.Router)(); -router.get("/", async (req, res) => { +router.get("/", async (_req, res) => { res.json({ ok: 1 }); }); const testRouter = router; diff --git a/ecosystem.config.js b/ecosystem.config.js index 746fe2e..c14085b 100644 --- a/ecosystem.config.js +++ b/ecosystem.config.js @@ -1,9 +1,8 @@ module.exports = { apps: [ { - name: "session-server", - exec_mode: "cluster", - script: "./dist/index.js", + name: "session-server:3000", + script: "./dist", }, ], }; diff --git a/src/index.ts b/src/index.ts index 735c917..adff15d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,7 @@ import "dotenv/config"; import connectDB from "./config/db"; import express, { json } from "express"; import cors from "cors"; -import os from "os"; +import os, { networkInterfaces } from "os"; import util from "util"; import { exec, execFile } from "child_process"; import treeKill from "tree-kill"; @@ -22,6 +22,12 @@ const serverName = process.env.SERVER_NAME; const serverType = process.env.SERVER_TYPE; 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) { try { await SessionServer.findOneAndUpdate({ hostname: serverHostname }, data); @@ -59,8 +65,6 @@ async function getAvailablePorts() { const cirrusPorts = [14000, 14001, 14002]; for (const cirrusPort of cirrusPorts) { - console.log(cirrusPort); - const activeSession = await ActiveSession.exists({ location: serverLocation, name: serverName, @@ -75,8 +79,12 @@ async function getAvailablePorts() { } } -async function startSession(buildName: string) { - const filePath = `C:/PixelStreaming/builds/${buildName}/${buildName}.exe`; +async function startSession( + buildName: string, + ownerIp: string, + endAt?: string +) { + const filePath = `C:/pixel-streaming/builds/${buildName}/${buildName}.exe`; const availablePorts = await getAvailablePorts(); @@ -88,7 +96,7 @@ async function startSession(buildName: string) { const { cirrusPort, uePort } = availablePorts; const cirrusProcess = execFile("node", [ - `C:/PixelStreaming/signalling-server/cirrus.js`, + `C:/pixel-streaming/signalling-server/cirrus.js`, `--StreamerPort`, `${uePort}`, `--HttpPort`, @@ -126,33 +134,50 @@ async function startSession(buildName: string) { return; } - const activeSession = await ActiveSession.create({ - location: serverLocation, - name: serverName, - buildName, - cirrusPort, - uePort, - cirrusProcessId, - ueProcessId, - }); + const type = serverType; - 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) { - const activeSession = await ActiveSession.findByIdAndDelete(activeSessionId); + try { + const activeSession = await ActiveSession.findByIdAndDelete( + activeSessionId + ); - if (!activeSession) { - console.log("Session with this ID not found"); - return; + if (!activeSession) { + console.log("Session with this ID not found"); + 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() { @@ -164,6 +189,7 @@ async function init() { name: serverName, type: serverType, hostname: serverHostname, + localIP, }, { upsert: true, new: true } ); @@ -177,18 +203,21 @@ async function init() { } app.post("/start", async (req, res) => { - console.log(req.query); - const buildName: string = req.body.buildName; + for (const [key, value] of Object.entries(req.body)) { + 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 }); } - const result = await startSession(buildName); + const activeSession = await startSession(buildName, ownerIp, endAt); - console.log("Result: ", result); - - res.json({ ok: 1 }); + res.json(activeSession); }); app.post("/end", async (req, res) => { diff --git a/src/models/ActiveSession.ts b/src/models/ActiveSession.ts index 78a15a7..210a8e2 100644 --- a/src/models/ActiveSession.ts +++ b/src/models/ActiveSession.ts @@ -11,6 +11,9 @@ const activeSessionSchema = new Schema( buildName: { type: String, }, + type: { + type: String, + }, uePort: { type: Number, }, @@ -23,6 +26,15 @@ const activeSessionSchema = new Schema( cirrusProcessId: { type: Number, }, + ownerIp: { + type: String, + }, + endAt: { + type: Date || null, + }, + localIP: { + type: String, + }, }, { timestamps: true, diff --git a/src/models/SessionServer.ts b/src/models/SessionServer.ts index 4aca4a6..428fc18 100644 --- a/src/models/SessionServer.ts +++ b/src/models/SessionServer.ts @@ -18,6 +18,9 @@ const sessionServerSchema = new Schema( gpuMemoryFree: { type: Number, }, + localIP: { + type: String, + }, }, { timestamps: true, diff --git a/src/routes/test.ts b/src/routes/test.ts index 4b1ea5c..9b000fd 100644 --- a/src/routes/test.ts +++ b/src/routes/test.ts @@ -2,7 +2,7 @@ import { Router } from "express"; const router = Router(); -router.get("/", async (req, res) => { +router.get("/", async (_req, res) => { res.json({ ok: 1 }); }); diff --git a/tsconfig.json b/tsconfig.json index 2ffd6f2..e7913fc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,110 +1,18 @@ { "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "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 ''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. */ + "target": "ESNext", + "module": "CommonJS", + "moduleResolution": "Node", + "outDir": "./dist", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true }, - "include": ["src"] + "ts-node": { + "transpileOnly": true + } }