Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.

feat: add a detach mode to the CLI #3568

Merged
merged 71 commits into from
Dec 1, 2022
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
Prev Previous commit
Next Next commit
Tidy ups from code review, add section on Detached mode to README.
  • Loading branch information
jeffsmale90 committed Sep 27, 2022
commit 773f21a4c3ec96f8e217975b7045be8776505c5d
3 changes: 1 addition & 2 deletions src/packages/cli/src/args.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { TruffleColors } from "@ganache/colors";

import yargs, { Options } from "yargs";
import {
DefaultFlavor,
Expand Down Expand Up @@ -233,7 +232,7 @@ export default function (
description: highlight(
"Run Ganache in detached (daemon) mode." +
EOL +
"See `ganache instances --help` for information omn managing detached instances."
"See `ganache instances --help` for information on managing detached instances."
),
type: "boolean",
alias: ["D", "😈"]
Expand Down
17 changes: 3 additions & 14 deletions src/packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import initializeFilecoin from "./initialize/filecoin";
import type { FilecoinProvider } from "@ganache/filecoin";
import type { EthereumProvider } from "@ganache/ethereum";
import {
removeDetachedInstanceFile,
notifyDetachedInstanceReady,
stopDetachedInstance,
startDetachedInstance,
Expand All @@ -19,18 +18,6 @@ import { TruffleColors } from "@ganache/colors";
import { table } from "table";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may snag this for version check stuff.

Tangential to this pr, table seems extensive and well vetted but it is pretty big after install for what it does. How did you like it and are there other places you think we can use it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah - it's good enough! I have used table in some tools I've written in the past, but not for anything complex.

You triggered me to look back into this, and have switched out table for cli-table, as that's an existing dependency via marked-terminal. The API is almost the same.

I've had to modify the styling, because by default the headers are red 🤮, but it looks mostly indistinguishable now.

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", () => {
removeDetachedInstanceFile(process.pid);
});
}

const logAndForceExit = (messages: any[], exitCode = 0) => {
// https://nodejs.org/api/process.html#process_process_exit_code
// writes to process.stdout in Node.js are sometimes asynchronous and may occur over
Expand Down Expand Up @@ -176,6 +163,9 @@ if (argv.action === "start") {
}
}

// 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) {
notifyDetachedInstanceReady();
}
Expand Down Expand Up @@ -223,7 +213,6 @@ if (argv.action === "start") {
chalk.bold("Uptime")
]
];

for (let i = 0; i < instances.length; i++) {
const instance = instances[i];

Expand Down
11 changes: 7 additions & 4 deletions src/packages/cli/src/detach.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ export async function stopDetachedInstance(
process.kill(instance.pid, "SIGTERM");
} catch (err) {
// process.kill throws if the process was not found (or was a group process in Windows)
removeDetachedInstanceFile(instance.pid);
return false;
} finally {
removeDetachedInstanceFile(instance.pid);
}
return true;
}
Expand Down Expand Up @@ -166,17 +167,17 @@ export async function startDetachedInstance(
/**
* Fetch all instance of Ganache running in detached mode. Cleans up any
* instance files for processes that are no longer running.
* @returns Promise<DetachedInstance[]> resolves with an array of instances
* @returns {Promise<DetachedInstance[]>} resolves with an array of instances
*/
export async function getDetachedInstances(): Promise<DetachedInstance[]> {
const files = readdirSync(dataPath);
const instances: DetachedInstance[] = [];
const processes = await psList();

for (let i = 0; i < files.length; i++) {
const filename = files[i];
const pid = parseInt(filename);

const processes = await psList();
const foundProcess = processes.find(p => p.pid === pid);

let shouldRemoveFile = false;
Expand Down Expand Up @@ -206,6 +207,8 @@ export async function getDetachedInstances(): Promise<DetachedInstance[]> {
if (shouldRemoveFile) removeDetachedInstanceFile(pid);
}

instances.sort((a, b) => b.startTime - a.startTime);

return instances;
}

Expand All @@ -222,7 +225,7 @@ async function findDetachedInstanceByName(
}

/**
* Flattens parsed, and namespaced args into an array of arguments to be passed
* Flattens parsed and namespaced args into an array of arguments to be passed
* to a child process. This handles "special" arguments, such as "action",
* "flavor" and "--detach".
* @param {object} args to be flattened
Expand Down
36 changes: 36 additions & 0 deletions src/packages/ganache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,43 @@ Server:
-p, --server.port, --port Port to listen on.
deprecated aliases: --port
[number] [default: 8545]
```

### Detached Instances

Ganache can be started as a background instance via the CLI by providing the following argument (along with any combination
of the Ganache startup arguments above):

```
-D, --detach, --😈 Run Ganache in detached (daemon) mode. [boolean]
```

This will start Ganache as a background process, and return to the console as soon as Ganache has started and ready to
receive requests. A friendly name will be returned to STDOUT which can then be used to interact with the instance via
the `ganache instances` command with the following arguments:

```
Commands:
cli.ts instances list List instances running in detached mode
cli.ts instances stop <name> Stop the instance specified by <name>
```

E.g., start Ganache on port 8544, with a block time of 10 seconds, and then stop the instance.

```
$ ganache --port=8544 --miner.blockTime=10 --detach
salted_caramel_ganache

$ ganache instances list
╔═══════╤════════════════════════╤══════════╤═════════╤═══════════╤══════╤════════════╗
║ PID │ Name │ Flavor │ Version │ Host │ Port │ Uptime ║
╟───────┼────────────────────────┼──────────┼─────────┼───────────┼──────┼────────────╢
║ 56004 │ salted_caramel_ganache │ ethereum │ 7.4.3 │ 127.0.0.1 │ 8544 │ 48 seconds ║
╚═══════╧════════════════════════╧══════════╧═════════╧═══════════╧══════╧════════════╝


$ ganache instances stop salted_caramel_ganache
Process stopped
```

### Ganache Provider Events
Expand Down