Skip to content

Commit 5859d77

Browse files
authored
Several improvements to fuchsia_ctl. (#134)
* Several improvements to fuchsia_ctl. * Adds timeouts for paving process. * Adds timeouts to ssh commands and tests. * Support to generate authorized_keys with existing pub key. * Add flags to pass public key to pave subcommand. flutter/flutter#54416 * Link CLI flags to command implementations. * Enables command help. * Address code review comments.
1 parent c35c226 commit 5859d77

7 files changed

Lines changed: 234 additions & 51 deletions

File tree

‎packages/fuchsia_ctl/bin/main.dart‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ Future<void> main(List<String> args) async {
3939
'If not specified, the first discoverable device will be used.')
4040
..addOption('dev-finder-path',
4141
defaultsTo: './dev_finder',
42-
help: 'The path to the dev_finder executable.');
42+
help: 'The path to the dev_finder executable.')
43+
..addFlag('help', defaultsTo: false, help: 'Prints help.');
4344
parser.addCommand('ssh')
4445
..addFlag('interactive',
4546
abbr: 'i',
@@ -50,8 +51,12 @@ Future<void> main(List<String> args) async {
5051
help: 'The command to run on the device. '
5152
'If specified, --interactive is ignored.')
5253
..addOption('identity-file',
53-
defaultsTo: '.ssh/pkey', help: 'The key to use when SSHing.');
54+
defaultsTo: '.ssh/pkey', help: 'The key to use when SSHing.')
55+
..addOption('timeout-seconds',
56+
defaultsTo: '120', help: 'Ssh command timeout in seconds.');
5457
parser.addCommand('pave')
58+
..addOption('public-key',
59+
abbr: 'p', help: 'The public key to add to authorized_keys.')
5560
..addOption('image',
5661
abbr: 'i', help: 'The system image tgz to unpack and pave.');
5762

@@ -89,7 +94,9 @@ Future<void> main(List<String> args) async {
8994
abbr: 'a',
9095
help: 'Command line arguments to pass when invoking the tests')
9196
..addMultiOption('far',
92-
abbr: 'f', help: 'The .far files to include for the test.');
97+
abbr: 'f', help: 'The .far files to include for the test.')
98+
..addOption('timeout-seconds',
99+
defaultsTo: '120', help: 'Test timeout in seconds.');
93100

94101
final ArgResults results = parser.parse(args);
95102

@@ -98,6 +105,12 @@ Future<void> main(List<String> args) async {
98105
stderr.writeln(parser.usage);
99106
exit(-1);
100107
}
108+
109+
if (results['help']) {
110+
stderr.writeln(parser.commands[results.command.name].usage);
111+
exit(0);
112+
}
113+
101114
final AsyncResult command = commands[results.command.name];
102115
if (command == null) {
103116
stderr.writeln('Unkown command ${results.command.name}.');
@@ -129,11 +142,11 @@ Future<OperationResult> ssh(
129142
identityFilePath: identityFile,
130143
);
131144
}
132-
final OperationResult result = await sshClient.runCommand(
133-
targetIp,
134-
identityFilePath: identityFile,
135-
command: args['command'].split(' '),
136-
);
145+
final OperationResult result = await sshClient.runCommand(targetIp,
146+
identityFilePath: identityFile,
147+
command: args['command'].split(' '),
148+
timeoutMs:
149+
Duration(milliseconds: int.parse(args['timeout-seconds']) * 1000));
137150
stdout.writeln(
138151
'==================================== STDOUT ====================================');
139152
stdout.writeln(result.info);
@@ -150,7 +163,11 @@ Future<OperationResult> pave(
150163
ArgResults args,
151164
) async {
152165
const ImagePaver paver = ImagePaver();
153-
return await paver.pave(args['image'], deviceName);
166+
return await paver.pave(
167+
args['image'],
168+
deviceName,
169+
publicKeyPath: args['public-key'],
170+
);
154171
}
155172

