-
Notifications
You must be signed in to change notification settings - Fork 40
/
http_entrypoints.rs
849 lines (719 loc) · 29.8 KB
/
http_entrypoints.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
// 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
//! HTTP entrypoint functions for the gateway service
use crate::error::SpCommsError;
use crate::http_err_with_message;
use crate::ServerContext;
use base64::Engine;
use dropshot::ApiDescription;
use dropshot::HttpError;
use dropshot::HttpResponseOk;
use dropshot::HttpResponseUpdatedNoContent;
use dropshot::Path;
use dropshot::Query;
use dropshot::RequestContext;
use dropshot::TypedBody;
use dropshot::UntypedBody;
use dropshot::WebsocketEndpointResult;
use dropshot::WebsocketUpgrade;
use futures::TryFutureExt;
use gateway_api::*;
use gateway_messages::RotBootInfo;
use gateway_messages::SpComponent;
use gateway_sp_comms::error::CommunicationError;
use gateway_sp_comms::HostPhase2Provider;
use gateway_sp_comms::VersionedSpState;
use gateway_types::caboose::SpComponentCaboose;
use gateway_types::component::PowerState;
use gateway_types::component::SpComponentFirmwareSlot;
use gateway_types::component::SpComponentInfo;
use gateway_types::component::SpComponentList;
use gateway_types::component::SpIdentifier;
use gateway_types::component::SpState;
use gateway_types::component_details::SpComponentDetails;
use gateway_types::host::HostStartupOptions;
use gateway_types::ignition::SpIgnitionInfo;
use gateway_types::rot::RotCfpa;
use gateway_types::rot::RotCfpaSlot;
use gateway_types::rot::RotCmpa;
use gateway_types::rot::RotState;
use gateway_types::sensor::SpSensorReading;
use gateway_types::update::HostPhase2Progress;
use gateway_types::update::HostPhase2RecoveryImageId;
use gateway_types::update::InstallinatorImageId;
use gateway_types::update::SpUpdateStatus;
use omicron_common::update::ArtifactHash;
use std::str;
use std::sync::Arc;
// TODO
// The gateway service will get asynchronous notifications both from directly
// SPs over the management network and indirectly from Ignition via the Sidecar
// SP.
// TODO The Ignition controller will send an interrupt to its local SP. Will
// that SP then notify both gateway services or just its local gateway service?
// Both Ignition controller should both do the same thing at about the same
// time so is there a real benefit to them both sending messages to both
// gateways? This would cause a single message to effectively be replicated 4x
// (Nexus would need to dedup these).
type GatewayApiDescription = ApiDescription<Arc<ServerContext>>;
/// Returns a description of the gateway API
pub fn api() -> GatewayApiDescription {
gateway_api_mod::api_description::<GatewayImpl>()
.expect("entrypoints registered successfully")
}
enum GatewayImpl {}
impl GatewayApi for GatewayImpl {
type Context = Arc<ServerContext>;
/// Get info on an SP
async fn sp_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseOk<SpState>, HttpError> {
let apictx = rqctx.context();
let sp_id = path.into_inner().sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let state = sp.state().await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
let rot_state = sp
.rot_state(gateway_messages::RotBootInfo::HIGHEST_KNOWN_VERSION)
.await;
let final_state = sp_state_from_comms(state, rot_state);
Ok(HttpResponseOk(final_state))
}
async fn sp_startup_options_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseOk<HostStartupOptions>, HttpError> {
let apictx = rqctx.context();
let mgmt_switch = &apictx.mgmt_switch;
let sp_id = path.into_inner().sp.into();
let sp = mgmt_switch.sp(sp_id)?;
let options = sp.get_startup_options().await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(options.into()))
}
async fn sp_startup_options_set(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
body: TypedBody<HostStartupOptions>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let mgmt_switch = &apictx.mgmt_switch;
let sp_id = path.into_inner().sp.into();
let sp = mgmt_switch.sp(sp_id)?;
sp.set_startup_options(body.into_inner().into()).await.map_err(
|err| SpCommsError::SpCommunicationFailed { sp: sp_id, err },
)?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_sensor_read_value(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpSensorId>,
) -> Result<HttpResponseOk<SpSensorReading>, HttpError> {
let apictx = rqctx.context();
let PathSpSensorId { sp, sensor_id } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let value = sp.read_sensor_value(sensor_id).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(value.into()))
}
async fn sp_component_list(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseOk<SpComponentList>, HttpError> {
let apictx = rqctx.context();
let sp_id = path.into_inner().sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let inventory = sp.inventory().await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(sp_component_list_from_comms(inventory)))
}
async fn sp_component_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseOk<Vec<SpComponentDetails>>, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
let details = sp.component_details(component).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(
details.entries.into_iter().map(Into::into).collect(),
))
}
// Implementation notes:
//
// 1. As of the time of this comment, the cannonical keys written to the hubris
// caboose are defined in https://github.com/oxidecomputer/hubtools; see
// `write_default_caboose()`.
// 2. We currently assume that the caboose always includes the same set of
// fields regardless of the component (e.g., the SP and RoT caboose have the
// same fields). If that becomes untrue, we may need to split this endpoint
// up to allow differently-typed responses.
async fn sp_component_caboose_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
query_params: Query<ComponentCabooseSlot>,
) -> Result<HttpResponseOk<SpComponentCaboose>, HttpError> {
const CABOOSE_KEY_GIT_COMMIT: [u8; 4] = *b"GITC";
const CABOOSE_KEY_BOARD: [u8; 4] = *b"BORD";
const CABOOSE_KEY_NAME: [u8; 4] = *b"NAME";
const CABOOSE_KEY_VERSION: [u8; 4] = *b"VERS";
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let ComponentCabooseSlot { firmware_slot } = query_params.into_inner();
let component = component_from_str(&component)?;
let from_utf8 = |key: &[u8], bytes| {
// This helper closure is only called with the ascii-printable [u8; 4]
// key constants we define above, so we can unwrap this conversion.
let key = str::from_utf8(key).unwrap();
String::from_utf8(bytes).map_err(|_| {
http_err_with_message(
http::StatusCode::SERVICE_UNAVAILABLE,
"InvalidCaboose",
format!("non-utf8 data returned for caboose key {key}"),
)
})
};
let git_commit =
sp.read_component_caboose(
component,
firmware_slot,
CABOOSE_KEY_GIT_COMMIT,
)
.await
.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
let board = sp
.read_component_caboose(component, firmware_slot, CABOOSE_KEY_BOARD)
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
let name = sp
.read_component_caboose(component, firmware_slot, CABOOSE_KEY_NAME)
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
let version =
sp.read_component_caboose(
component,
firmware_slot,
CABOOSE_KEY_VERSION,
)
.await
.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
let git_commit = from_utf8(&CABOOSE_KEY_GIT_COMMIT, git_commit)?;
let board = from_utf8(&CABOOSE_KEY_BOARD, board)?;
let name = from_utf8(&CABOOSE_KEY_NAME, name)?;
let version = from_utf8(&CABOOSE_KEY_VERSION, version)?;
let caboose = SpComponentCaboose { git_commit, board, name, version };
Ok(HttpResponseOk(caboose))
}
async fn sp_component_clear_status(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
sp.component_clear_status(component).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_component_active_slot_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseOk<SpComponentFirmwareSlot>, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
let slot =
sp.component_active_slot(component).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(SpComponentFirmwareSlot { slot }))
}
async fn sp_component_active_slot_set(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
query_params: Query<SetComponentActiveSlotParams>,
body: TypedBody<SpComponentFirmwareSlot>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
let slot = body.into_inner().slot;
let persist = query_params.into_inner().persist;
sp.set_component_active_slot(component, slot, persist).await.map_err(
|err| SpCommsError::SpCommunicationFailed { sp: sp_id, err },
)?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_component_serial_console_attach(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
websocket: WebsocketUpgrade,
) -> WebsocketEndpointResult {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let component = component_from_str(&component)?;
// Ensure we can attach to this SP's serial console.
let console = apictx
.mgmt_switch
.sp(sp_id)?
.serial_console_attach(component)
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
let log = apictx.log.new(slog::o!("sp" => format!("{sp:?}")));
// We've successfully attached to the SP's serial console: upgrade the
// websocket and run our side of that connection.
websocket.handle(move |conn| {
crate::serial_console::run(sp_id, console, conn, log)
})
}
async fn sp_component_serial_console_detach(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
// TODO-cleanup: "component" support for the serial console is half baked;
// we don't use it at all to detach.
let PathSpComponent { sp, component: _ } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
sp.serial_console_detach().await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_component_reset(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
sp.reset_component_prepare(component)
// We always want to run with the watchdog when resetting as
// disabling the watchdog should be considered a debug only feature
.and_then(|()| sp.reset_component_trigger(component, false))
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_component_update(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
query_params: Query<ComponentUpdateIdSlot>,
body: UntypedBody,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
let ComponentUpdateIdSlot { id, firmware_slot } =
query_params.into_inner();
// TODO-performance: this makes a full copy of the uploaded data
let image = body.as_bytes().to_vec();
sp.start_update(component, id, firmware_slot, image)
.await
.map_err(|err| SpCommsError::UpdateFailed { sp: sp_id, err })?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_component_update_status(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseOk<SpUpdateStatus>, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
let status = sp.update_status(component).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(status.into()))
}
async fn sp_component_update_abort(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
body: TypedBody<UpdateAbortBody>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let component = component_from_str(&component)?;
let UpdateAbortBody { id } = body.into_inner();
sp.update_abort(component, id).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_rot_cmpa_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
) -> Result<HttpResponseOk<RotCmpa>, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let sp_id = sp.into();
// Ensure the caller knows they're asking for the RoT
if component_from_str(&component)? != SpComponent::ROT {
return Err(HttpError::for_bad_request(
Some("RequestUnsupportedForComponent".to_string()),
"Only the RoT has a CFPA".into(),
));
}
let sp = apictx.mgmt_switch.sp(sp_id)?;
let data = sp.read_rot_cmpa().await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
let base64_data =
base64::engine::general_purpose::STANDARD.encode(data);
Ok(HttpResponseOk(RotCmpa { base64_data }))
}
async fn sp_rot_cfpa_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
params: TypedBody<GetCfpaParams>,
) -> Result<HttpResponseOk<RotCfpa>, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let GetCfpaParams { slot } = params.into_inner();
let sp_id = sp.into();
// Ensure the caller knows they're asking for the RoT
if component_from_str(&component)? != SpComponent::ROT {
return Err(HttpError::for_bad_request(
Some("RequestUnsupportedForComponent".to_string()),
"Only the RoT has a CFPA".into(),
));
}
let sp = apictx.mgmt_switch.sp(sp_id)?;
let data = match slot {
RotCfpaSlot::Active => sp.read_rot_active_cfpa().await,
RotCfpaSlot::Inactive => sp.read_rot_inactive_cfpa().await,
RotCfpaSlot::Scratch => sp.read_rot_scratch_cfpa().await,
}
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
let base64_data =
base64::engine::general_purpose::STANDARD.encode(data);
Ok(HttpResponseOk(RotCfpa { base64_data, slot }))
}
async fn sp_rot_boot_info(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpComponent>,
params: TypedBody<GetRotBootInfoParams>,
) -> Result<HttpResponseOk<RotState>, HttpError> {
let apictx = rqctx.context();
let PathSpComponent { sp, component } = path.into_inner();
let GetRotBootInfoParams { version } = params.into_inner();
let sp_id = sp.into();
// Ensure the caller knows they're asking for the RoT
if component_from_str(&component)? != SpComponent::ROT {
return Err(HttpError::for_bad_request(
Some("RequestUnsupportedForComponent".to_string()),
"rot_boot_info only makes sent for a RoT".into(),
));
}
let sp = apictx.mgmt_switch.sp(sp_id)?;
let state = sp.rot_state(version).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(state.into()))
}
async fn ignition_list(
rqctx: RequestContext<Self::Context>,
) -> Result<HttpResponseOk<Vec<SpIgnitionInfo>>, HttpError> {
let apictx = rqctx.context();
let mgmt_switch = &apictx.mgmt_switch;
let out = mgmt_switch
.bulk_ignition_state()
.await?
.map(|(id, state)| SpIgnitionInfo {
id: id.into(),
details: state.into(),
})
.collect();
Ok(HttpResponseOk(out))
}
async fn ignition_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseOk<SpIgnitionInfo>, HttpError> {
let apictx = rqctx.context();
let mgmt_switch = &apictx.mgmt_switch;
let sp_id = path.into_inner().sp.into();
let ignition_target = mgmt_switch.ignition_target(sp_id)?;
let state = mgmt_switch
.ignition_controller()
.ignition_state(ignition_target)
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
let info = SpIgnitionInfo { id: sp_id.into(), details: state.into() };
Ok(HttpResponseOk(info))
}
async fn ignition_command(
rqctx: RequestContext<Self::Context>,
path: Path<PathSpIgnitionCommand>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let mgmt_switch = &apictx.mgmt_switch;
let PathSpIgnitionCommand { sp, command } = path.into_inner();
let sp_id = sp.into();
let ignition_target = mgmt_switch.ignition_target(sp_id)?;
mgmt_switch
.ignition_controller()
.ignition_command(ignition_target, command.into())
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_power_state_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseOk<PowerState>, HttpError> {
let apictx = rqctx.context();
let sp_id = path.into_inner().sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let power_state = sp.power_state().await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseOk(power_state.into()))
}
async fn sp_power_state_set(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
body: TypedBody<PowerState>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let sp_id = path.into_inner().sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let power_state = body.into_inner();
sp.set_power_state(power_state.into()).await.map_err(|err| {
SpCommsError::SpCommunicationFailed { sp: sp_id, err }
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_installinator_image_id_set(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
body: TypedBody<InstallinatorImageId>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
use ipcc::Key;
let apictx = rqctx.context();
let sp_id = path.into_inner().sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
let image_id = ipcc::InstallinatorImageId::from(body.into_inner());
sp.set_ipcc_key_lookup_value(
Key::InstallinatorImageId as u8,
image_id.serialize(),
)
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_installinator_image_id_delete(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
use ipcc::Key;
let apictx = rqctx.context();
let sp_id = path.into_inner().sp.into();
let sp = apictx.mgmt_switch.sp(sp_id)?;
// We clear the image ID by setting it to a 0-length vec.
sp.set_ipcc_key_lookup_value(
Key::InstallinatorImageId as u8,
Vec::new(),
)
.await
.map_err(|err| SpCommsError::SpCommunicationFailed {
sp: sp_id,
err,
})?;
Ok(HttpResponseUpdatedNoContent {})
}
async fn sp_host_phase2_progress_get(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseOk<HostPhase2Progress>, HttpError> {
let apictx = rqctx.context();
let sp = apictx.mgmt_switch.sp(path.into_inner().sp.into())?;
let Some(progress) = sp.most_recent_host_phase2_request().await else {
return Ok(HttpResponseOk(HostPhase2Progress::None));
};
// Our `host_phase2_provider` is using an in-memory cache, so the only way
// we can fail to get the total size is if we no longer have the image that
// this SP most recently requested. We'll treat that as "no progress
// information", since it almost certainly means our progress info on this
// SP is very stale.
let Ok(total_size) =
apictx.host_phase2_provider.total_size(progress.hash).await
else {
return Ok(HttpResponseOk(HostPhase2Progress::None));
};
let image_id = HostPhase2RecoveryImageId {
sha256_hash: ArtifactHash(progress.hash),
};
// `progress` tells us the offset the SP requested and the amount of data we
// sent starting at that offset; report the end of that chunk to our caller.
let offset = progress.offset.saturating_add(progress.data_sent);
Ok(HttpResponseOk(HostPhase2Progress::Available {
image_id,
offset,
total_size,
age: progress.received.elapsed(),
}))
}
async fn sp_host_phase2_progress_delete(
rqctx: RequestContext<Self::Context>,
path: Path<PathSp>,
) -> Result<HttpResponseUpdatedNoContent, HttpError> {
let apictx = rqctx.context();
let sp = apictx.mgmt_switch.sp(path.into_inner().sp.into())?;
sp.clear_most_recent_host_phase2_request().await;
Ok(HttpResponseUpdatedNoContent {})
}
async fn recovery_host_phase2_upload(
rqctx: RequestContext<Self::Context>,
body: UntypedBody,
) -> Result<HttpResponseOk<HostPhase2RecoveryImageId>, HttpError> {
let apictx = rqctx.context();
// TODO: this makes a full copy of the host image, potentially unnecessarily
// if it's malformed.
let image = body.as_bytes().to_vec();
let sha256_hash =
apictx.host_phase2_provider.insert(image).await.map_err(|err| {
// Any cache-insertion failure indicates a malformed image; map them
// to bad requests.
HttpError::for_bad_request(
Some("BadHostPhase2Image".to_string()),
err.to_string(),
)
})?;
let sha256_hash = ArtifactHash(sha256_hash);
Ok(HttpResponseOk(HostPhase2RecoveryImageId { sha256_hash }))
}
async fn sp_local_switch_id(
rqctx: RequestContext<Self::Context>,
) -> Result<HttpResponseOk<SpIdentifier>, HttpError> {
let apictx = rqctx.context();
let id = apictx.mgmt_switch.local_switch()?;
Ok(HttpResponseOk(id.into()))
}
async fn sp_all_ids(
rqctx: RequestContext<Self::Context>,
) -> Result<HttpResponseOk<Vec<SpIdentifier>>, HttpError> {
let apictx = rqctx.context();
let all_ids =
apictx.mgmt_switch.all_sps()?.map(|(id, _)| id.into()).collect();
Ok(HttpResponseOk(all_ids))
}
}
// wrap `SpComponent::try_from(&str)` into a usable form for dropshot endpoints
fn component_from_str(s: &str) -> Result<SpComponent, HttpError> {
SpComponent::try_from(s).map_err(|_| {
HttpError::for_bad_request(
Some("InvalidSpComponent".to_string()),
"invalid SP component name".to_string(),
)
})
}
// The _from_comms functions are here rather than `From` impls in gateway-types
// so that gateway-types avoids a dependency on gateway-sp-comms.
fn sp_state_from_comms(
sp_state: VersionedSpState,
rot_state: Result<RotBootInfo, CommunicationError>,
) -> SpState {
// We need to keep this backwards compatible. If we get an error from reading `rot_state`
// it could be because the RoT/SP isn't updated or because we have failed for some
// other reason. If we're on V1/V2 SP info and we fail, just fall back to using the
// RoT info in that struct since any error will also be communicated there.
match (sp_state, rot_state) {
(VersionedSpState::V1(s), Err(_)) => SpState::from(s),
(VersionedSpState::V1(s), Ok(r)) => {
SpState::from((s, RotState::from(r)))
}
(VersionedSpState::V2(s), Err(_)) => SpState::from(s),
(VersionedSpState::V2(s), Ok(r)) => {
SpState::from((s, RotState::from(r)))
}
(VersionedSpState::V3(s), Ok(r)) => {
SpState::from((s, RotState::from(r)))
}
(VersionedSpState::V3(s), Err(err)) => SpState::from((
s,
RotState::CommunicationFailed { message: err.to_string() },
)),
}
}
fn sp_component_list_from_comms(
inv: gateway_sp_comms::SpInventory,
) -> SpComponentList {
SpComponentList {
components: inv
.devices
.into_iter()
.map(sp_component_info_from_comms)
.collect(),
}
}
fn sp_component_info_from_comms(
dev: gateway_sp_comms::SpDevice,
) -> SpComponentInfo {
SpComponentInfo {
component: dev.component.as_str().unwrap_or("???").to_string(),
device: dev.device,
serial_number: None, // TODO populate when SP provides it
description: dev.description,
capabilities: dev.capabilities.bits(),
presence: dev.presence.into(),
}
}