Skip to content

Commit

Permalink
pnpm fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
tmpolaczyk committed Oct 27, 2023
1 parent 657374f commit 52839eb
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 86 deletions.
113 changes: 59 additions & 54 deletions test/scripts/zombienetRestart.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import * as ps from 'ps-node';
import { exec, spawn, execSync } from 'child_process';
import { readFileSync, writeFileSync, readlinkSync, unlinkSync } from 'fs';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import os from 'os';
import path from 'path';
import inquirer from 'inquirer';
import * as ps from "ps-node";
import { exec, spawn, execSync } from "child_process";
import { readFileSync, writeFileSync, readlinkSync, unlinkSync } from "fs";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import os from "os";
import path from "path";
import inquirer from "inquirer";

const getEnvVariables = (pid: number) => {
const envData = readFileSync(`/proc/${pid}/environ`).toString();
return envData.split('\0').filter(Boolean);
return envData.split("\0").filter(Boolean);
};

const getCwd = (pid: number) => {
Expand All @@ -20,26 +20,29 @@ const targetProcessNames = [
"tanssi-node",
"container-chain-template-simple-node",
"container-chain-template-frontier-node",
"polkadot"
"polkadot",
];
const pattern = targetProcessNames.join('|');
const pattern = targetProcessNames.join("|");

const fetchProcesses = async () => {
const cmd = `ps aux | grep -E "${pattern}"`;
const { stdout } = await execPromisify(cmd);
return stdout.split('\n').filter(line => line && !line.includes("grep -E")).map(line => {
const parts = line.split(/\s+/);
const pid = parts[1];
const command = parts.slice(10).join(' ');
return {
name: `PID: ${pid}, Command: ${command}`,
value: pid
};
});
return stdout
.split("\n")
.filter((line) => line && !line.includes("grep -E"))
.map((line) => {
const parts = line.split(/\s+/);
const pid = parts[1];
const command = parts.slice(10).join(" ");
return {
name: `PID: ${pid}, Command: ${command}`,
value: pid,
};
});
};

const execPromisify = (command: string) => {
return new Promise<{ stdout: string, stderr: string }>((resolve, reject) => {
return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
Expand Down Expand Up @@ -76,79 +79,81 @@ yargs(hideBin(process.argv))
},
async (argv) => {
let pid = argv.pid as number;

if (!pid) {
const processes = await fetchProcesses();
if (processes.length === 0) {
console.error("No matching processes found. Exiting...");
process.exit(1);
}

const { selectedPid } = await inquirer.prompt([{
type: 'list',
name: 'selectedPid',
message: 'Select a process to restart:',
choices: processes,
pageSize: 15 // Increase this number as needed
}]);
const { selectedPid } = await inquirer.prompt([
{
type: "list",
name: "selectedPid",
message: "Select a process to restart:",
choices: processes,
pageSize: 15, // Increase this number as needed
},
]);

pid = Number(selectedPid);
}

// Get process details by PID
ps.lookup({ pid: pid }, (err, resultList) => {
if (err) {
throw new Error(err);
}

const processInfo = resultList[0];

if (processInfo) {
let { command, arguments: args } = processInfo;

if (argv["edit-cmd"]) {
const tempFilePath = path.join(os.tmpdir(), `zombienet-restart-cmd-${Date.now()}.txt`);
writeFileSync(tempFilePath, `${command} ${args.join(' ')}`);
const editor = process.env.EDITOR || 'vim'; // Default to 'vim' if EDITOR is not set
execSync(`${editor} ${tempFilePath}`, { stdio: 'inherit' });
const modifiedCommand = readFileSync(tempFilePath, 'utf-8').trim().split(' ');
writeFileSync(tempFilePath, `${command} ${args.join(" ")}`);

const editor = process.env.EDITOR || "vim"; // Default to 'vim' if EDITOR is not set
execSync(`${editor} ${tempFilePath}`, { stdio: "inherit" });

const modifiedCommand = readFileSync(tempFilePath, "utf-8").trim().split(" ");
command = modifiedCommand[0];
args = modifiedCommand.slice(1);

// Delete the temporary file
unlinkSync(tempFilePath);
}

console.log(`Command: ${command}`);
console.log(`Arguments: ${args.join(' ')}`);
console.log(`Arguments: ${args.join(" ")}`);

// Fetch environment variables, CWD, etc.
const envVariables = getEnvVariables(pid);
const cwd = getCwd(pid);
console.log(`Environment Variables: \n${envVariables.join('\n')}`);
console.log(`Environment Variables: \n${envVariables.join("\n")}`);
console.log(`Current Working Directory: ${cwd}`);

// Kill the process
exec(`kill -9 ${pid}`, (err) => {
if (err) {
console.error(`Failed to kill process with ID ${pid}.`, err);
return;
}

console.log(`Process with ID ${pid} has been killed.`);

setTimeout(() => {
// Restart the process in the current terminal with its original environment variables and cwd
const child = spawn(command, args, {
stdio: 'inherit',
stdio: "inherit",
cwd: cwd,
env: Object.fromEntries(envVariables.map(e => e.split('=', 2)))
env: Object.fromEntries(envVariables.map((e) => e.split("=", 2))),
});
process.on('SIGINT', () => {
child.kill('SIGINT');

process.on("SIGINT", () => {
child.kill("SIGINT");
});
}, argv["wait-ms"]);
});
Expand All @@ -162,17 +167,17 @@ yargs(hideBin(process.argv))
.command(
"list",
"List processes with specified names",
(yargs) => {},
() => {},
async () => {
const processes = await fetchProcesses();
if (processes.length) {
console.log("Matching Processes:");
processes.forEach(process => {
processes.forEach((process) => {
console.log(process.name);
});
} else {
console.log("No matching processes found.");
}
}
)
.parse();
.parse();
57 changes: 30 additions & 27 deletions test/suites/keep-db/test_restart_keep_db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import { getAuthorFromDigest } from "../../util/author";
import { signAndSendAndInclude, waitSessions } from "../../util/block";
import { getKeyringNimbusIdHex } from "../../util/keys";
import { getHeaderFromRelay } from "../../util/relayInterface";
import net from "net";
import { exec, execSync, spawn, ChildProcessWithoutNullStreams } from 'child_process';
import { ExecaChildProcess, execa, execaCommand } from "execa";
import { exec } from "child_process";
import { ExecaChildProcess, execa } from "execa";

describeSuite({
id: "ZK01",
Expand All @@ -16,7 +15,7 @@ describeSuite({
let paraApi: ApiPromise;
let relayApi: ApiPromise;
let container2000Api: ApiPromise;
let restartedHandles: Array<ExecaChildProcess<string>> = [];
const restartedHandles: Array<ExecaChildProcess<string>> = [];

beforeAll(async () => {
paraApi = context.polkadotJs("Tanssi");
Expand All @@ -43,20 +42,21 @@ describeSuite({
}, 120000);

afterAll(async () => {
for (let h of restartedHandles) {
console.log('Stopping process ', h.pid);

for (const h of restartedHandles) {
h.kill();

console.log("process killed? ", h.killed);
}
})
});

const runZombienetRestart = async (pid: number): Promise<void> => {
// Wait 10 seconds to have enough time to check if db exists
const handle = execa('pnpm', ['run', 'zombienet-restart', 'restart', '--wait-ms', '10000', '--pid', pid.toString()], {
stdio: 'inherit',
});
// Need to use `pnpm tsx` instead of `pnpm run` to ensure that the process gets killed properly
const handle = execa(
"pnpm",
["tsx", "scripts/zombienetRestart.ts", "restart", "--wait-ms", "10000", "--pid", pid.toString()],
{
stdio: "inherit",
}
);

restartedHandles.push(handle);
};
Expand Down Expand Up @@ -205,36 +205,39 @@ describeSuite({
});

const sleep = (ms: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, ms));
return new Promise((resolve) => setTimeout(resolve, ms));
};

const findCollatorProcessPid = async (collatorName: string) => {
const pattern = `(tanssi-node.*${collatorName})`;
const cmd = `ps aux | grep -E "${pattern}"`;
const { stdout } = await execPromisify(cmd);
const processes = stdout.split('\n').filter(line => line && !line.includes("grep -E")).map(line => {
const parts = line.split(/\s+/);
const pid = parts[1];
const command = parts.slice(10).join(' ');
return {
name: `PID: ${pid}, Command: ${command}`,
value: pid
};
});
const processes = stdout
.split("\n")
.filter((line) => line && !line.includes("grep -E"))
.map((line) => {
const parts = line.split(/\s+/);
const pid = parts[1];
const command = parts.slice(10).join(" ");
return {
name: `PID: ${pid}, Command: ${command}`,
value: pid,
};
});

if (processes.length === 1) {
return processes[0].value; // return pid
} else {
const error = {
message: 'Multiple processes found.',
processes: processes.map(p => p.name)
message: "Multiple processes found.",
processes: processes.map((p) => p.name),
};
throw error;
}
};

const execPromisify = (command: string) => {
return new Promise<{ stdout: string, stderr: string }>((resolve, reject) => {
return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
Expand All @@ -243,4 +246,4 @@ const execPromisify = (command: string) => {
}
});
});
};
};
10 changes: 5 additions & 5 deletions test/suites/warp-sync/test_warp_sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,16 @@ describeSuite({

// Restart the process in the current terminal with its original environment variables and cwd
const child = spawn(command, args, {
stdio: 'inherit',
stdio: "inherit",
cwd: cwd,
env: Object.fromEntries(envVariables.map(e => e.split('=', 2)))
env: Object.fromEntries(envVariables.map((e) => e.split("=", 2))),
});

process.on('SIGINT', () => {
child.kill('SIGINT');
process.on("SIGINT", () => {
child.kill("SIGINT");
});

process.on('exit', () => {
process.on("exit", () => {
// Kill process
});
},
Expand Down

0 comments on commit 52839eb

Please sign in to comment.