-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
1776 lines (1551 loc) · 53.3 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright 2022 Oxide Computer Company
#[cfg(test)]
mod test;
mod util;
pub mod cli;
pub mod error;
pub mod serial;
pub mod unit;
use anyhow::Context;
use camino::{Utf8Path, Utf8PathBuf};
use error::Error;
use futures::future::join_all;
use futures::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use ron::ser::{to_string_pretty, PrettyConfig};
use serde::{Deserialize, Serialize};
use slog::Drain;
use slog::{debug, error, info, warn, Logger};
use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::convert::TryInto;
use std::fs::{self, OpenOptions};
use std::io::BufWriter;
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::process::Command;
use std::str::FromStr;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::time::{sleep, Duration, Instant};
use uuid::Uuid;
use xz2::read::XzDecoder;
use propolis_client::types::InstanceMetadata;
use propolis_client::types::{
ComponentV0, DlpiNetworkBackend, FileStorageBackend, P9fs, SerialPort,
SerialPortNumber, SoftNpuP9, SoftNpuPciPort, SoftNpuPort, VirtioDisk,
VirtioNetworkBackend, VirtioNic,
};
use propolis_client::PciPath;
use propolis_client::SpecKey;
#[macro_export]
macro_rules! node {
($d:ident, $name:ident, $img:literal, $cores:literal, $mem:expr) => {
let $name = $d.node(stringify!($name), $img, $cores, $mem);
};
($d:ident, $name:ident, $img:ident, $cores:literal, $mem:expr) => {
let $name = $d.node(stringify!($name), $img, $cores, $mem);
};
}
#[macro_export]
macro_rules! cmd {
($d:expr, $node:expr, $cmd:expr, $msg:expr) => {{
let bx: std::pin::Pin<
Box<
dyn futures::future::Future<
Output = Result<String, anyhow::Error>,
>,
>,
> = Box::pin(async {
info!($d.log, "{} start", $msg);
let result = $d
.exec($node, $cmd)
.await
.map_err(|e| anyhow!("{} {e}", $msg));
info!($d.log, "{} finish", $msg);
result
});
bx
}};
}
pub const DEFAULT_FALCON_DIR: &str = ".falcon";
const ZFS_BIN: &str = "/usr/sbin/zfs";
const DLADM_BIN: &str = "/usr/sbin/dladm";
const DD_BIN: &str = "/usr/bin/dd";
const RM_BIN: &str = "/usr/bin/rm";
const TRUNCATE_BIN: &str = "/usr/bin/truncate";
pub struct Runner {
/// The deployment object that describes the Falcon topology
pub deployment: Deployment,
/// If persistent is set to true, this deployment will not autodestruct when
/// dropped.
pub persistent: bool,
/// The propolis-server binary to use
pub propolis_binary: String,
pub log: Logger,
/// The root dataset to use for falcon activities
pub dataset: String,
/// The location of the ".falcon" directory for a given deployment
///
/// This directory is created by falcon and stores configuration.
pub falcon_dir: Utf8PathBuf,
}
/// A Deployment is the top level Falcon object. It contains a set of nodes and
/// links that are logically namespaced under the name of the deployment. Links
/// interconnect nodes forming a network.
#[derive(Serialize, Deserialize)]
pub struct Deployment {
/// The name of this deployment
pub name: String,
/// The nodes of this deployment
pub nodes: Vec<Node>,
/// The point to point links of this deployment interconnectiong nodes
pub links: Vec<Link>,
/// External links connected to a host data link such as a phy or a vnic.
pub ext_links: Vec<ExtLink>,
}
impl Default for Deployment {
fn default() -> Self {
Deployment {
name: "".to_string(),
nodes: Vec::new(),
links: Vec::new(),
ext_links: Vec::new(),
}
}
}
#[derive(Serialize, Deserialize)]
pub enum PrimaryDiskBacking {
/// Use a zvol cloned from the image source.
Zvol,
/// Use a file copied from the image source.
File,
}
/// A node in a falcon network.
#[derive(Serialize, Deserialize)]
pub struct Node {
/// Name of the node
pub name: String,
/// Image node uses
pub image: String,
/// How many links the node has
pub radix: usize,
/// Mounted file systems
pub mounts: Vec<Mount>,
/// uuid of the node
pub id: uuid::Uuid,
/// how many cores to give the node
pub cores: u8,
/// how much memory to give the node in mb
pub memory: u64,
/// The root dataset to use for falcon activities
pub dataset: String,
/// Whether or not to do initial setup on the node
pub do_setup: bool,
/// How much space to reserve on the boot disk in GB.
pub reserved: usize,
/// How to create the backing of the main disk.
pub primary_disk_backing: PrimaryDiskBacking,
/// VNC port to use
pub vnc_port: Option<u16>,
/// Propolis components for instance spec
pub components: BTreeMap<SpecKey, ComponentV0>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum GuestMountMechanism {
P9kp,
Mount,
}
/// Directories mounted from host machine into a node.
#[derive(Debug, Serialize, Deserialize)]
pub struct Mount {
/// Directory from host to mount.
pub source: Utf8PathBuf,
/// Directory in node to mount to.
pub destination: Utf8PathBuf,
/// Mechanism to mount in the guest.
pub mechanism: GuestMountMechanism,
}
/// Node references are passed back to clients when nodes are created. These are
/// an opaque handle that can be used in conjunction with various methods
/// provided by the Deployment implementation.
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct NodeRef {
/// The index of the referenced node in `Deployment::nodes`
index: usize,
}
/// Links connect nodes through a pair of Endpoints. Links are strictly point to
/// point. They are meant to represent a single cable between machines. The only
/// future exception to this may be for breakout cables that have a 1 to N
/// fanout.
#[derive(Serialize, Deserialize)]
pub struct Link {
pub endpoints: [Endpoint; 2],
}
#[derive(Serialize, Deserialize)]
pub struct ExtLink {
pub endpoint: Endpoint,
pub host_ifx: String,
pub exclusive: bool,
}
/// Endpoint kind determines what type of device will be chosen to underpin a
/// given endpoint on a VM.
#[derive(Serialize, Deserialize, Clone)]
pub enum EndpointKind {
/// Use a bhyve/viona kernel device. This is the default. Optionally specify
/// mac.
Viona(Option<String>),
/// A link connected to a SoftNPU device with an optional MAC specification
SoftNPU(Option<String>),
}
impl EndpointKind {
fn designator(&self) -> &'static str {
match self {
Self::Viona(_) => "vn",
Self::SoftNPU(_) => "sn",
}
}
}
/// Endpoints are owned by a Link and reference nodes through a references.
#[derive(Serialize, Deserialize, Clone)]
pub struct Endpoint {
/// The node this endpiont is attached to
node: NodeRef,
/// The link index within the referenced node e.g., if this is the 3rd link
/// in the referenzed node index=2.
index: usize,
/// What kind of virtual device this endpoint will be realized as.
kind: EndpointKind,
}
/// Opaque handle to a link. Used by clients to perform API functions on
/// links owned by a Deployment.
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct LinkRef {
/// The index of the referenced link in `Deployment::links`
_index: usize,
}
impl Runner {
pub fn new(name: &str) -> Self {
namecheck!(name, "deployment");
match std::env::var("RUST_LOG") {
Ok(s) => {
if s.is_empty() {
unsafe {
std::env::set_var("RUST_LOG", "info");
}
}
}
_ => unsafe {
std::env::set_var("RUST_LOG", "info");
},
}
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_envlogger::new(drain).fuse();
let drain = slog_async::Async::new(drain).build().fuse();
Runner {
deployment: Deployment::new(name),
log: slog::Logger::root(drain, slog::o!()),
persistent: false,
propolis_binary: "propolis-server".into(),
dataset: dataset(),
falcon_dir: DEFAULT_FALCON_DIR.into(),
}
}
pub fn set_falcon_dir(&mut self, dir: &Utf8Path) {
self.falcon_dir = dir.to_string().into();
info!(self.log, "set falcon dir to {}", self.falcon_dir);
}
/// Create a new node within this deployment with the given name. Names must
/// conform to `[A-Za-z]?[A-Za-z0-9_]*`
pub fn node(
&mut self,
name: &str,
image: &str,
cores: u8,
memory: u64,
) -> NodeRef {
namecheck!(name, "node");
let id = uuid::Uuid::new_v4();
let r = NodeRef {
index: self.deployment.nodes.len(),
};
let n = Node {
name: String::from(name),
image: String::from(image),
dataset: self.dataset.clone(),
radix: 0,
mounts: Vec::new(),
id,
cores,
memory,
do_setup: true,
reserved: 20,
primary_disk_backing: PrimaryDiskBacking::Zvol,
vnc_port: None,
components: BTreeMap::new(),
};
self.deployment.nodes.push(n);
r
}
pub fn find_node(&self, name: &str) -> Option<NodeRef> {
Some(NodeRef {
index: self.deployment.nodes.iter().position(|x| x.name == name)?,
})
}
pub fn all_nodes(&self) -> Vec<NodeRef> {
let mut result = Vec::new();
for index in 0..self.deployment.nodes.len() {
result.push(NodeRef { index })
}
result
}
pub fn get_node(&self, r: NodeRef) -> &Node {
&self.deployment.nodes[r.index]
}
pub fn do_setup(&mut self, r: NodeRef, value: bool) {
self.deployment.nodes[r.index].do_setup = value;
}
pub fn bump_radix(&mut self, node: NodeRef) -> usize {
let current = self.deployment.nodes[node.index].radix;
self.deployment.nodes[node.index].radix += 1;
current
}
/// Create a new link within this deployment between the referenced nodes.
pub fn link(&mut self, a: NodeRef, b: NodeRef) -> LinkRef {
let r = LinkRef {
_index: self.deployment.links.len(),
};
let l = Link {
endpoints: [
Endpoint {
node: a,
index: self.deployment.nodes[a.index].radix,
kind: EndpointKind::Viona(None),
},
Endpoint {
node: b,
index: self.deployment.nodes[b.index].radix,
kind: EndpointKind::Viona(None),
},
],
};
self.deployment.links.push(l);
self.deployment.nodes[a.index].radix += 1;
self.deployment.nodes[b.index].radix += 1;
r
}
pub fn softnpu_link(
&mut self,
softnpu_node: NodeRef,
node: NodeRef,
node_mac: Option<String>,
softnpu_mac: Option<String>,
) -> LinkRef {
let r = LinkRef {
_index: self.deployment.links.len(),
};
let l = Link {
endpoints: [
Endpoint {
node: softnpu_node,
index: self.deployment.nodes[softnpu_node.index].radix,
kind: EndpointKind::SoftNPU(softnpu_mac),
},
Endpoint {
node,
index: self.deployment.nodes[node.index].radix,
kind: EndpointKind::Viona(node_mac),
},
],
};
self.deployment.links.push(l);
self.deployment.nodes[softnpu_node.index].radix += 1;
self.deployment.nodes[node.index].radix += 1;
r
}
pub fn softnpu_links(
&mut self,
node1: NodeRef,
node2: NodeRef,
mac1: Option<String>,
mac2: Option<String>,
) -> LinkRef {
let r = LinkRef {
_index: self.deployment.links.len(),
};
let l = Link {
endpoints: [
Endpoint {
node: node1,
index: self.deployment.nodes[node1.index].radix,
kind: EndpointKind::SoftNPU(mac1),
},
Endpoint {
node: node2,
index: self.deployment.nodes[node2.index].radix,
kind: EndpointKind::SoftNPU(mac2),
},
],
};
self.deployment.links.push(l);
self.deployment.nodes[node1.index].radix += 1;
self.deployment.nodes[node2.index].radix += 1;
r
}
pub fn reserve(&mut self, n: NodeRef, gb: usize) {
self.deployment.nodes[n.index].reserved = gb;
}
pub fn set_backing(&mut self, n: NodeRef, backing: PrimaryDiskBacking) {
self.deployment.nodes[n.index].primary_disk_backing = backing
}
/// Create an external link attached to `host_ifx` via a new VNIC.
pub fn ext_link(&mut self, host_ifx: impl AsRef<str>, n: NodeRef) {
self.ext_link_common(host_ifx, n, false);
}
/// Create an external link, consuming the link `host_ifx`.
pub fn ext_link_exclusive(
&mut self,
host_ifx: impl AsRef<str>,
n: NodeRef,
) {
self.ext_link_common(host_ifx, n, true);
}
fn ext_link_common(
&mut self,
host_ifx: impl AsRef<str>,
n: NodeRef,
exclusive: bool,
) {
let endpoint = Endpoint {
node: n,
index: self.deployment.nodes[n.index].radix,
kind: EndpointKind::Viona(None),
};
let host_ifx = host_ifx.as_ref().into();
self.deployment.ext_links.push(ExtLink {
endpoint,
host_ifx,
exclusive,
});
self.deployment.nodes[n.index].radix += 1;
}
/// Provide the host folder `src` as a p9fs mount to the guest with the tag
/// `dst`.
pub fn do_mount(
&mut self,
src: impl AsRef<Utf8Path>,
dst: impl AsRef<Utf8Path>,
n: NodeRef,
mechanism: GuestMountMechanism,
) -> Result<(), Error> {
let src = src.as_ref();
let src = src.canonicalize_utf8().map_err(|error| {
Error::PathError(format!(
"{}: canonicalization error: {}",
src, error
))
})?;
self.deployment.nodes[n.index].mounts.push(Mount {
source: src,
destination: dst.as_ref().to_owned(),
mechanism,
});
Ok(())
}
pub fn mount(
&mut self,
src: impl AsRef<Utf8Path>,
dst: impl AsRef<Utf8Path>,
n: NodeRef,
) -> Result<(), Error> {
self.do_mount(src, dst, n, GuestMountMechanism::P9kp)
}
pub fn mount_linux(
&mut self,
src: impl AsRef<Utf8Path>,
dst: impl AsRef<Utf8Path>,
n: NodeRef,
) -> Result<(), Error> {
self.do_mount(src, dst, n, GuestMountMechanism::Mount)
}
/// Launch the deployment. This will clone the necessary image zvols, create
/// the propolis VM instances, create the point to point network interfaces,
/// set up the serial console for each VM and, run any user defined exec
/// statements.
pub async fn launch(&mut self) -> Result<(), Error> {
self.preflight().await?;
match self.do_launch().await {
Ok(()) => Ok(()),
Err(e) => {
error!(self.log, "launch failed: {}", e);
Err(e)
}
}
}
async fn preflight(&mut self) -> Result<(), Error> {
// Verify all required executables are discoverable.
let out = Command::new(&self.propolis_binary).args(["-V"]).output();
if out.is_err() {
return Err(Error::Exec(format!(
"failed to find {} on PATH",
&self.propolis_binary
)));
}
// validate that no external links are being jointly specified
// as exclusive and as parents of vnics.
let mut link_is_exclusive = HashMap::new();
for link in self.deployment.ext_links.iter() {
let entry = link_is_exclusive.entry(link.host_ifx.clone());
match entry {
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(link.exclusive);
}
Entry::Occupied(occupied_entry) => {
if link.exclusive || *occupied_entry.get() {
return Err(Error::ExternalNicReused(
link.host_ifx.clone(),
));
}
}
}
}
// ensure falcon working dir
fs::create_dir_all(&self.falcon_dir)?;
// write falcon config
let pretty = PrettyConfig::new().separate_tuple_members(true);
let out = format!("{}\n", to_string_pretty(&self.deployment, pretty)?);
let mut topo_path = self.falcon_dir.clone();
topo_path.push("topology.ron");
fs::write(&topo_path, out)?;
self.deployment.nodes_preflight(&self.log).await?;
Ok(())
}
async fn net_launch(&self) -> Result<(), Error> {
info!(self.log, "creating links");
for l in self.deployment.links.iter() {
l.create(self)?;
}
info!(self.log, "creating external links");
for l in self.deployment.ext_links.iter() {
l.create(self)?;
}
Ok(())
}
async fn do_launch(&self) -> Result<(), Error> {
self.net_launch().await?;
info!(self.log, "creating nodes");
let mut fs = Vec::new();
for n in self.deployment.nodes.iter() {
fs.push(n.launch(self));
}
for x in join_all(fs).await {
x?;
}
Ok(())
}
pub fn net_destroy(&self) -> Result<(), Error> {
info!(self.log, "destroying links");
for l in self.deployment.links.iter() {
l.destroy(self)?;
}
info!(self.log, "destroying external links");
for l in self.deployment.ext_links.iter() {
l.destroy(self)?;
}
Ok(())
}
/// Tear down all the nodes, followed by the links and the ZFS pool
// TODO in parallel
pub fn destroy(&self) -> Result<(), Error> {
info!(self.log, "destroying nodes");
for n in self.deployment.nodes.iter() {
n.destroy(self)?;
}
self.net_destroy()?;
// Destroy images
info!(self.log, "destroying images");
// destroy any zvol backed images
let img_dir = format!("{}/topo/{}", self.dataset, self.deployment.name);
Command::new(ZFS_BIN)
.args(["destroy", "-r", img_dir.as_ref()])
.output()?;
// destroy any file backed images
let img_dir = format!("/var/falcon/dsk/{}", self.deployment.name);
Command::new(RM_BIN)
.args(["-rf", img_dir.as_ref()])
.output()?;
// Destroy workspace
info!(self.log, "destroying workspace at {}", self.falcon_dir);
fs::remove_dir_all(&self.falcon_dir)?;
Ok(())
}
/// Run a command synchronously in the vm.
pub async fn exec(&self, n: NodeRef, cmd: &str) -> Result<String, Error> {
let name = self.deployment.nodes[n.index].name.clone();
self.do_exec(&name, cmd).await
}
async fn do_exec(&self, name: &str, cmd: &str) -> Result<String, Error> {
let mut path = self.falcon_dir.clone();
path.push(format!("{name}.uuid"));
let id = match fs::read_to_string(&path) {
Ok(u) => u,
Err(e) => {
return Err(Error::NotFound(format!(
"propolis uuid for {}: {}",
name, e
)));
}
};
path.pop();
path.push(format!("{name}.port"));
let port = match fs::read_to_string(&path) {
Ok(p) => p.as_str().parse::<u16>()?,
Err(e) => {
return Err(Error::NotFound(format!(
"get propolis port for {}: {}",
name, e
)));
}
};
path.pop();
let addr = SocketAddr::new(
IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
port,
);
let mut sc = serial::SerialCommander::new(
addr,
id,
name.into(),
self.log.clone(),
);
let mut ws = sc.start(true).await?;
let out = sc.exec(&mut ws, cmd.to_string()).await?;
sc.logout(&mut ws).await?;
Ok(out)
}
}
impl Deployment {
/// Create a new deployment with the given name. Names must conform to
/// [A-Za-z]?[A-Za-z0-9_]*
pub fn new(name: &str) -> Self {
namecheck!(name, "deployment");
Deployment {
name: String::from(name),
nodes: Vec::new(),
links: Vec::new(),
ext_links: Vec::new(),
}
}
fn simnet_link_name(&self, e: &Endpoint) -> String {
format!(
"{}_{}_{}_sim{}",
self.name,
self.nodes[e.node.index].name,
e.kind.designator(),
e.index,
)
}
fn vnic_link_name(&self, e: &Endpoint) -> String {
format!(
"{}_{}_{}_vnic{}",
self.name,
self.nodes[e.node.index].name,
e.kind.designator(),
e.index,
)
}
async fn nodes_preflight(&mut self, log: &Logger) -> Result<(), Error> {
let mut endpoints = Vec::new();
for l in &self.links {
for e in &l.endpoints {
endpoints.push(NodeEndpoint {
vnic_name: self.vnic_link_name(e),
endpoint: e.clone(),
});
}
}
for l in &self.ext_links {
let vnic_name = if l.exclusive {
l.host_ifx.clone()
} else {
self.vnic_link_name(&l.endpoint)
};
endpoints.push(NodeEndpoint {
vnic_name,
endpoint: l.endpoint.clone(),
})
}
let mut node_endpoints_map: HashMap<String, Vec<NodeEndpoint>> =
HashMap::new();
let mut softnpu_deployment = false;
for n in self.nodes.iter() {
let node_endpoints: Vec<NodeEndpoint> = endpoints
.iter()
.filter(|e| self.nodes[e.endpoint.node.index].name == n.name)
.cloned()
.collect();
let has_softnpu = node_endpoints.iter().any(|ne| {
matches!(&ne.endpoint.kind, EndpointKind::SoftNPU(_))
});
softnpu_deployment |= has_softnpu;
node_endpoints_map.insert(n.name.clone(), node_endpoints);
}
for n in self.nodes.iter_mut() {
n.preflight(
log,
&self.name,
&node_endpoints_map[&n.name],
softnpu_deployment,
)
.await?;
}
Ok(())
}
}
impl Drop for Runner {
fn drop(&mut self) {
if !self.persistent {
match self.destroy() {
Ok(()) => {}
Err(e) => error!(self.log, "cleanup failed: {}", e),
}
}
}
}
#[derive(Clone)]
struct NodeEndpoint {
vnic_name: String,
endpoint: Endpoint,
}
impl Node {
async fn preflight(
&mut self,
log: &Logger,
deployment_name: &str,
node_endpoints: &[NodeEndpoint],
softnpu_deployment: bool,
) -> Result<(), Error> {
self.try_ensure_base_image(log).await?;
// Propolis supports COM1 to COM4, so ensure those devices are present.
// Note COM4 will be added implicitly due to the presence of a
// SoftNpuPciPort device in the spec, and it will be commandeered by
// SoftNPU devices.
self.components.insert(
SpecKey::Name("com1".into()),
ComponentV0::SerialPort(SerialPort {
num: SerialPortNumber::Com1,
}),
);
self.components.insert(
SpecKey::Name("com2".into()),
ComponentV0::SerialPort(SerialPort {
num: SerialPortNumber::Com2,
}),
);
self.components.insert(
SpecKey::Name("com3".into()),
ComponentV0::SerialPort(SerialPort {
num: SerialPortNumber::Com3,
}),
);
let backing = match self.primary_disk_backing {
PrimaryDiskBacking::Zvol => {
self.create_zvol_backing(deployment_name)?
}
PrimaryDiskBacking::File => {
self.create_file_backing(log, deployment_name)?
}
};
self.create_blockdev(backing);
let mut pci_index = 5;
// mounts
for (i, m) in self.mounts.iter().enumerate() {
self.components.insert(
SpecKey::Name(format!("fs{i}")),
ComponentV0::P9fs(P9fs {
source: m.source.to_string(),
target: m.destination.to_string(),
chunk_size: 65536, // XXX magic number?
pci_path: PciPath::new(0, pci_index, 0).unwrap(),
}),
);
pci_index += 1;
}
// network interfaces
let mut viona_index = 0;
let mut softnpu_index = 0;
// if using a softnpu deployment, each instance must have the following
// components, but note that the spec keys will (current) be overwritten
// by propolis-server
if softnpu_deployment {
self.components.insert(
SpecKey::Name("softnpu-p9".into()),
ComponentV0::SoftNpuP9(SoftNpuP9 {
pci_path: PciPath::new(0, pci_index, 0).unwrap(),
}),
);
pci_index += 1;
self.components.insert(
SpecKey::Name("softnpu-pci-port".into()),
ComponentV0::SoftNpuPciPort(SoftNpuPciPort {
pci_path: PciPath::new(0, pci_index, 0).unwrap(),
}),
);
pci_index += 1;
// note: softnpu requires com4 but propolis-server will add that for
// us
}
for NodeEndpoint {
vnic_name,
endpoint,
} in node_endpoints
{
match &endpoint.kind {
EndpointKind::Viona(_) => {
self.components.insert(
SpecKey::Name(format!("net{viona_index}-backing")),
ComponentV0::VirtioNetworkBackend(
VirtioNetworkBackend {
vnic_name: vnic_name.clone(),
},
),
);
self.components.insert(
SpecKey::Name(format!("net{viona_index}")),
ComponentV0::VirtioNic(VirtioNic {
backend_id: SpecKey::Name(format!(
"net{viona_index}-backing"
)),
interface_id: Uuid::new_v4(),
pci_path: PciPath::new(0, pci_index, 0).unwrap(),
}),
);
viona_index += 1;
pci_index += 1;
}
// XXX is mac used in spec?
EndpointKind::SoftNPU(_mac) => {
let backend_id = SpecKey::Name(format!(
"softnpu{softnpu_index}-backing"
));
self.components.insert(
backend_id.clone(),
ComponentV0::DlpiNetworkBackend(DlpiNetworkBackend {
vnic_name: vnic_name.clone(),
}),
);
self.components.insert(
SpecKey::Name(format!("softnpu{softnpu_index}-port")),
ComponentV0::SoftNpuPort(SoftNpuPort {
link_name: format!("softnpu{softnpu_index}"),
backend_id,
}),
);
softnpu_index += 1;
}
}
}
Ok(())
}
async fn try_ensure_base_image(&self, log: &Logger) -> Result<(), Error> {
match Command::new(ZFS_BIN)
.args([
"list",
"-t",
"snapshot",
format!("{}/img/{}@base", self.dataset, self.image).as_str(),
])
.output()
{
Ok(output) if output.status.success() => Ok(()),
_ => {
info!(
log,
"base image for {} does not exist, attempting to install",