Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
fcc4228
feat: allow users to specify a option, which causes Ganache to start…
jeffsmale90 Aug 22, 2022
7a787f2
Stream stderr from the child to the parent
jeffsmale90 Aug 23, 2022
301c500
Tidy up of --detach argument parsing
jeffsmale90 Aug 23, 2022
7dec4c0
Improve detach configuration
jeffsmale90 Aug 24, 2022
9ed54db
Add tests for parsing detach arguments. Change default value to false…
jeffsmale90 Aug 24, 2022
20579ae
Make parent aware of detached instances, and allow stopping them via cli
jeffsmale90 Sep 4, 2022
1da7911
improve args tests, remove placeholder
jeffsmale90 Sep 6, 2022
9cc5b59
Implement , and allow different actions to be executed via the CLI
jeffsmale90 Sep 7, 2022
e5d7e60
Clean up orphaned instance process files. uses a terrible hack to fet…
jeffsmale90 Sep 7, 2022
295b1a3
Implement `instances` command with subcommands. Clean up orphaned ins…
jeffsmale90 Sep 7, 2022
75ffbb0
Tidy up args types and parsing
jeffsmale90 Sep 12, 2022
17732d7
Refactor, add flavor to instance data, and to list output. Change ins…
jeffsmale90 Sep 12, 2022
dea1ddb
Fix createFlatChildArgs import in args.test.ts
jeffsmale90 Sep 20, 2022
07a4b03
Merge branch 'develop' into feat/detach-mode
jeffsmale90 Sep 20, 2022
a74d0a3
Update package-lock.json files - required for new deps
jeffsmale90 Sep 20, 2022
1eaea51
Fix module resolution
jeffsmale90 Sep 20, 2022
cba7589
Tidy ups and refactors
jeffsmale90 Sep 20, 2022
c39cae6
Tidy up arg parsing
jeffsmale90 Sep 20, 2022
bc61cb1
Revert package-lock.json files
jeffsmale90 Sep 20, 2022
f5650f2
Fix miss-typed action name
jeffsmale90 Sep 20, 2022
90a2305
Remove dependency on ps-list, move data files to Ganache/instances, i…
jeffsmale90 Sep 22, 2022
c1e5f43
Remove kebab-case names when expanding arguments. Add tests for expan…
jeffsmale90 Sep 22, 2022
757220b
Reintroduce ps-list, only list instances where the process co
jeffsmale90 Sep 23, 2022
c432c35
Move createFlatChildArgs() to detach.ts, add version to list, ensure …
jeffsmale90 Sep 23, 2022
2dec992
Create instances directory recursively, because now it's
jeffsmale90 Sep 23, 2022
773f21a
Tidy ups from code review, add section on Detached mode to README.
jeffsmale90 Sep 27, 2022
5fb72d1
Fix incorrect command name in README.md
jeffsmale90 Oct 10, 2022
9bf6064
Merge branch 'develop' into feat/detach-mode
jeffsmale90 Oct 10, 2022
d27e6bc
Update to use @trufflesuite/ps-list instead of ps-list
jeffsmale90 Nov 6, 2022
eafc679
If no instances are found, using , print a friendly message instead o…
jeffsmale90 Nov 6, 2022
e6ae996
Revert ganache package version to match develop
jeffsmale90 Nov 6, 2022
eb14694
Merge branch 'develop' into feat/detach-mode
jeffsmale90 Nov 6, 2022
876b972
Bump @trufflesuite/ps-list to include support for node 12
jeffsmale90 Nov 6, 2022
208b149
upgrade @trufflesuite/ps-list to support nodejs < 12.17.0
jeffsmale90 Nov 7, 2022
5f4b80d
Merge branch 'develop' into feat/detach-mode
jeffsmale90 Nov 9, 2022
6b61cba
Improve wording of `--detach` description in README.md
jeffsmale90 Nov 13, 2022
7f36f1f
Switched out for (existing dependency via marked-terminal)
jeffsmale90 Nov 13, 2022
ac5aba0
Move instance list sorting to the consumer that needs the list sorted
jeffsmale90 Nov 15, 2022
bfc5cf9
use detached instance friendly name for instance file (instead of pid)
jeffsmale90 Nov 15, 2022
1a52d4c
pass original process.args to startDetachedInstance, calculate expect…
jeffsmale90 Nov 15, 2022
7a4c256
Fix 'cmd' argument for win32 platform
jeffsmale90 Nov 15, 2022
67d11fc
Add attribution for duration formatter
jeffsmale90 Nov 15, 2022
683c201
Change all detach mode file access to async
jeffsmale90 Nov 15, 2022
60ae164
Adds warning messages if instances removed
jeffsmale90 Nov 15, 2022
1726ec9
Add PID to warning message.
jeffsmale90 Nov 15, 2022
0811874
Remove unnecessary detach.test.ts
jeffsmale90 Nov 15, 2022
485ff64
improvements / refactor as per pr review.
jeffsmale90 Nov 16, 2022
1701140
Don't check for existence of the folder each time - just catch the Er…
jeffsmale90 Nov 16, 2022
78a9d0c
Accidentally recreated the instance name twice
jeffsmale90 Nov 16, 2022
04719a6
Move comment to relevant code
jeffsmale90 Nov 16, 2022
3ea9968
Improvements to detach re PR
jeffsmale90 Nov 16, 2022
6a7f3b3
Revert package-lock.json
jeffsmale90 Nov 16, 2022
c5c0c31
_Actually_ fix package-lock.json this time
jeffsmale90 Nov 16, 2022
bc8d269
Remove nyc dev-dependency from cli/package.json - correct, but irrele…
jeffsmale90 Nov 16, 2022
aa72840
Strip the detach argument correctly before passing arguments to child…
jeffsmale90 Nov 16, 2022
4e8f933
Add tests for duration formatting - move implementation into detach.ts
jeffsmale90 Nov 18, 2022
6b49cbb
Rename formatDuration to formatUptime, add --detach example to README…
jeffsmale90 Nov 18, 2022
0435951
Revert shrinkwrap :/
jeffsmale90 Nov 18, 2022
959c6dc
Pin cli-table dependency to latest release
jeffsmale90 Nov 18, 2022
dfb8b72
Fix failing test
jeffsmale90 Nov 18, 2022
c495cc9
Improve duration formatting, improve readme
jeffsmale90 Nov 22, 2022
c16cb20
Annoyingly, args parsing is complicated. Don't try to strip out the d…
jeffsmale90 Nov 22, 2022
b272237
Instance files now have .json extension. Remove any files / folders f…
jeffsmale90 Nov 22, 2022
c85d022
Remove unused import
jeffsmale90 Nov 22, 2022
359cb6b
Handle errors betterer
jeffsmale90 Nov 23, 2022
f94442f
Shorten duration formatting, combine host and port, right align PID i…
jeffsmale90 Nov 23, 2022
26af55e
RH align Uptime
jeffsmale90 Nov 23, 2022
d717d3f
remove unnecessary type assertion, remove datapath suffix
jeffsmale90 Nov 23, 2022
393702c
Use unlink instead of rm, because node 12
jeffsmale90 Nov 25, 2022
0507aa4
Support ndoe 12 correctly for removal of files and directories
jeffsmale90 Nov 28, 2022
2d92da1
Make PowerShell example consistent with non-Windows example
jeffsmale90 Dec 1, 2022
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
12 changes: 11 additions & 1 deletion src/packages/cli/src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,16 @@ export default function (
}

