-
Notifications
You must be signed in to change notification settings - Fork 39
/
mod.rs
2168 lines (1974 loc) · 70.4 KB
/
mod.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/.
//! Data structures and related facilities for representing resources in the API
//!
//! This includes all representations over the wire for both the external and
//! internal APIs. The contents here are all HTTP-agnostic.
mod error;
pub mod http_pagination;
pub use error::*;
use anyhow::anyhow;
use anyhow::Context;
use api_identity::ObjectIdentity;
use chrono::DateTime;
use chrono::Utc;
pub use dropshot::PaginationOrder;
use futures::future::ready;
use futures::stream::BoxStream;
use futures::stream::StreamExt;
use parse_display::Display;
use parse_display::FromStr;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FormatResult;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::num::{NonZeroU16, NonZeroU32};
use std::str::FromStr;
use uuid::Uuid;
// The type aliases below exist primarily to ensure consistency among return
// types for functions in the `nexus::Nexus` and `nexus::DataStore`. The
// type argument `T` generally implements `Object`.
/// Result of a create operation for the specified type
pub type CreateResult<T> = Result<T, Error>;
/// Result of a delete operation for the specified type
pub type DeleteResult = Result<(), Error>;
/// Result of a list operation that returns an ObjectStream
pub type ListResult<T> = Result<ObjectStream<T>, Error>;
/// Result of a list operation that returns a vector
pub type ListResultVec<T> = Result<Vec<T>, Error>;
/// Result of a lookup operation for the specified type
pub type LookupResult<T> = Result<T, Error>;
/// Result of an update operation for the specified type
pub type UpdateResult<T> = Result<T, Error>;
/// A stream of Results, each potentially representing an object in the API
pub type ObjectStream<T> = BoxStream<'static, Result<T, Error>>;
// General-purpose types used for client request parameters and return values.
/// Describes an `Object` that has its own identity metadata. This is
/// currently used only for pagination.
pub trait ObjectIdentity {
fn identity(&self) -> &IdentityMetadata;
}
/// Parameters used to request a specific page of results when listing a
/// collection of objects
///
/// This is logically analogous to Dropshot's `PageSelector` (plus the limit from
/// Dropshot's `PaginationParams). However, this type is HTTP-agnostic. More
/// importantly, by the time this struct is generated, we know the type of the
/// sort field and we can specialize `DataPageParams` to that type. This makes
/// it considerably simpler to implement the backend for most of our paginated
/// APIs.
///
/// `NameType` is the type of the field used to sort the returned values and it's
/// usually `Name`.
#[derive(Debug)]
pub struct DataPageParams<'a, NameType> {
/// If present, this is the value of the sort field for the last object seen
pub marker: Option<&'a NameType>,
/// Whether the sort is in ascending order
pub direction: PaginationOrder,
/// This identifies how many results should be returned on this page.
/// Backend implementations must provide this many results unless we're at
/// the end of the scan. Dropshot assumes that if we provide fewer results
/// than this number, then we're done with the scan.
pub limit: NonZeroU32,
}
impl<'a, NameType> DataPageParams<'a, NameType> {
/// Maps the marker type to a new type.
///
/// Equivalent to [std::option::Option::map], because that's what it calls.
pub fn map_name<OtherName, F>(&self, f: F) -> DataPageParams<'a, OtherName>
where
F: FnOnce(&'a NameType) -> &'a OtherName,
{
DataPageParams {
marker: self.marker.map(f),
direction: self.direction,
limit: self.limit,
}
}
}
/// A name used in the API
///
/// Names are generally user-provided unique identifiers, highly constrained as
/// described in RFD 4. An `Name` can only be constructed with a string
/// that's valid as a name.
#[derive(
Clone,
Debug,
Deserialize,
Display,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
#[display("{0}")]
#[serde(try_from = "String")]
pub struct Name(String);
/// `Name::try_from(String)` is the primary method for constructing an Name
/// from an input string. This validates the string according to our
/// requirements for a name.
/// TODO-cleanup why shouldn't callers use TryFrom<&str>?
impl TryFrom<String> for Name {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.len() > 63 {
return Err(String::from("name may contain at most 63 characters"));
}
let mut iter = value.chars();
let first = iter.next().ok_or_else(|| {
String::from("name requires at least one character")
})?;
if !first.is_ascii_lowercase() {
return Err(String::from(
"name must begin with an ASCII lowercase character",
));
}
let mut last = first;
for c in iter {
last = c;
if !c.is_ascii_lowercase() && !c.is_digit(10) && c != '-' {
return Err(format!(
"name contains invalid character: \"{}\" (allowed \
characters are lowercase ASCII, digits, and \"-\")",
c
));
}
}
if last == '-' {
return Err(String::from("name cannot end with \"-\""));
}
Ok(Name(value))
}
}
impl FromStr for Name {
// TODO: We should have better error types here.
// See https://github.com/oxidecomputer/omicron/issues/347
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Name::try_from(String::from(value))
}
}
impl<'a> From<&'a Name> for &'a str {
fn from(n: &'a Name) -> Self {
n.as_str()
}
}
/// `Name` instances are comparable like Strings, primarily so that they can
/// be used as keys in trees.
impl<S> PartialEq<S> for Name
where
S: AsRef<str>,
{
fn eq(&self, other: &S) -> bool {
self.0 == other.as_ref()
}
}
/// Custom JsonSchema implementation to encode the constraints on Name
// TODO: 1. make this part of schemars w/ rename and maxlen annotations
// TODO: 2. integrate the regex with `try_from`
impl JsonSchema for Name {
fn schema_name() -> String {
"Name".to_string()
}
fn json_schema(
_gen: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
schemars::schema::Schema::Object(schemars::schema::SchemaObject {
metadata: Some(Box::new(schemars::schema::Metadata {
id: None,
title: Some("A name used in the API".to_string()),
description: Some(
"Names must begin with a lower case ASCII letter, be \
composed exclusively of lowercase ASCII, uppercase \
ASCII, numbers, and '-', and may not end with a '-'."
.to_string(),
),
default: None,
deprecated: false,
read_only: false,
write_only: false,
examples: vec![],
})),
instance_type: Some(schemars::schema::SingleOrVec::Single(
Box::new(schemars::schema::InstanceType::String),
)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: Some(Box::new(schemars::schema::StringValidation {
max_length: Some(63),
min_length: None,
pattern: Some("[a-z](|[a-zA-Z0-9-]*[a-zA-Z0-9])".to_string()),
})),
array: None,
object: None,
reference: None,
extensions: BTreeMap::new(),
})
}
}
impl Name {
/// Parse an `Name`. This is a convenience wrapper around
/// `Name::try_from(String)` that marshals any error into an appropriate
/// `Error`.
pub fn from_param(value: String, label: &str) -> Result<Name, Error> {
value.parse().map_err(|e| Error::InvalidValue {
label: String::from(label),
message: e,
})
}
/// Return the `&str` representing the actual name.
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
/// Name for a built-in role
#[derive(
Clone,
Debug,
DeserializeFromStr,
Display,
Eq,
FromStr,
Ord,
PartialEq,
PartialOrd,
SerializeDisplay,
)]
#[display("{resource_type}.{role_name}")]
pub struct RoleName {
// "resource_type" is generally the String value of one of the
// `ResourceType` variants. We could store the parsed `ResourceType`
// instead, but it's useful to be able to represent RoleNames for resource
// types that we don't know about. That could happen if we happen to find
// them in the database, for example.
#[from_str(regex = "[a-z-]+")]
resource_type: String,
#[from_str(regex = "[a-z-]+")]
role_name: String,
}
impl RoleName {
pub fn new(resource_type: &str, role_name: &str) -> RoleName {
RoleName {
resource_type: String::from(resource_type),
role_name: String::from(role_name),
}
}
}
/// Custom JsonSchema implementation to encode the constraints on Name
// TODO see TODOs on Name above
impl JsonSchema for RoleName {
fn schema_name() -> String {
"RoleName".to_string()
}
fn json_schema(
_gen: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
schemars::schema::Schema::Object(schemars::schema::SchemaObject {
metadata: Some(Box::new(schemars::schema::Metadata {
id: None,
title: Some("A name for a built-in role".to_string()),
description: Some(
"Role names consist of two string components \
separated by dot (\".\")."
.to_string(),
),
default: None,
deprecated: false,
read_only: false,
write_only: false,
examples: vec![],
})),
instance_type: Some(schemars::schema::SingleOrVec::Single(
Box::new(schemars::schema::InstanceType::String),
)),
format: None,
enum_values: None,
const_value: None,
subschemas: None,
number: None,
string: Some(Box::new(schemars::schema::StringValidation {
max_length: Some(63),
min_length: None,
pattern: Some("[a-z-]+\\.[a-z-]+".to_string()),
})),
array: None,
object: None,
reference: None,
extensions: BTreeMap::new(),
})
}
}
/// A count of bytes, typically used either for memory or storage capacity
///
/// The maximum supported byte count is [`i64::MAX`]. This makes it somewhat
/// inconvenient to define constructors: a u32 constructor can be infallible, but
/// an i64 constructor can fail (if the value is negative) and a u64 constructor
/// can fail (if the value is larger than i64::MAX). We provide all of these for
/// consumers' convenience.
// TODO-cleanup This could benefit from a more complete implementation.
// TODO-correctness RFD 4 requires that this be a multiple of 256 MiB. We'll
// need to write a validator for that.
// /
//
// The maximum byte count of i64::MAX comes from the fact that this is stored in
// the database as an i64. Constraining it here ensures that we can't fail to
// serialize the value.
#[derive(Copy, Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq)]
pub struct ByteCount(u64);
impl ByteCount {
pub fn from_kibibytes_u32(kibibytes: u32) -> ByteCount {
ByteCount::try_from(1024 * u64::from(kibibytes)).unwrap()
}
pub fn from_mebibytes_u32(mebibytes: u32) -> ByteCount {
ByteCount::try_from(1024 * 1024 * u64::from(mebibytes)).unwrap()
}
pub fn from_gibibytes_u32(gibibytes: u32) -> ByteCount {
ByteCount::try_from(1024 * 1024 * 1024 * u64::from(gibibytes)).unwrap()
}
pub fn to_bytes(&self) -> u64 {
self.0
}
pub fn to_whole_kibibytes(&self) -> u64 {
self.to_bytes() / 1024
}
pub fn to_whole_mebibytes(&self) -> u64 {
self.to_bytes() / 1024 / 1024
}
pub fn to_whole_gibibytes(&self) -> u64 {
self.to_bytes() / 1024 / 1024 / 1024
}
pub fn to_whole_tebibytes(&self) -> u64 {
self.to_bytes() / 1024 / 1024 / 1024 / 1024
}
}
// TODO-cleanup This could use the experimental std::num::IntErrorKind.
#[derive(Debug, Eq, thiserror::Error, Ord, PartialEq, PartialOrd)]
pub enum ByteCountRangeError {
#[error("value is too small for a byte count")]
TooSmall,
#[error("value is too large for a byte count")]
TooLarge,
}
impl TryFrom<u64> for ByteCount {
type Error = ByteCountRangeError;
fn try_from(bytes: u64) -> Result<Self, Self::Error> {
if i64::try_from(bytes).is_err() {
Err(ByteCountRangeError::TooLarge)
} else {
Ok(ByteCount(bytes))
}
}
}
impl TryFrom<i64> for ByteCount {
type Error = ByteCountRangeError;
fn try_from(bytes: i64) -> Result<Self, Self::Error> {
Ok(ByteCount(
u64::try_from(bytes).map_err(|_| ByteCountRangeError::TooSmall)?,
))
}
}
impl From<u32> for ByteCount {
fn from(value: u32) -> Self {
ByteCount(u64::from(value))
}
}
impl From<ByteCount> for i64 {
fn from(b: ByteCount) -> Self {
// We have already validated that this value is in range.
i64::try_from(b.0).unwrap()
}
}
/// Generation numbers stored in the database, used for optimistic concurrency
/// control
// Because generation numbers are stored in the database, we represent them as
// i64.
#[derive(
Copy,
Clone,
Debug,
Deserialize,
Eq,
JsonSchema,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
pub struct Generation(u64);
impl Generation {
pub fn new() -> Generation {
Generation(1)
}
pub fn next(&self) -> Generation {
// It should technically be an operational error if this wraps or even
// exceeds the value allowed by an i64. But it seems unlikely enough to
// happen in practice that we can probably feel safe with this.
let next_gen = self.0 + 1;
assert!(next_gen <= u64::try_from(i64::MAX).unwrap());
Generation(next_gen)
}
}
impl Display for Generation {
fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult {
f.write_str(&self.0.to_string())
}
}
impl From<&Generation> for i64 {
fn from(g: &Generation) -> Self {
// We have already validated that the value is within range.
// TODO-robustness We need to ensure that we don't deserialize a value
// out of range here.
i64::try_from(g.0).unwrap()
}
}
impl TryFrom<i64> for Generation {
type Error = anyhow::Error;
fn try_from(value: i64) -> Result<Self, Self::Error> {
Ok(Generation(
u64::try_from(value)
.map_err(|_| anyhow!("generation number too large"))?,
))
}
}
// General types used to implement API resources
/// Identifies a type of API resource
#[derive(
Clone,
Copy,
Debug,
DeserializeFromStr,
Display,
Eq,
FromStr,
Ord,
PartialEq,
PartialOrd,
SerializeDisplay,
)]
#[display(style = "kebab-case")]
pub enum ResourceType {
Fleet,
Silo,
SiloUser,
ConsoleSession,
Organization,
Project,
Dataset,
Disk,
Instance,
NetworkInterface,
Rack,
Sled,
SagaDbg,
Volume,
Vpc,
VpcFirewallRule,
VpcSubnet,
VpcRouter,
RouterRoute,
Oximeter,
MetricProducer,
Role,
User,
Zpool,
}
pub async fn to_list<T, U>(object_stream: ObjectStream<T>) -> Vec<U>
where
T: Into<U>,
{
object_stream
.filter(|maybe_object| ready(maybe_object.is_ok()))
.map(|maybe_object| maybe_object.unwrap().into())
.collect::<Vec<U>>()
.await
}
// IDENTITY METADATA
/// Identity-related metadata that's included in nearly all public API objects
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct IdentityMetadata {
/// unique, immutable, system-controlled identifier for each resource
pub id: Uuid,
/// unique, mutable, user-controlled identifier for each resource
pub name: Name,
/// human-readable free-form text about a resource
pub description: String,
/// timestamp when this resource was created
pub time_created: DateTime<Utc>,
/// timestamp when this resource was last modified
pub time_modified: DateTime<Utc>,
}
/// Create-time identity-related parameters
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct IdentityMetadataCreateParams {
pub name: Name,
pub description: String,
}
/// Updateable identity-related parameters
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct IdentityMetadataUpdateParams {
pub name: Option<Name>,
pub description: Option<String>,
}
// Specific API resources
// INSTANCES
/// Running state of an Instance (primarily: booted or stopped)
///
/// This typically reflects whether it's starting, running, stopping, or stopped,
/// but also includes states related to the Instance's lifecycle
#[derive(
Copy,
Clone,
Debug,
Deserialize,
Eq,
Ord,
PartialEq,
PartialOrd,
Serialize,
JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum InstanceState {
Creating, // TODO-polish: paper over Creating in the API with Starting?
Starting,
Running,
/// Implied that a transition to "Stopped" is imminent.
Stopping,
/// The instance is currently stopped.
Stopped,
/// The instance is in the process of rebooting - it will remain
/// in the "rebooting" state until the VM is starting once more.
Rebooting,
/// The instance is in the process of migrating - it will remain
/// in the "migrating" state until the migration process is complete
/// and the destination propolis is ready to continue execution.
Migrating,
Repairing,
Failed,
Destroyed,
}
impl Display for InstanceState {
fn fmt(&self, f: &mut Formatter) -> FormatResult {
write!(f, "{}", self.label())
}
}
// TODO-cleanup why is this error type different from the one for Name? The
// reason is probably that Name can be provided by the user, so we want a
// good validation error. InstanceState cannot. Still, is there a way to
// unify these?
impl TryFrom<&str> for InstanceState {
type Error = String;
fn try_from(variant: &str) -> Result<Self, Self::Error> {
let r = match variant {
"creating" => InstanceState::Creating,
"starting" => InstanceState::Starting,
"running" => InstanceState::Running,
"stopping" => InstanceState::Stopping,
"stopped" => InstanceState::Stopped,
"rebooting" => InstanceState::Rebooting,
"migrating" => InstanceState::Migrating,
"repairing" => InstanceState::Repairing,
"failed" => InstanceState::Failed,
"destroyed" => InstanceState::Destroyed,
_ => return Err(format!("Unexpected variant {}", variant)),
};
Ok(r)
}
}
impl InstanceState {
pub fn label(&self) -> &'static str {
match self {
InstanceState::Creating => "creating",
InstanceState::Starting => "starting",
InstanceState::Running => "running",
InstanceState::Stopping => "stopping",
InstanceState::Stopped => "stopped",
InstanceState::Rebooting => "rebooting",
InstanceState::Migrating => "migrating",
InstanceState::Repairing => "repairing",
InstanceState::Failed => "failed",
InstanceState::Destroyed => "destroyed",
}
}
/// Returns true if the given state represents a fully stopped Instance.
/// This means that a transition from an !is_stopped() state must go
/// through Stopping.
pub fn is_stopped(&self) -> bool {
match self {
InstanceState::Starting => false,
InstanceState::Running => false,
InstanceState::Stopping => false,
InstanceState::Rebooting => false,
InstanceState::Migrating => false,
InstanceState::Creating => true,
InstanceState::Stopped => true,
InstanceState::Repairing => true,
InstanceState::Failed => true,
InstanceState::Destroyed => true,
}
}
}
/// The number of CPUs in an Instance
#[derive(Copy, Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct InstanceCpuCount(pub u16);
impl TryFrom<i64> for InstanceCpuCount {
type Error = anyhow::Error;
fn try_from(value: i64) -> Result<Self, Self::Error> {
Ok(InstanceCpuCount(u16::try_from(value).context("parsing CPU count")?))
}
}
impl From<&InstanceCpuCount> for i64 {
fn from(c: &InstanceCpuCount) -> Self {
i64::from(c.0)
}
}
/// Client view of an [`InstanceRuntimeState`]
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct InstanceRuntimeState {
pub run_state: InstanceState,
pub time_run_state_updated: DateTime<Utc>,
}
impl From<crate::api::internal::nexus::InstanceRuntimeState>
for InstanceRuntimeState
{
fn from(state: crate::api::internal::nexus::InstanceRuntimeState) -> Self {
InstanceRuntimeState {
run_state: state.run_state,
time_run_state_updated: state.time_updated,
}
}
}
/// Client view of an [`Instance`]
#[derive(ObjectIdentity, Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct Instance {
// TODO is flattening here the intent in RFD 4?
#[serde(flatten)]
pub identity: IdentityMetadata,
/// id for the project containing this Instance
pub project_id: Uuid,
/// number of CPUs allocated for this Instance
pub ncpus: InstanceCpuCount,
/// memory allocated for this Instance
pub memory: ByteCount,
/// RFC1035-compliant hostname for the Instance.
pub hostname: String, // TODO-cleanup different type?
#[serde(flatten)]
pub runtime: InstanceRuntimeState,
}
// DISKS
/// Client view of an [`Disk`]
#[derive(ObjectIdentity, Clone, Debug, Deserialize, Serialize, JsonSchema)]
pub struct Disk {
#[serde(flatten)]
pub identity: IdentityMetadata,
pub project_id: Uuid,
pub snapshot_id: Option<Uuid>,
pub size: ByteCount,
pub state: DiskState,
pub device_path: String,
}
/// State of a Disk (primarily: attached or not)
#[derive(
Clone,
Debug,
Deserialize,
Eq,
Ord,
PartialEq,
PartialOrd,
Serialize,
JsonSchema,
)]
#[serde(tag = "state", content = "instance", rename_all = "snake_case")]
pub enum DiskState {
/// Disk is being initialized
Creating,
/// Disk is ready but detached from any Instance
Detached,
/// Disk is being attached to the given Instance
Attaching(Uuid), // attached Instance id
/// Disk is attached to the given Instance
Attached(Uuid), // attached Instance id
/// Disk is being detached from the given Instance
Detaching(Uuid), // attached Instance id
/// Disk has been destroyed
Destroyed,
/// Disk is unavailable
Faulted,
}
impl Display for DiskState {
fn fmt(&self, f: &mut Formatter) -> FormatResult {
write!(f, "{}", self.label())
}
}
impl TryFrom<(&str, Option<Uuid>)> for DiskState {
type Error = String;
fn try_from(
(s, maybe_id): (&str, Option<Uuid>),
) -> Result<Self, Self::Error> {
match (s, maybe_id) {
("creating", None) => Ok(DiskState::Creating),
("detached", None) => Ok(DiskState::Detached),
("destroyed", None) => Ok(DiskState::Destroyed),
("faulted", None) => Ok(DiskState::Faulted),
("attaching", Some(id)) => Ok(DiskState::Attaching(id)),
("attached", Some(id)) => Ok(DiskState::Attached(id)),
("detaching", Some(id)) => Ok(DiskState::Detaching(id)),
_ => Err(format!(
"unexpected value for disk state: {:?} with attached id {:?}",
s, maybe_id
)),
}
}
}
impl DiskState {
/// Returns the string label for this disk state
pub fn label(&self) -> &'static str {
match self {
DiskState::Creating => "creating",
DiskState::Detached => "detached",
DiskState::Attaching(_) => "attaching",
DiskState::Attached(_) => "attached",
DiskState::Detaching(_) => "detaching",
DiskState::Destroyed => "destroyed",
DiskState::Faulted => "faulted",
}
}
/// Returns whether the Disk is currently attached to, being attached to, or
/// being detached from any Instance.
pub fn is_attached(&self) -> bool {
self.attached_instance_id().is_some()
}
/// If the Disk is attached to, being attached to, or being detached from an
/// Instance, returns the id for that Instance. Otherwise returns `None`.
pub fn attached_instance_id(&self) -> Option<&Uuid> {
match self {
DiskState::Attaching(id) => Some(id),
DiskState::Attached(id) => Some(id),
DiskState::Detaching(id) => Some(id),
DiskState::Creating => None,
DiskState::Detached => None,
DiskState::Destroyed => None,
DiskState::Faulted => None,
}
}
}
// Sagas
//
// These are currently only intended for observability by developers. We will
// eventually want to flesh this out into something more observable for end
// users.
#[derive(ObjectIdentity, Clone, Debug, Serialize, JsonSchema)]
pub struct Saga {
pub id: Uuid,
pub state: SagaState,
// TODO-cleanup This object contains a fake `IdentityMetadata`. Why? We
// want to paginate these objects. http_pagination.rs provides a bunch of
// useful facilities -- notably `PaginatedById`. `PaginatedById`
// requires being able to take an arbitrary object in the result set and get
// its id. To do that, it uses the `ObjectIdentity` trait, which expects
// to be able to return an `IdentityMetadata` reference from an object.
// Finally, the pagination facilities just pull the `id` out of that.
//
// In this case (as well as others, like sleds and racks), we have ids, and
// we want to be able to paginate by id, but we don't have full identity
// metadata. (Or we do, but it's similarly faked up.) What we should
// probably do is create a new trait, say `ObjectId`, that returns _just_
// an id. We can provide a blanket impl for anything that impls
// IdentityMetadata. We can define one-off impls for structs like this
// one. Then the id-only pagination interfaces can require just
// `ObjectId`.
#[serde(skip)]
pub identity: IdentityMetadata,
}
impl From<steno::SagaView> for Saga {
fn from(s: steno::SagaView) -> Self {
Saga {
id: Uuid::from(s.id),
state: SagaState::from(s.state),
identity: IdentityMetadata {
// TODO-cleanup See the note in Saga above.
id: Uuid::from(s.id),
name: format!("saga-{}", s.id).parse().unwrap(),
description: format!("saga {}", s.id),
time_created: Utc::now(),
time_modified: Utc::now(),
},
}
}
}
#[derive(Clone, Debug, Serialize, JsonSchema)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum SagaState {
Running,
Succeeded,
Failed { error_node_name: String, error_info: SagaErrorInfo },
}
#[derive(Clone, Debug, Serialize, JsonSchema)]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum SagaErrorInfo {
ActionFailed { source_error: serde_json::Value },
DeserializeFailed { message: String },
InjectedError,
SerializeFailed { message: String },
SubsagaCreateFailed { message: String },
}
impl From<steno::SagaStateView> for SagaState {
fn from(st: steno::SagaStateView) -> Self {
match st {
steno::SagaStateView::Ready { .. } => SagaState::Running,
steno::SagaStateView::Running { .. } => SagaState::Running,
steno::SagaStateView::Done {
result: steno::SagaResult { kind: Ok(_), .. },
..
} => SagaState::Succeeded,
steno::SagaStateView::Done {
result: steno::SagaResult { kind: Err(e), .. },
..
} => SagaState::Failed {
error_node_name: e.error_node_name,
error_info: match e.error_source {
steno::ActionError::ActionFailed { source_error } => {
SagaErrorInfo::ActionFailed { source_error }
}
steno::ActionError::DeserializeFailed { message } => {
SagaErrorInfo::DeserializeFailed { message }
}
steno::ActionError::InjectedError => {
SagaErrorInfo::InjectedError
}
steno::ActionError::SerializeFailed { message } => {
SagaErrorInfo::SerializeFailed { message }
}
steno::ActionError::SubsagaCreateFailed { message } => {
SagaErrorInfo::SubsagaCreateFailed { message }
}
},
},
}
}
}
/// An `Ipv4Net` represents a IPv4 subnetwork, including the address and network mask.
#[derive(Clone, Copy, Debug, Deserialize, Hash, PartialEq, Serialize)]
pub struct Ipv4Net(pub ipnetwork::Ipv4Network);
impl Ipv4Net {
/// Return `true` if this IPv4 subnetwork is from an RFC 1918 private
/// address space.
pub fn is_private(&self) -> bool {
self.0.network().is_private()
}
}
impl std::ops::Deref for Ipv4Net {
type Target = ipnetwork::Ipv4Network;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::fmt::Display for Ipv4Net {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl JsonSchema for Ipv4Net {
fn schema_name() -> String {
"Ipv4Net".to_string()
}
fn json_schema(
_: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
schemars::schema::Schema::Object(
schemars::schema::SchemaObject {
metadata: Some(Box::new(schemars::schema::Metadata {
title: Some("An IPv4 subnet".to_string()),
description: Some("An IPv4 subnet, including prefix and subnet mask".to_string()),
examples: vec!["192.168.1.0/24".into()],
..Default::default()
})),
instance_type: Some(schemars::schema::SingleOrVec::Single(Box::new(schemars::schema::InstanceType::String))),
string: Some(Box::new(schemars::schema::StringValidation {
// Fully-specified IPv4 address. Up to 15 chars for address, plus slash and up to 2 subnet digits.