156173
@visibleForTesting
@@ -271,6 +288,8 @@ Future<OperationResult> test(
271288
'fuchsia-pkg://fuchsia.com/$target#meta/$target.cmx',
272289
arguments
273290
],
291+
timeoutMs:
292+
Duration(milliseconds: int.parse(args['timeout-seconds']) * 1000),
274293
);
275294
stdout.writeln('Test results (passed: ${testResult.success}):');
276295
if (result.info != null) {

‎packages/fuchsia_ctl/lib/src/image_paver.dart‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,25 +27,27 @@ class ImagePaver {
2727
this.processManager = const LocalProcessManager(),
2828
this.fs = const LocalFileSystem(),
2929
this.tar = const SystemTar(processManager: LocalProcessManager()),
30-
this.sshKeyManager =
31-
const SystemSshKeyManager(processManager: LocalProcessManager()),
30+
this.sshKeyManagerProvider = SystemSshKeyManager.defaultProvider,
3231
}) : assert(processManager != null),
3332
assert(fs != null),
34-
assert(tar != null),
35-
assert(sshKeyManager != null);
33+
assert(tar != null);
3634

3735
/// The [ProcessManager] used to launch the boot server, `tar`,
3836
/// and `ssh-keygen`.
3937
final ProcessManager processManager;
4038

39+
/// The default pave timeout as [Duration] in milliseconds.
40+
static const Duration defaultPaveTimeoutMs =
41+
Duration(milliseconds: 5 * 60 * 1000);
42+
4143
/// The [FileSystem] implementation used to
4244
final FileSystem fs;
4345

4446
/// The implementation to use for untarring system images.
4547
final Tar tar;
4648

4749
/// The implementation to use for creating SSH keys.
48-
final SshKeyManager sshKeyManager;
50+
final SshKeyManagerProvider sshKeyManagerProvider;
4951