args = args
.command(
"stop [name]",
"Stop an instance of Ganache running in detached mode",
stopArgs => {
stopArgs.positional("name", {
type: "string",
name: "The name of the instance to stop"
});
}
)
.showHelpOnFail(false, "Specify -? or --help for available options")
.alias("help", "?")
.wrap(wrapWidth)
Expand All @@ -246,7 +256,7 @@ export default function (
flavor: parsedArgs._.length > 0 ? parsedArgs._[0] : DefaultFlavor,
detach: parsedArgs.detach || false
} as Argv;
for (let key in parsedArgs) {
for (const key in parsedArgs) {
// split on the first "."
const [group, option] = key.split(/\.(.+)/);
// only copy namespaced/group keys
Expand Down
83 changes: 37 additions & 46 deletions src/packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,26 @@ import initializeEthereum from "./initialize/ethereum";
import initializeFilecoin from "./initialize/filecoin";
import type { FilecoinProvider } from "@ganache/filecoin";
import type { EthereumProvider } from "@ganache/ethereum";
import { fork } from "child_process";
import {
cleanupDetachedInstanceFile,
notifyDetachedInstanceReady,
stopDetachedInstance,
startDetachedInstance
} from "./detach";
import { TruffleColors } from "@ganache/colors";
import chalk from "chalk";

// if process.send is defined, this is a child_process (we assume a detached
// instance), so we need to notify that we are ready.
const isDetachedInstance = process.send !== undefined;

if (isDetachedInstance) {
// we want to attach this listener as early as possible, to avoid leaving a
// dangling instance file
process.on("exit", () => {
cleanupDetachedInstanceFile(process.pid);
});
}

const logAndForceExit = (messages: any[], exitCode = 0) => {
// https://nodejs.org/api/process.html#process_process_exit_code
Expand Down Expand Up @@ -40,52 +59,26 @@ const isDocker =

const argv = args(detailedVersion, isDocker);

if (argv.detach) {
// Start Ganache in a child process, and allow it to run in the background.
// The only output to stdout should be the PID of the child process.
const module = process.argv[1];
const args = process.argv.slice(2);
args.splice(args.indexOf("--detach"), 1);

const child = fork(module, args, {
stdio: ["ignore", "ignore", "pipe", "ipc"],
detached: true
});

// Any messages output to stderr by the child process (before the `ready`
// event is emitted) will be streamed to stderr on the parent.
child.stderr.pipe(process.stderr);

child.on("message", message => {
if (message === "ready") {
console.log(child.pid);

// Destroy the ReadableStream exposed by the child process, to allow the
// parent to exit gracefully.
child.stderr.destroy();
child.unref();
child.disconnect();
}
});
// todo: defs need to improve this
if (process.argv.indexOf("stop") !== -1) {
const instanceName = process.argv[process.argv.length - 1];

child.on("error", err => {
// This only happens if there's an error starting the child process, not if
// the application throws within the child process.
console.error(
`An error occurred starting Ganache in detached mode: ${err}`
if (stopDetachedInstance(instanceName)) {
console.log("Process stopped");
} else {
console.error("Process not found");
}
} else if (argv.detach) {
startDetachedInstance(process.argv).then(instance => {
const highlightedName = chalk.hex(TruffleColors.porsche)(
instance.friendlyName
);
process.exit(1);
});

child.on("exit", (code: number) => {
// If the child process exits before the parent, something has gone wrong,
// so let the user know (even if the exit code is 0).
console.error(`The child process exited with exit code ${code}`);
process.exit(code);
// output only the friendly name to allow users to capture stdout and use to
// programmatically stop the instance
console.log(highlightedName);
});
Comment thread
jeffsmale90 marked this conversation as resolved.
Outdated
} else {
const flavor = argv.flavor;

const cliSettings = argv.server;

console.log(detailedVersion);
Expand Down Expand Up @@ -186,10 +179,8 @@ if (argv.detach) {
}
}

// in "detach" mode, the parent will wait until the "ready" message is
// received before disconnecting from the child process.
if (process.send) {
process.send("ready");
if (isDetachedInstance) {
notifyDetachedInstanceReady();
Comment thread
davidmurdoch marked this conversation as resolved.
}
}
console.log("Starting RPC server");
Expand Down
167 changes: 167 additions & 0 deletions src/packages/cli/src/detach.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { fork } from "child_process";
import createProcessName from "./process-name";
import envPaths from "env-paths";
import {
existsSync,
mkdirSync,
rmSync,
writeFileSync,
readdirSync,
readFileSync
} from "fs";
import path from "path";

export type DetachedInstance = {
friendlyName: string;
pid: number;
startTime: number;
};

const dataPath = envPaths(`ganache`).data;
Comment thread
jeffsmale90 marked this conversation as resolved.
Outdated
if (!existsSync(dataPath)) mkdirSync(dataPath);

const READY_MESSAGE = "ready";

/**
* Notify that the detached instance has started and is ready to receive requests.
*/
export function notifyDetachedInstanceReady() {
// in "detach" mode, the parent will wait until the "ready" message is
// received before disconnecting from the child process.
process.send(READY_MESSAGE);
}

/**
* Attempt to find and remove the instance file for a detached instance.
* @param {number} pid the pid of the detached instance
* @returns boolean indicating whether the instance file was cleaned up successfully
*/
export function cleanupDetachedInstanceFile(pid: number): boolean {
const instanceFilename = `${dataPath}/${pid}`;
if (existsSync(instanceFilename)) {
rmSync(instanceFilename);
Comment thread
davidmurdoch marked this conversation as resolved.
Outdated
return true;
}
return false;
}

/**
* Register a new detached instance. Creates an instance file containing
* information about the instance.
* @param {DetachedInstance} instance
*/
function registerDetachedInstance(instance: DetachedInstance) {
const instanceFilename = `${dataPath}/${instance.pid}`;

writeFileSync(
instanceFilename,
`${instance.friendlyName}|${instance.startTime}`
);
}

/**
* Attempts to stop a detached instance with the specified instance name by
* sending a SIGTERM signal. Returns a boolean indicating whether the process
* was found. If the PID is identified, but the process is not found, any
* corresponding instance file will be removed.
*
* Note: This does not guarantee that the instance actually stops.
* @param {string} instanceName
Comment thread
davidmurdoch marked this conversation as resolved.
* @returns boolean indicating whether the instance was found.
*/
export function stopDetachedInstance(instanceName: string): boolean {
const instance = findInstanceByName(instanceName);

if (instance) {
try {
process.kill(instance.pid, "SIGTERM");
Comment thread
MicaiahReid marked this conversation as resolved.
Outdated
} catch (err) {
// process.kill throws if the process was not found (or was a group process in Windows)
cleanupDetachedInstanceFile(instance.pid);
return false;
}
return true;
}
return false;
}

/**
* Start an instance of Ganache in detached mode.
* @param {string[]} argv arguments to be passed to the new instance.
* @returns {Promise<DetachedInstance>} resolves to the DetachedInstance once it
* is started and ready to receive requests.
*/
export async function startDetachedInstance(
argv: string[]
): Promise<DetachedInstance> {
const module = argv[1];
const args = argv.slice(1).splice(argv.indexOf("--detach"), 1);

const child = fork(module, args, {
stdio: ["ignore", "ignore", "pipe", "ipc"],
detached: true
});

// Any messages output to stderr by the child process (before the `ready`
// event is emitted) will be streamed to stderr on the parent.
child.stderr.pipe(process.stderr);

let friendlyName: string;
do {
friendlyName = createProcessName();
} while (findInstanceByName(friendlyName));

await new Promise<void>((resolve, reject) => {
child.on("message", message => {
if (message === READY_MESSAGE) {
resolve();
}
});

child.on("error", err => {
// This only happens if there's an error starting the child process, not if
// the application throws within the child process.
reject(err);
});

child.on("exit", (code: number) => {
// If the child process exits before the parent, something has gone wrong,
// so let the user know (even if the exit code is 0).
reject(new Error(`The child process exited with code ${code}`));
});
});

// destroy the ReadableStream exposed by the child process, to allow the
// parent to exit gracefully.
child.stderr.destroy();
child.unref();
child.disconnect();

const instance = {
startTime: Date.now(),
pid: child.pid,
friendlyName
};

registerDetachedInstance(instance);

return instance;
}

function findInstanceByName(
friendlyName: string
): DetachedInstance | undefined {
const files = readdirSync(dataPath);
Comment thread
davidmurdoch marked this conversation as resolved.
Outdated
for (let i = 0; i < files.length; i++) {
const filepath = path.join(dataPath, files[i]);
const content = readFileSync(filepath).toString("utf8");
const [name, startTime] = content.split("|");
if (name === friendlyName) {
return {
friendlyName,
pid: parseInt(files[i]),
startTime: parseInt(startTime)
};
}
}
}
83 changes: 83 additions & 0 deletions src/packages/cli/src/process-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
export default function createFriendlyName() {
const name = [...Array(3)].map((_, i) => {
const partSource = nameParts[i];
const partIndex = Math.floor(Math.random() * partSource.length);
return partSource[partIndex];
});

return name.join("-");
}

const adjectives = [
"baked",
"candied",
"deepfried",
"frozen",
"hot",
"molten",
"pureed",
"salted",
"spiced",
"sticky"
];
const flavours = [
Comment thread
jeffsmale90 marked this conversation as resolved.
Outdated
"almond",
"apple",
"banana",
"blackforest",
"caramel",
"cherry",
"chocolate",
"cinnamon",
"coconut",
"coffee",
"cream",
"custard",
"fruit",
"ginger",
"gingerbread",
"jelly",
"lemon",
"lime",
"milk",
"nut",
"orange",
"peanut",
"plum",
"poppy-seed",
"rhubarb",
"strawberry",
"sugar",
"tiramisu"
];
const kinds = [
"bar",
"biscuit",
"brownie",
"cake",
"cheesecake",
"cookie",
"crumble",
"cupcake",
"doughnut",
"drizzle",
"dumpling",
"friand",
"ganache",
"loaf",
"macaroon",
"mousse",
"muffin",
"pastry",
"pie",
"pudding",
"sponge",
"strudel",
"tart",
"torte",
"trifle",
"truffle",
"waffle"
];

const nameParts = [adjectives, flavours, kinds];