-
Notifications
You must be signed in to change notification settings - Fork 3
/
single_sp.rs
2368 lines (2122 loc) · 81.7 KB
/
single_sp.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
//! Interface for communicating with a single SP.
use crate::error::CommunicationError;
use crate::error::UpdateError;
use crate::shared_socket::SingleSpHandle;
use crate::shared_socket::SingleSpHandleError;
use crate::shared_socket::SingleSpMessage;
use crate::sp_response_expect::*;
use crate::SharedSocket;
use crate::SwitchPortConfig;
use crate::VersionedSpState;
use async_trait::async_trait;
use backoff::backoff::Backoff;
use gateway_messages::ignition::LinkEvents;
use gateway_messages::ignition::TransceiverSelect;
use gateway_messages::tlv;
use gateway_messages::version;
use gateway_messages::version::WATCHDOG_VERSION;
use gateway_messages::BadRequestReason;
use gateway_messages::CfpaPage;
use gateway_messages::ComponentAction;
use gateway_messages::ComponentActionResponse;
use gateway_messages::ComponentDetails;
use gateway_messages::DeviceCapabilities;
use gateway_messages::DeviceDescriptionHeader;
use gateway_messages::DevicePresence;
use gateway_messages::Header;
use gateway_messages::IgnitionCommand;
use gateway_messages::IgnitionState;
use gateway_messages::Message;
use gateway_messages::MessageKind;
use gateway_messages::MgsRequest;
use gateway_messages::MonorailError;
use gateway_messages::PowerState;
use gateway_messages::RotBootInfo;
use gateway_messages::RotRequest;
use gateway_messages::SensorReading;
use gateway_messages::SensorRequest;
use gateway_messages::SensorRequestKind;
use gateway_messages::SensorResponse;
use gateway_messages::SpComponent;
use gateway_messages::SpError;
use gateway_messages::SpPort;
use gateway_messages::SpRequest;
use gateway_messages::SpResponse;
use gateway_messages::SprotProtocolError;
use gateway_messages::StartupOptions;
use gateway_messages::TlvPage;
use gateway_messages::UpdateStatus;
use gateway_messages::MIN_TRAILING_DATA_LEN;
use gateway_messages::ROT_PAGE_SIZE;
use serde::Serialize;
use slog::debug;
use slog::error;
use slog::info;
use slog::trace;
use slog::warn;
use slog::Logger;
use std::io::Cursor;
use std::io::Seek;
use std::io::SeekFrom;
use std::net::SocketAddr;
use std::net::SocketAddrV6;
use std::str;
use std::time::Duration;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TryRecvError;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use tokio::time;
use tokio::time::Instant;
use uuid::Uuid;
mod update;
use self::update::start_component_update;
use self::update::start_rot_update;
use self::update::start_sp_update;
use self::update::update_status;
// Once we've discovered an SP, continue to send discovery packets on this
// interval to detect changes.
//
// TODO-correctness/TODO-security What do we do if the SP address changes?
const DISCOVERY_INTERVAL_IDLE: Duration = Duration::from_secs(60);
// Minor "malicious / misbehaving SP" denial of service protection: When we ask
// the SP for its inventory or details of a component, we get back a response
// indicating the total number of TLV triples the SP will return in response to
// our query. We then repeatedly call the SP to fetch all of those triples
// (getting back multiple triples per call, hopefully, but that's fully in the
// SP's control). The number of triples is a u32; if an SP claimed to have an
// absurdly large number, we'd be stuck fetching that many (and building up a
// Vec of them in memory). We set a "we never expect this many devices" cap
// here; 1024 is over 10x our current gimlet rev-c device inventory count, so
// this should be plenty of buffer. If it needs to increase in the future, that
// will require an MGS update.
const TLV_RPC_TOTAL_ITEMS_DOS_LIMIT: u32 = 1024;
// We allow our client to specify the max RPC attempts and the
// per-attempt timeout; however, it's very easy to set a timeout that is
// too low for the "reset the SP" request, especially if the SP being
// reset is a sidecar (which means it won't be able to respond until it
// brings the management network back online). We will override the max
// attempt count for only that message to ensure we give SPs ample time
// to reset.
const SP_RESET_TIME_ALLOWED: Duration = Duration::from_secs(30);
type Result<T, E = CommunicationError> = std::result::Result<T, E>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HostPhase2Request {
pub hash: [u8; 32],
pub offset: u64,
pub data_sent: u64,
pub received: Instant,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SpInventory {
pub devices: Vec<SpDevice>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SpDevice {
pub component: SpComponent,
pub device: String,
pub description: String,
pub capabilities: DeviceCapabilities,
pub presence: DevicePresence,
}
#[derive(Debug, Clone)]
pub struct SpComponentDetails {
pub entries: Vec<ComponentDetails>,
}
#[derive(Debug)]
pub struct SingleSp {
interface: String,
cmds_tx: mpsc::Sender<InnerCommand>,
sp_addr_rx: watch::Receiver<Option<(SocketAddrV6, SpPort)>>,
inner_task: JoinHandle<()>,
log: Logger,
}
impl Drop for SingleSp {
fn drop(&mut self) {
self.inner_task.abort();
}
}
impl SingleSp {
/// Construct a new `SingleSp` that will periodically attempt to discover an
/// SP reachable on the port specified by `config`.
///
/// This function returns immediately, but returns an object that is
/// initially (and possibly always) unusable: until we complete any local
/// setup for our UDP socket, methods of the returned `SingleSp` will fail.
/// The local setup includes:
///
/// 1. Waiting for an interface with the name specified by
/// `config.interface` to exist (if `config.interface` is `Some(_)`). We
/// determine this via `if_nametoindex()`. This step never fails, but
/// will block forever waiting for the interface.
/// 2. Binding a UDP socket to `config.listen_addr` (with a `scope_id`
/// determined by the previous step). If this bind fails (e.g., because
/// `config.listen_addr` is invalid), the returned `SingleSp` will return
/// a "UDP bind failed" error from all methods forever.
///
/// Note that `max_attempts_per_rpc` may be overridden for certain kinds of
/// requests. Today, the only request that overrides this value is resetting
/// an SP, which (particularly for sidecars) can take much longer than any
/// other request. `SingleSp` will internally use a higher max attempt count
/// for these messages (but will still respect `per_attempt_timeout`).
pub async fn new(
shared_socket: &SharedSocket,
config: SwitchPortConfig,
max_attempts_per_rpc: usize,
per_attempt_timeout: Duration,
) -> Self {
let handle = shared_socket
.single_sp_handler(&config.interface, config.discovery_addr)
.await;
let log = handle.log().clone();
Self::new_impl(
handle,
config.interface,
max_attempts_per_rpc,
per_attempt_timeout,
log,
)
}
/// Create a new `SingleSp` instance specifically for testing (i.e.,
/// communicating with a simulated SP).
///
/// Unlike [`SingleSp::new()`], this method takes an existing bound
/// [`UdpSocket`] and the target address of the SP. This allows multiple
/// `SingleSp`s to exist on the same interface (e.g., the loopback
/// interface) for testing.
pub fn new_direct_socket_for_testing(
socket: UdpSocket,
discovery_addr: SocketAddrV6,
max_attempts_per_rpc: usize,
per_attempt_timeout: Duration,
log: Logger,
) -> Self {
let wrapper =
InnerSocketWrapper { socket, discovery_addr, log: log.clone() };
Self::new_impl(
wrapper,
"(direct socket handle)".to_string(),
max_attempts_per_rpc,
per_attempt_timeout,
log,
)
}
// Shared implementation of `new` and `new_direct_socket_for_testing` that
// doesn't care whether we're using a `SharedSocket` or a
// `InnerSocketWrapper` (the latter for tests).
fn new_impl<T: InnerSocket + Send + 'static>(
socket: T,
interface: String,
max_attempts_per_rpc: usize,
per_attempt_timeout: Duration,
log: Logger,
) -> Self {
// SPs don't support pipelining, so any command we send to
// `Inner` that involves contacting an SP will effectively block
// until it completes. We use a more-or-less arbitrary chanel
// size of 8 here to allow (a) non-SP commands (e.g., detaching
// the serial console) and (b) a small number of enqueued SP
// commands to be submitted without blocking the caller.
let (cmds_tx, cmds_rx) = mpsc::channel(8);
let (sp_addr_tx, sp_addr_rx) = watch::channel(None);
let inner = Inner::new(
socket,
sp_addr_tx,
max_attempts_per_rpc,
per_attempt_timeout,
cmds_rx,
);
let inner_task = tokio::spawn(inner.run());
Self { interface, cmds_tx, sp_addr_rx, inner_task, log }
}
fn log(&self) -> &Logger {
&self.log
}
pub fn interface(&self) -> &str {
&self.interface
}
/// Retrieve the [`watch::Receiver`] for notifications of discovery of an
/// SP's address.
pub fn sp_addr_watch(
&self,
) -> &watch::Receiver<Option<(SocketAddrV6, SpPort)>> {
&self.sp_addr_rx
}
/// Get the most recent host phase 2 request we've received from our target
/// SP.
///
/// This method does not actively communicate with the SP; it only reports
/// the most recent request we've received from it (if any).
pub async fn most_recent_host_phase2_request(
&self,
) -> Option<HostPhase2Request> {
let (tx, rx) = oneshot::channel();
self.cmds_tx
.send(InnerCommand::GetMostRecentHostPhase2Request(tx))
.await
.unwrap();
rx.await.unwrap()
}
/// Clear the most recent host phase 2 request we've received from our
/// target SP.
///
/// This method does not actively communicate with the SP, but is inherently
/// racy with it: we could receive a host phase 2 request from our SP at any
/// time, including immediately after we clear it but even before this
/// function returns.
pub async fn clear_most_recent_host_phase2_request(&self) {
let (tx, rx) = oneshot::channel();
self.cmds_tx
.send(InnerCommand::ClearMostRecentHostPhase2Request(tx))
.await
.unwrap();
rx.await.unwrap()
}
/// Request the state of an ignition target.
///
/// This will fail if this SP is not connected to an ignition controller.
pub async fn ignition_state(&self, target: u8) -> Result<IgnitionState> {
self.rpc(MgsRequest::IgnitionState { target })
.await
.and_then(expect_ignition_state)
}
/// Request the state of all ignition targets.
///
/// This will fail if this SP is not connected to an ignition controller.
///
/// TODO: This _does not_ return the ignition state for the SP we're
/// querying (which must be an ignition controller)! If this function
/// returns successfully, it's on. Is that good enough?
pub async fn bulk_ignition_state(&self) -> Result<Vec<IgnitionState>> {
self.get_paginated_tlv_data(BulkIgnitionStateTlvRpc { log: self.log() })
.await
}
/// Request link events for a single ignition target.
///
/// This will fail if this SP is not connected to an ignition controller.
pub async fn ignition_link_events(&self, target: u8) -> Result<LinkEvents> {
self.rpc(MgsRequest::IgnitionLinkEvents { target })
.await
.and_then(expect_ignition_link_events)
}
/// Request all link events on all ignition targets.
///
/// This will fail if this SP is not connected to an ignition controller.
///
/// TODO: This _does not_ return events for the target on the SP we're
/// querying (which must be an ignition controller)!
pub async fn bulk_ignition_link_events(&self) -> Result<Vec<LinkEvents>> {
self.get_paginated_tlv_data(BulkIgnitionLinkEventsTlvRpc {
log: self.log(),
})
.await
}
/// Clear ignition link events.
///
/// If `target` is `None`, ignition events are cleared on all targets
/// (potentially restricted by `transceiver_select`).
///
/// If `transceiver_select` is `None`, ignition events are cleared for all
/// transceivers (potentially restricted by `target`).
///
/// This will fail if this SP is not connected to an ignition controller.
pub async fn clear_ignition_link_events(
&self,
target: Option<u8>,
transceiver_select: Option<TransceiverSelect>,
) -> Result<()> {
self.rpc(MgsRequest::ClearIgnitionLinkEvents {
target,
transceiver_select,
})
.await
.and_then(expect_clear_ignition_link_events_ack)
}
/// Send an ignition command to the given target.
///
/// This will fail if this SP is not connected to an ignition controller.
pub async fn ignition_command(
&self,
target: u8,
command: IgnitionCommand,
) -> Result<()> {
self.rpc(MgsRequest::IgnitionCommand { target, command })
.await
.and_then(expect_ignition_command_ack)
}
/// Request the state of the SP.
pub async fn state(&self) -> Result<VersionedSpState> {
self.rpc(MgsRequest::SpState).await.and_then(expect_sp_state)
}
/// Request the state of the RoT.
pub async fn rot_state(&self, version: u8) -> Result<RotBootInfo> {
self.rpc(MgsRequest::VersionedRotBootInfo { version })
.await
.and_then(expect_rot_boot_info)
}
/// Request the inventory of the SP.
pub async fn inventory(&self) -> Result<SpInventory> {
let devices = self.get_paginated_tlv_data(InventoryTlvRpc).await?;
Ok(SpInventory { devices })
}
/// Request the detailed status / measurements of a particular component
/// accessible to the SP.
pub async fn component_details(
&self,
component: SpComponent,
) -> Result<SpComponentDetails> {
let entries = self
.get_paginated_tlv_data(ComponentDetailsTlvRpc {
component,
log: self.log(),
})
.await?;
Ok(SpComponentDetails { entries })
}
/// Get the currently-active slot of a particular component.
pub async fn component_active_slot(
&self,
component: SpComponent,
) -> Result<u16> {
self.rpc(MgsRequest::ComponentGetActiveSlot(component))
.await
.and_then(expect_component_active_slot)
}
/// Set the currently-active slot of a particular component.
pub async fn set_component_active_slot(
&self,
component: SpComponent,
slot: u16,
persist: bool,
) -> Result<()> {
let msg = if persist {
MgsRequest::ComponentSetAndPersistActiveSlot { component, slot }
} else {
MgsRequest::ComponentSetActiveSlot { component, slot }
};
self.rpc(msg).await.and_then(if persist {
expect_component_set_and_persist_active_slot_ack
} else {
expect_component_set_active_slot_ack
})
}
/// Request that the status of a component be cleared (e.g., resetting
/// counters).
pub async fn component_clear_status(
&self,
component: SpComponent,
) -> Result<()> {
self.rpc(MgsRequest::ComponentClearStatus(component))
.await
.and_then(expect_component_clear_status_ack)
}
async fn get_paginated_tlv_data<T: TlvRpc>(
&self,
rpc: T,
) -> Result<Vec<T::Item>> {
// We don't know the total number of entries until we've requested the
// first page; we'll set this to `Some(_)` in the first iteration of the
// loop below.
let mut page0_total = None;
let mut entries = Vec::new();
while entries.len() < page0_total.unwrap_or(usize::MAX) {
// Index of the first entry we want to fetch.
let offset = entries.len() as u32;
let (page, data) = self.rpc(rpc.request(offset)).await.and_then(
|(peer, response, data)| {
rpc.parse_response(peer, response, data)
},
)?;
// Double-check the numbers we got were reasonable: did we get the
// page we asked for, and is the total correct? If this is the first
// page, "correct" just means "reasonable"; if this is the second or
// later page, it should match every other page.
if page.offset != offset {
return Err(CommunicationError::TlvPagination {
reason: "unexpected offset from SP",
});
}
let total = if let Some(n) = page0_total {
if n != page.total as usize {
return Err(CommunicationError::TlvPagination {
reason: "total item count changed",
});
}
n
} else {
if page.total > TLV_RPC_TOTAL_ITEMS_DOS_LIMIT {
return Err(CommunicationError::TlvPagination {
reason: "too many items",
});
}
let n = page.total as usize;
entries.reserve_exact(n);
page0_total = Some(n);
n
};
// Decode the TLV data.
for result in tlv::decode_iter(&data) {
// Is the TLV chunk valid?
let (tag, value) = result?;
// Are we expecting this chunk?
if entries.len() >= total {
return Err(CommunicationError::TlvPagination {
reason:
"SP returned more entries than its reported total",
});
}
// Decode this chunk.
if let Some(entry) = rpc.parse_tag_value(tag, value)? {
entries.push(entry);
} else {
info!(
self.log(),
"skipping unknown tag {tag:?} while parsing {}",
T::LOG_NAME
);
}
}
// Did our number of entries change? If not, we're presumably unable
// to parse the response (unknown TLV tags, perhaps) and won't make
// forward progress by retrying.
if entries.len() as u32 == offset && total > 0 {
return Err(CommunicationError::TlvPagination {
reason: "failed to parse any entries from SP response",
});
}
}
Ok(entries)
}
/// Get the current startup options of the target SP.
///
/// Startup options are only meaningful for sleds and will only take effect
/// the next time the sled starts up.
pub async fn get_startup_options(&self) -> Result<StartupOptions> {
self.rpc(MgsRequest::GetStartupOptions)
.await
.and_then(expect_startup_options)
}
/// Set startup options on the target SP.
///
/// Startup options are only meaningful for sleds and will only take effect
/// the next time the sled starts up.
pub async fn set_startup_options(
&self,
startup_options: StartupOptions,
) -> Result<()> {
self.rpc(MgsRequest::SetStartupOptions(startup_options))
.await
.and_then(expect_set_startup_options_ack)
}
/// Update a component of the SP (or the SP itself!).
///
/// This function will return before the update is compelte! Once the SP
/// acknowledges that we want to apply an update, we spawn a background task
/// to stream the update to the SP and then return. Poll the status of the
/// update via [`Self::update_status()`].
pub async fn start_update(
&self,
component: SpComponent,
update_id: Uuid,
slot: u16,
image: Vec<u8>,
) -> Result<(), UpdateError> {
if image.is_empty() {
return Err(UpdateError::ImageEmpty);
}
// SP updates are special (`image` is a hubris archive and may include
// an aux flash image in addition to the SP image).
if component == SpComponent::SP_ITSELF {
if slot != 0 {
// We know the SP only has one possible slot, so fail fast if
// the caller requested a slot other than 0.
return Err(UpdateError::Communication(
CommunicationError::SpError(
SpError::InvalidSlotForComponent,
),
));
}
start_sp_update(&self.cmds_tx, update_id, image, self.log()).await
} else if matches!(component, SpComponent::ROT | SpComponent::STAGE0) {
start_rot_update(
&self.cmds_tx,
update_id,
component,
slot,
image,
self.log(),
)
.await
} else {
start_component_update(
&self.cmds_tx,
component,
update_id,
slot,
image,
self.log(),
)
.await
}
}
/// Get the status of any update being applied to the given component.
pub async fn update_status(
&self,
component: SpComponent,
) -> Result<UpdateStatus> {
update_status(&self.cmds_tx, component).await
}
/// Abort an in-progress update.
pub async fn update_abort(
&self,
component: SpComponent,
update_id: Uuid,
) -> Result<()> {
self.rpc(MgsRequest::UpdateAbort { component, id: update_id.into() })
.await
.and_then(expect_update_abort_ack)
}
/// Get the current power state.
pub async fn power_state(&self) -> Result<PowerState> {
self.rpc(MgsRequest::GetPowerState).await.and_then(expect_power_state)
}
/// Set the current power state.
pub async fn set_power_state(&self, power_state: PowerState) -> Result<()> {
self.rpc(MgsRequest::SetPowerState(power_state))
.await
.and_then(expect_set_power_state_ack)
}
/// "Attach" to the serial console, setting up a tokio channel for all
/// incoming serial console packets from the SP.
pub async fn serial_console_attach(
&self,
component: SpComponent,
) -> Result<AttachedSerialConsole> {
let (tx, rx) = oneshot::channel();
// `Inner::run()` doesn't exit until we are dropped, so unwrapping here
// only panics if it itself panicked.
self.cmds_tx
.send(InnerCommand::SerialConsoleAttach(component, tx))
.await
.unwrap();
let attachment = rx.await.unwrap()?;
Ok(AttachedSerialConsole {
key: attachment.key,
rx: attachment.incoming,
inner_tx: self.cmds_tx.clone(),
log: self.log().clone(),
})
}
/// Detach any existing attached serial console connection.
pub async fn serial_console_detach(&self) -> Result<()> {
let (tx, rx) = oneshot::channel();
// `Inner::run()` doesn't exit until we are dropped, so unwrapping here
// only panics if it itself panicked.
self.cmds_tx
.send(InnerCommand::SerialConsoleDetach(None, tx))
.await
.unwrap();
rx.await.unwrap()
}
pub(crate) async fn rpc(
&self,
kind: MgsRequest,
) -> Result<(SocketAddrV6, SpResponse, Vec<u8>)> {
rpc(&self.cmds_tx, kind, None).await.result
}
pub async fn send_host_nmi(&self) -> Result<()> {
self.rpc(MgsRequest::SendHostNmi)
.await
.and_then(expect_send_host_nmi_ack)
}
pub async fn set_ipcc_key_lookup_value(
&self,
key: u8,
data: Vec<u8>,
) -> Result<()> {
// We currently only support ipcc values that fit in a single packet;
// immediately fail if this one doesn't.
if data.len() > MIN_TRAILING_DATA_LEN {
return Err(CommunicationError::IpccKeyLookupValueTooLarge);
}
let (result, leftover_data) = rpc_with_trailing_data(
&self.cmds_tx,
MgsRequest::SetIpccKeyLookupValue { key },
Cursor::new(data),
)
.await;
// We checked that `data.len()` fits in one packet above, so we should
// never have any leftover data.
assert!(CursorExt::is_empty(&leftover_data));
result.and_then(expect_set_ipcc_key_lookup_value_ack)
}
/// Reads a single value from the SP's caboose (in the active slot)
///
/// This can eventually be deprecated in favor of
/// `read_component_caboose(SpComponent::SP_ITSELF, 0, key)`, once that
/// message is widely accepted by SPs in the field.
pub async fn get_caboose_value(&self, key: [u8; 4]) -> Result<Vec<u8>> {
let result =
rpc(&self.cmds_tx, MgsRequest::ReadCaboose { key }, None).await;
result.result.and_then(expect_caboose_value)
}
/// Instruct the SP that a reset_component_trigger will be coming with a
/// boot image selection policy setting.
///
/// This is part of a two-phase reset process. MGS should set a
/// `reset_component_prepare()` followed by `reset_component_trigger()`. Internally,
/// `reset_component_trigger()` continues to send the reset trigger message until the
/// SP responds with an error that it wasn't expecting it, at which point we
/// assume a reset has happened. In critical situations (e.g., updates),
/// callers should verify through a separate channel that the operation they
/// needed the reset for has happened (e.g., checking the SP's version, in
/// the case of updates).
pub async fn reset_component_prepare(
&self,
component: SpComponent,
) -> Result<()> {
self.rpc(MgsRequest::ResetComponentPrepare { component })
.await
.and_then(expect_reset_component_prepare_ack)
}
/// Instruct the SP to reset a component.
///
/// Only valid after a successful call to `reset_component_prepare()`.
///
/// If `disable_watchdog` is `true`, then any watchdogs associated with the
/// reset are disabled. Otherwise, watchdogs are enabled opportunistically
/// (depending on component and MGS protocol version).
pub async fn reset_component_trigger(
&self,
component: SpComponent,
disable_watchdog: bool,
) -> Result<()> {
// If the SP has an update pending, then try to use the watchdog reset
let mut use_watchdog = !disable_watchdog
&& matches!(
self.update_status(component).await?,
UpdateStatus::Complete(..)
);
if use_watchdog {
let response = self
.rpc(MgsRequest::ComponentWatchdogSupported { component })
.await;
match response {
Ok(v) => {
expect_component_watchdog_supported_ack(v)?;
}
Err(CommunicationError::SpError(
SpError::RequestUnsupportedForComponent,
)) => {
// If the component doesn't support the watchdog (i.e. it's
// not the SP itself), then that's fine and we'll disable
// the watchdog.
info!(
self.log,
"cannot use reset watchdog; \
not supported for {component}"
);
use_watchdog = false;
}
Err(CommunicationError::SpError(SpError::BadRequest(
BadRequestReason::WrongVersion { sp, .. },
))) if sp < WATCHDOG_VERSION => {
// If the SP firmware version is too old, then log an error
// message and fall back to the non-watchdog reset command
warn!(
self.log,
"cannot use reset watchdog; SP MGS version is too old"
);
use_watchdog = false;
}
Err(CommunicationError::SpError(SpError::Sprot(
SprotProtocolError::Deserialization,
))) => {
// If the RoT firmware version is too old, then it will fail
// to deserialize the message; then log an error message and
// fall back to the non-watchdog reset command
warn!(
self.log,
"cannot use reset watchdog; RoT firmware failed to \
deserialize message"
);
use_watchdog = false;
}
Err(e) => {
warn!(
self.log,
"unexpected error when checking for watchdog support: \
{e:?}"
);
return Err(e);
}
}
}
let reset_command = if use_watchdog {
// We'll set the watchdog timer to slightly longer than
// SP_RESET_TIME_ALLOWED; this means that if things fail, the
// watchdog will reset the SP **after** the MGS timeout expires, so
// we won't have a false-positive success in this function.
let time_ms =
u32::try_from(SP_RESET_TIME_ALLOWED.as_millis()).unwrap() * 3
/ 2;
info!(self.log, "using watchdog during reset");
MgsRequest::ResetComponentTriggerWithWatchdog { component, time_ms }
} else {
MgsRequest::ResetComponentTrigger { component }
};
// If we are resetting the SP itself, then reset trigger should
// retry until we get back an error indicating the
// SP wasn't expecting a reset trigger (because it has reset!).
//
// On Sidecar, we will instead get a message back indicating that the
// management network is locked (if we're updating the SP from a
// temporarily-unlocked tech port).
//
// If we are resetting the RoT, the SP will send an ack.
// When resetting the RoT, the SP SpRot client will either timeout on a
// response because the RoT was reset or because the message got
// dropped. TODO: have this code and/or SP check a boot nonce or other
// information to verify that the RoT did reset.
let response = self.rpc(reset_command).await;
let mut r = match response {
Ok((addr, response, data)) => {
if component == SpComponent::SP_ITSELF {
// Reset trigger should retry until we get back an error
// indicating the SP wasn't expecting a reset trigger
// (because it has reset!).
Err(CommunicationError::BadResponseType {
expected: "system-reset",
got: response.into(),
})
} else {
expect_reset_component_trigger_ack((addr, response, data))
}
}
Err(CommunicationError::SpError(
SpError::ResetComponentTriggerWithoutPrepare
| SpError::Monorail(MonorailError::ManagementNetworkLocked),
)) if component == SpComponent::SP_ITSELF => Ok(()),
Err(other) => Err(other),
};
// If the watchdog was set up, perform teardown and/or logging
if use_watchdog {
match r {
Ok(()) => {
// Reset completed successfully, so disable the watchdog
info!(self.log, "disabling watchdog");
r = self
.rpc(MgsRequest::DisableComponentWatchdog { component })
.await
.and_then(expect_disable_component_watchdog_ack);
if r.is_err() {
error!(
self.log,
"watchdog could not be disabled; \
the system may reboot momentarily!"
);
}
}
Err(CommunicationError::SpError(SpError::BadRequest(
BadRequestReason::WrongVersion { sp, .. },
))) if sp < WATCHDOG_VERSION => {
error!(
self.log,
"cannot disable watchdog (new image is too old); \
the system may reboot momentarily!"
);
}
Err(..) => {
warn!(
self.log,
"reset failed; watchdog may recover the system"
);
}
}
}
r
}
pub async fn component_action(
&self,
component: SpComponent,
action: ComponentAction,
) -> Result<()> {
self.rpc(MgsRequest::ComponentAction { component, action })
.await
.and_then(expect_component_action_ack)
}
pub async fn component_action_with_response(
&self,
component: SpComponent,
action: ComponentAction,
) -> Result<ComponentActionResponse> {
self.rpc(MgsRequest::ComponentAction { component, action })
.await
.and_then(expect_component_action)
}
pub async fn read_component_caboose(
&self,
component: SpComponent,
slot: u16,
key: [u8; 4],
) -> Result<Vec<u8>> {
let result = rpc(
&self.cmds_tx,
MgsRequest::ReadComponentCaboose { component, slot, key },
None,
)
.await;
result.result.and_then(expect_caboose_value)
}
pub async fn read_sensor_value(&self, id: u32) -> Result<SensorReading> {
let v = self
.rpc(MgsRequest::ReadSensor(SensorRequest {
kind: SensorRequestKind::LastReading,
id,
}))
.await
.and_then(expect_read_sensor)?;
match v {
SensorResponse::LastReading(r) => Ok(r),
other => Err(CommunicationError::BadResponseType {
expected: "last_reading",
got: other.into(),
}),
}
}
pub async fn read_rot_cmpa(&self) -> Result<[u8; ROT_PAGE_SIZE]> {
self.rpc(MgsRequest::ReadRot(RotRequest::ReadCmpa))
.await
.and_then(expect_read_rot)
}
pub async fn read_rot_active_cfpa(&self) -> Result<[u8; ROT_PAGE_SIZE]> {
self.rpc(MgsRequest::ReadRot(RotRequest::ReadCfpa(CfpaPage::Active)))
.await
.and_then(expect_read_rot)
}
pub async fn read_rot_inactive_cfpa(&self) -> Result<[u8; ROT_PAGE_SIZE]> {
self.rpc(MgsRequest::ReadRot(RotRequest::ReadCfpa(CfpaPage::Inactive)))
.await
.and_then(expect_read_rot)
}