5052
/// Paves an image (in .tgz format) to the specified device.
5153
///
@@ -54,14 +56,21 @@ class ImagePaver {
5456
Future<OperationResult> pave(
5557
String imageTgzPath,
5658
String deviceName, {
59+
String publicKeyPath,
5760
bool verbose = true,
61+
Duration timeoutMs = defaultPaveTimeoutMs,
5862
}) async {
5963
assert(imageTgzPath != null);
6064
if (deviceName == null) {
6165
stderr.writeln('Warning: No device name specified. '
6266
'If multiple devices are attached, this may result in paving '
6367
'an unexpected device.');
6468
}
69+
final SshKeyManager sshKeyManager = sshKeyManagerProvider(
70+
processManager: processManager,
71+
publicKeyPath: publicKeyPath,
72+
fs: fs,
73+
);
6574
final String uuid = Uuid().v4();
6675
final Directory imageDirectory = fs.directory('image_$uuid');
6776
if (verbose) {
@@ -98,7 +107,7 @@ class ImagePaver {
98107
if (deviceName != null) ...<String>['-n', deviceName],
99108
'--authorized-keys', '.ssh/authorized_keys',
100109
],
101-
);
110+
).timeout(timeoutMs);
102111
final StringBuffer paveStdout = StringBuffer();
103112
final StringBuffer paveStderr = StringBuffer();
104113
paveProcess.stdout.transform(utf8.decoder).forEach((String s) {

‎packages/fuchsia_ctl/lib/src/ssh_client.dart‎

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
import 'dart:async';
56
import 'dart:convert';
67
import 'dart:io';
78

@@ -25,6 +26,10 @@ class SshClient {
2526
/// The [ProcessManager] to use for spawning `ssh`.
2627
final ProcessManager processManager;
2728

29+
/// The default ssh timeout as [Duration] in milliseconds.
30+
static const Duration defaultSshTimeoutMs =
31+
Duration(milliseconds: 5 * 60 * 1000);
32+
2833
/// Creates a list of arguments to pass to ssh.
2934
///
3035
/// This method is not intended for use outside of this library, except for
@@ -84,23 +89,24 @@ class SshClient {
8489
/// [DevFinder] class.
8590
///
8691
/// All arguments must not be null.
87-
Future<OperationResult> runCommand(
88-
String targetIp, {
89-
@required String identityFilePath,
90-
@required List<String> command,
91-
}) async {
92+
Future<OperationResult> runCommand(String targetIp,
93+
{@required String identityFilePath,
94+
@required List<String> command,
95+
Duration timeoutMs = defaultSshTimeoutMs}) async {
9296
assert(targetIp != null);
9397
assert(identityFilePath != null);
9498
assert(command != null);
9599

96100
return OperationResult.fromProcessResult(
97-
await processManager.run(
98-
getSshArguments(
99-
identityFilePath: identityFilePath,
100-
targetIp: targetIp,
101-
command: command,
102-
),
103-
),
101+
await processManager
102+
.run(
103+
getSshArguments(
104+
identityFilePath: identityFilePath,
105+
targetIp: targetIp,
106+
command: command,
107+
),
108+
)
109+
.timeout(timeoutMs),
104110
);
105111
}
106112
}

‎packages/fuchsia_ctl/lib/src/ssh_key_manager.dart‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
import 'dart:io';
5+
import 'dart:io' as io;
66

77
import 'package:file/file.dart';
88
import 'package:file/local.dart';
@@ -11,6 +11,13 @@ import 'package:process/process.dart';
1111

1212
import 'operation_result.dart';
1313

14+
/// Function signature for a [SshKeyManager] provider.
15+
typedef SshKeyManagerProvider = SshKeyManager Function({
16+
ProcessManager processManager,
17+
FileSystem fs,
18+
String publicKeyPath,
19+
});
20+
1421
/// A wrapper for managing SSH key generation.
1522
///
1623
/// Implemented by [SystemSshKeyManager].
@@ -32,16 +39,40 @@ class SystemSshKeyManager implements SshKeyManager {
3239
const SystemSshKeyManager({
3340
this.processManager = const LocalProcessManager(),
3441
this.fs = const LocalFileSystem(),
42+
this.pkeyPubPath,
3543
}) : assert(processManager != null),
3644
assert(fs != null);
3745

46+
/// Creates a static provider that returns a SystemSshKeyManager.
47+
static SshKeyManager defaultProvider({
48+
ProcessManager processManager,
49+
FileSystem fs,
50+
String publicKeyPath,
51+
}) {
52+
return SystemSshKeyManager(
53+
processManager: processManager ?? const LocalProcessManager(),
54+
fs: fs,
55+
pkeyPubPath: publicKeyPath,
56+
);
57+
}
58+
3859
/// The [ProcessManager] implementation to use when spawning ssh-keygen.
3960
final ProcessManager processManager;
4061

4162
/// The [FileSystem] implementation to use when creating the authorized_keys
4263
/// file.
4364
final FileSystem fs;
4465

66+
/// The [String] with the path to a public key.
67+
final String pkeyPubPath;
68+
69+
/// Populates [authorizedKeys] file with the public key in [pKeyPub].
70+
Future<void> createAuthorizedKeys(File authorizedKeys, File pkeyPub) async {
71+
final List<String> pkeyPubParts = pkeyPub.readAsStringSync().split(' ');
72+
await authorizedKeys
73+
.writeAsString('${pkeyPubParts[0]} ${pkeyPubParts[1]}\n');
74+
}
75+
4576
@override
4677
Future<OperationResult> createKeys({
4778
String destinationPath = '.ssh',
@@ -58,9 +89,14 @@ class SystemSshKeyManager implements SshKeyManager {
5889
}
5990

6091
await sshDir.create();
92+
if (pkeyPubPath != null) {
93+
await createAuthorizedKeys(authorizedKeys, fs.file(pkeyPubPath));
94+
return OperationResult.success(info: 'Using previously generated keys.');
95+
}
96+
6197
final File pkey = sshDir.childFile('pkey');
6298
final File pkeyPub = sshDir.childFile('pkey.pub');
63-
final ProcessResult result = await processManager.run(
99+
final io.ProcessResult result = await processManager.run(
64100
<String>[
65101
'ssh-keygen',
66102
'-t', 'ed25519', //
@@ -72,10 +108,7 @@ class SystemSshKeyManager implements SshKeyManager {
72108
if (result.exitCode != 0) {
73109
return OperationResult.fromProcessResult(result);
74110
}
75-
76-
final List<String> pkeyPubParts = pkeyPub.readAsStringSync().split(' ');
77-
await authorizedKeys
78-
.writeAsString('${pkeyPubParts[0]} ${pkeyPubParts[1]}\n');
111+
await createAuthorizedKeys(authorizedKeys, pkeyPub);
79112
return OperationResult.fromProcessResult(result);
80113
}
81114
}

0 commit comments

Comments
 (0)