-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathrack.rs
1842 lines (1692 loc) · 70 KB
/
rack.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/.
//! [`DataStore`] methods on [`Rack`]s.
use super::dns::DnsVersionUpdateBuilder;
use super::DataStore;
use super::SERVICE_IP_POOL_NAME;
use crate::authz;
use crate::context::OpContext;
use crate::db;
use crate::db::collection_insert::AsyncInsertError;
use crate::db::collection_insert::DatastoreCollection;
use crate::db::error::public_error_from_diesel;
use crate::db::error::retryable;
use crate::db::error::ErrorHandler;
use crate::db::error::MaybeRetryable::*;
use crate::db::fixed_data::silo::INTERNAL_SILO_ID;
use crate::db::fixed_data::vpc_subnet::DNS_VPC_SUBNET;
use crate::db::fixed_data::vpc_subnet::NEXUS_VPC_SUBNET;
use crate::db::fixed_data::vpc_subnet::NTP_VPC_SUBNET;
use crate::db::identity::Asset;
use crate::db::model::Dataset;
use crate::db::model::IncompleteExternalIp;
use crate::db::model::Rack;
use crate::db::model::Zpool;
use crate::db::pagination::paginated;
use crate::db::pool::DbConnection;
use crate::transaction_retry::OptionalError;
use async_bb8_diesel::AsyncConnection;
use async_bb8_diesel::AsyncRunQueryDsl;
use chrono::Utc;
use diesel::prelude::*;
use diesel::result::Error as DieselError;
use diesel::upsert::excluded;
use ipnetwork::IpNetwork;
use nexus_db_model::DnsGroup;
use nexus_db_model::DnsZone;
use nexus_db_model::ExternalIp;
use nexus_db_model::IncompleteNetworkInterface;
use nexus_db_model::InitialDnsGroup;
use nexus_db_model::PasswordHashString;
use nexus_db_model::SiloUser;
use nexus_db_model::SiloUserPasswordHash;
use nexus_db_model::SledUnderlaySubnetAllocation;
use nexus_types::external_api::params as external_params;
use nexus_types::external_api::shared;
use nexus_types::external_api::shared::IdentityType;
use nexus_types::external_api::shared::IpRange;
use nexus_types::external_api::shared::SiloRole;
use nexus_types::identity::Resource;
use nexus_types::internal_api::params as internal_params;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::Error;
use omicron_common::api::external::IdentityMetadataCreateParams;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupType;
use omicron_common::api::external::ResourceType;
use omicron_common::api::external::UpdateResult;
use omicron_common::bail_unless;
use std::net::IpAddr;
use std::sync::{Arc, OnceLock};
use uuid::Uuid;
/// Groups arguments related to rack initialization
#[derive(Clone)]
pub struct RackInit {
pub rack_id: Uuid,
pub rack_subnet: IpNetwork,
pub services: Vec<internal_params::ServicePutRequest>,
pub datasets: Vec<Dataset>,
pub service_ip_pool_ranges: Vec<IpRange>,
pub internal_dns: InitialDnsGroup,
pub external_dns: InitialDnsGroup,
pub recovery_silo: external_params::SiloCreate,
pub recovery_silo_fq_dns_name: String,
pub recovery_user_id: external_params::UserId,
pub recovery_user_password_hash: omicron_passwords::PasswordHashString,
pub dns_update: DnsVersionUpdateBuilder,
}
/// Possible errors while trying to initialize rack
#[derive(Debug)]
enum RackInitError {
AddingIp(Error),
AddingNic(Error),
ServiceInsert(Error),
DatasetInsert { err: AsyncInsertError, zpool_id: Uuid },
RackUpdate { err: DieselError, rack_id: Uuid },
DnsSerialization(Error),
Silo(Error),
RoleAssignment(Error),
// Retryable database error
Retryable(DieselError),
// Other non-retryable database error
Database(DieselError),
}
// Catch-all for Diesel error conversion into RackInitError, which
// can also label errors as retryable.
impl From<DieselError> for RackInitError {
fn from(e: DieselError) -> Self {
if retryable(&e) {
Self::Retryable(e)
} else {
Self::Database(e)
}
}
}
impl From<RackInitError> for Error {
fn from(e: RackInitError) -> Self {
match e {
RackInitError::AddingIp(err) => err,
RackInitError::AddingNic(err) => err,
RackInitError::DatasetInsert { err, zpool_id } => match err {
AsyncInsertError::CollectionNotFound => Error::ObjectNotFound {
type_name: ResourceType::Zpool,
lookup_type: LookupType::ById(zpool_id),
},
AsyncInsertError::DatabaseError(e) => {
public_error_from_diesel(e, ErrorHandler::Server)
}
},
RackInitError::ServiceInsert(err) => Error::internal_error(
&format!("failed to insert Service record: {:#}", err),
),
RackInitError::RackUpdate { err, rack_id } => {
public_error_from_diesel(
err,
ErrorHandler::NotFoundByLookup(
ResourceType::Rack,
LookupType::ById(rack_id),
),
)
}
RackInitError::DnsSerialization(err) => Error::internal_error(
&format!("failed to serialize initial DNS records: {:#}", err),
),
RackInitError::Silo(err) => Error::internal_error(&format!(
"failed to create recovery Silo: {:#}",
err
)),
RackInitError::RoleAssignment(err) => Error::internal_error(
&format!("failed to assign role to initial user: {:#}", err),
),
RackInitError::Retryable(err) => Error::internal_error(&format!(
"failed operation due to database contention: {:#}",
err
)),
RackInitError::Database(err) => Error::internal_error(&format!(
"failed operation due to database error: {:#}",
err
)),
}
}
}
impl DataStore {
pub async fn rack_list(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<Rack> {
opctx.authorize(authz::Action::Read, &authz::FLEET).await?;
use db::schema::rack::dsl;
paginated(dsl::rack, dsl::id, pagparams)
.select(Rack::as_select())
.load_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))
}
/// Stores a new rack in the database.
///
/// This function is a no-op if the rack already exists.
pub async fn rack_insert(
&self,
opctx: &OpContext,
rack: &Rack,
) -> Result<Rack, Error> {
use db::schema::rack::dsl;
diesel::insert_into(dsl::rack)
.values(rack.clone())
.on_conflict(dsl::id)
.do_update()
// This is a no-op, since we conflicted on the ID.
.set(dsl::id.eq(excluded(dsl::id)))
.returning(Rack::as_returning())
.get_result_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel(
e,
ErrorHandler::Conflict(
ResourceType::Rack,
&rack.id().to_string(),
),
)
})
}
pub async fn update_rack_subnet(
&self,
opctx: &OpContext,
rack: &Rack,
) -> Result<(), Error> {
debug!(
opctx.log,
"updating rack subnet for rack {} to {:#?}",
rack.id(),
rack.rack_subnet
);
use db::schema::rack::dsl;
diesel::update(dsl::rack)
.filter(dsl::id.eq(rack.id()))
.set(dsl::rack_subnet.eq(rack.rack_subnet))
.execute_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;
Ok(())
}
// Return the subnet for the rack
pub async fn rack_subnet(
&self,
opctx: &OpContext,
rack_id: Uuid,
) -> Result<IpNetwork, Error> {
opctx.authorize(authz::Action::Read, &authz::FLEET).await?;
let conn = self.pool_connection_authorized(opctx).await?;
use db::schema::rack::dsl;
// It's safe to unwrap the returned `rack_subnet` because
// we filter on `rack_subnet.is_not_null()`
let subnet = dsl::rack
.filter(dsl::id.eq(rack_id))
.filter(dsl::rack_subnet.is_not_null())
.select(dsl::rack_subnet)
.first_async::<Option<IpNetwork>>(&*conn)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;
match subnet {
Some(subnet) => Ok(subnet),
None => Err(Error::internal_error(
"DB Error(bug): returned a null subnet for {rack_id}",
)),
}
}
/// Allocate a rack subnet octet to a given sled
///
/// 1. Find the existing allocations
/// 2. Calculate the new allocation
/// 3. Save the new allocation, if there isn't one for the given
/// `hw_baseboard_id`
/// 4. Return the new allocation
///
// TODO: This could all actually be done in SQL using a `next_item` query.
// See https://github.com/oxidecomputer/omicron/issues/4544
pub async fn allocate_sled_underlay_subnet_octets(
&self,
opctx: &OpContext,
rack_id: Uuid,
hw_baseboard_id: Uuid,
) -> Result<SledUnderlaySubnetAllocation, Error> {
// Fetch all the existing allocations via self.rack_id
let allocations = self.rack_subnet_allocations(opctx, rack_id).await?;
// Calculate the allocation for the new sled by choosing the minimum
// octet. The returned allocations are ordered by octet, so we will know
// when we have a free one. However, if we already have an allocation
// for the given sled then reuse that one.
const MIN_SUBNET_OCTET: i16 = 33;
let mut new_allocation = SledUnderlaySubnetAllocation {
rack_id,
sled_id: Uuid::new_v4(),
subnet_octet: MIN_SUBNET_OCTET,
hw_baseboard_id,
};
let mut allocation_already_exists = false;
for allocation in allocations {
if allocation.hw_baseboard_id == new_allocation.hw_baseboard_id {
// We already have an allocation for this sled.
new_allocation = allocation;
allocation_already_exists = true;
break;
}
if allocation.subnet_octet == new_allocation.subnet_octet {
bail_unless!(
new_allocation.subnet_octet < 255,
"Too many sled subnets allocated"
);
new_allocation.subnet_octet += 1;
}
}
// Write the new allocation row to CRDB. The UNIQUE constraint
// on `subnet_octet` will prevent dueling administrators reusing
// allocations when sleds are being added. We will need another
// mechanism ala generation numbers when we must interleave additions
// and removals of sleds.
if !allocation_already_exists {
self.sled_subnet_allocation_insert(opctx, &new_allocation).await?;
}
Ok(new_allocation)
}
/// Return all current underlay allocations for the rack.
///
/// Order allocations by `subnet_octet`
pub async fn rack_subnet_allocations(
&self,
opctx: &OpContext,
rack_id: Uuid,
) -> Result<Vec<SledUnderlaySubnetAllocation>, Error> {
opctx.authorize(authz::Action::Read, &authz::FLEET).await?;
use db::schema::sled_underlay_subnet_allocation::dsl as subnet_dsl;
subnet_dsl::sled_underlay_subnet_allocation
.filter(subnet_dsl::rack_id.eq(rack_id))
.select(SledUnderlaySubnetAllocation::as_select())
.order_by(subnet_dsl::subnet_octet.asc())
.load_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))
}
/// Store a new sled subnet allocation in the database
pub async fn sled_subnet_allocation_insert(
&self,
opctx: &OpContext,
allocation: &SledUnderlaySubnetAllocation,
) -> Result<(), Error> {
opctx.authorize(authz::Action::Modify, &authz::FLEET).await?;
use db::schema::sled_underlay_subnet_allocation::dsl;
diesel::insert_into(dsl::sled_underlay_subnet_allocation)
.values(allocation.clone())
.execute_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn rack_create_recovery_silo(
&self,
opctx: &OpContext,
conn: &async_bb8_diesel::Connection<DbConnection>,
log: &slog::Logger,
recovery_silo: external_params::SiloCreate,
recovery_silo_fq_dns_name: String,
recovery_user_id: external_params::UserId,
recovery_user_password_hash: omicron_passwords::PasswordHashString,
dns_update: DnsVersionUpdateBuilder,
) -> Result<(), RackInitError> {
let db_silo = self
.silo_create_conn(
conn,
opctx,
opctx,
recovery_silo,
&[recovery_silo_fq_dns_name],
dns_update,
)
.await
.map_err(|err| match err.retryable() {
NotRetryable(err) => RackInitError::Silo(err.into()),
Retryable(err) => RackInitError::Retryable(err),
})?;
info!(log, "Created recovery silo");
// Create the first user in the initial Recovery Silo
let silo_user_id = Uuid::new_v4();
let silo_user = SiloUser::new(
db_silo.id(),
silo_user_id,
recovery_user_id.as_ref().to_owned(),
);
{
use db::schema::silo_user::dsl;
diesel::insert_into(dsl::silo_user)
.values(silo_user)
.execute_async(conn)
.await?;
}
info!(log, "Created recovery user");
// Set that user's password.
let hash = SiloUserPasswordHash::new(
silo_user_id,
PasswordHashString::from(recovery_user_password_hash),
);
{
use db::schema::silo_user_password_hash::dsl;
diesel::insert_into(dsl::silo_user_password_hash)
.values(hash)
.execute_async(conn)
.await?;
}
info!(log, "Created recovery user's password");
// Grant that user Admin privileges on the Recovery Silo.
// This is very subtle: we must generate both of these queries before we
// execute either of them, and we must not attempt to do any authz
// checks after this in the same transaction because they may deadlock
// with our query.
let authz_silo = authz::Silo::new(
authz::FLEET,
db_silo.id(),
LookupType::ById(db_silo.id()),
);
let (q1, q2) = Self::role_assignment_replace_visible_queries(
opctx,
&authz_silo,
&[shared::RoleAssignment {
identity_type: IdentityType::SiloUser,
identity_id: silo_user_id,
role_name: SiloRole::Admin,
}],
)
.await
.map_err(RackInitError::RoleAssignment)?;
debug!(log, "Generated role assignment queries");
q1.execute_async(conn).await?;
q2.execute_async(conn).await?;
info!(log, "Granted Silo privileges");
Ok(())
}
async fn rack_populate_service_records(
&self,
conn: &async_bb8_diesel::Connection<DbConnection>,
log: &slog::Logger,
service_pool: &db::model::IpPool,
service: internal_params::ServicePutRequest,
) -> Result<(), RackInitError> {
use internal_params::ServiceKind;
let service_db = db::model::Service::new(
service.service_id,
service.sled_id,
service.zone_id,
service.address,
service.kind.clone().into(),
);
self.service_upsert_conn(conn, service_db).await.map_err(
|e| match e.retryable() {
Retryable(e) => RackInitError::Retryable(e),
NotRetryable(e) => RackInitError::ServiceInsert(e.into()),
},
)?;
// For services with external connectivity, we record their
// explicit IP allocation and create a service NIC as well.
let service_ip_nic = match service.kind {
ServiceKind::ExternalDns { external_address, ref nic }
| ServiceKind::Nexus { external_address, ref nic } => {
let db_ip = IncompleteExternalIp::for_service_explicit(
Uuid::new_v4(),
&db::model::Name(nic.name.clone()),
&format!("{}", service.kind),
service.service_id,
service_pool.id(),
external_address,
);
let vpc_subnet = match service.kind {
ServiceKind::ExternalDns { .. } => DNS_VPC_SUBNET.clone(),
ServiceKind::Nexus { .. } => NEXUS_VPC_SUBNET.clone(),
_ => unreachable!(),
};
let db_nic = IncompleteNetworkInterface::new_service(
nic.id,
service.service_id,
vpc_subnet,
IdentityMetadataCreateParams {
name: nic.name.clone(),
description: format!("{} service vNIC", service.kind),
},
Some(nic.ip),
Some(nic.mac),
)
.map_err(|e| RackInitError::AddingNic(e))?;
Some((db_ip, db_nic))
}
ServiceKind::BoundaryNtp { snat, ref nic } => {
let db_ip = IncompleteExternalIp::for_service_explicit_snat(
Uuid::new_v4(),
service.service_id,
service_pool.id(),
snat.ip,
(snat.first_port, snat.last_port),
);
let db_nic = IncompleteNetworkInterface::new_service(
nic.id,
service.service_id,
NTP_VPC_SUBNET.clone(),
IdentityMetadataCreateParams {
name: nic.name.clone(),
description: format!("{} service vNIC", service.kind),
},
Some(nic.ip),
Some(nic.mac),
)
.map_err(|e| RackInitError::AddingNic(e))?;
Some((db_ip, db_nic))
}
_ => None,
};
if let Some((db_ip, db_nic)) = service_ip_nic {
Self::allocate_external_ip_on_connection(conn, db_ip)
.await
.map_err(|err| {
warn!(
log,
"Initializing Rack: Failed to allocate \
IP address for {}",
service.kind,
);
match err.retryable() {
Retryable(e) => RackInitError::Retryable(e),
NotRetryable(e) => RackInitError::AddingIp(e.into()),
}
})?;
self.create_network_interface_raw_conn(conn, db_nic)
.await
.map(|_| ())
.or_else(|e| {
use db::queries::network_interface::InsertError;
match e {
InsertError::InterfaceAlreadyExists(
_,
db::model::NetworkInterfaceKind::Service,
) => Ok(()),
InsertError::Retryable(err) => {
Err(RackInitError::Retryable(err))
}
_ => Err(RackInitError::AddingNic(e.into_external())),
}
})?;
}
info!(log, "Inserted records for {} service", service.kind);
Ok(())
}
/// Update a rack to mark that it has been initialized
pub async fn rack_set_initialized(
&self,
opctx: &OpContext,
rack_init: RackInit,
) -> UpdateResult<Rack> {
use db::schema::rack::dsl as rack_dsl;
opctx.authorize(authz::Action::CreateChild, &authz::FLEET).await?;
let (authz_service_pool, service_pool) =
self.ip_pools_service_lookup(&opctx).await?;
// NOTE: This operation could likely be optimized with a CTE, but given
// the low-frequency of calls, this optimization has been deferred.
let log = opctx.log.clone();
let err = Arc::new(OnceLock::new());
// NOTE: This transaction cannot yet be made retryable, as it uses
// nested transactions.
let rack = self
.pool_connection_authorized(opctx)
.await?
.transaction_async(|conn| {
let err = err.clone();
let log = log.clone();
let authz_service_pool = authz_service_pool.clone();
let rack_init = rack_init.clone();
let service_pool = service_pool.clone();
async move {
let rack_id = rack_init.rack_id;
let services = rack_init.services;
let datasets = rack_init.datasets;
let service_ip_pool_ranges = rack_init.service_ip_pool_ranges;
let internal_dns = rack_init.internal_dns;
let external_dns = rack_init.external_dns;
// Early exit if the rack has already been initialized.
let rack = rack_dsl::rack
.filter(rack_dsl::id.eq(rack_id))
.select(Rack::as_select())
.get_result_async(&conn)
.await
.map_err(|e| {
warn!(log, "Initializing Rack: Rack UUID not found");
err.set(RackInitError::RackUpdate {
err: e,
rack_id,
}).unwrap();
DieselError::RollbackTransaction
})?;
if rack.initialized {
info!(log, "Early exit: Rack already initialized");
return Ok::<_, DieselError>(rack);
}
// Otherwise, insert services and datasets.
// Set up the IP pool for internal services.
for range in service_ip_pool_ranges {
Self::ip_pool_add_range_on_connection(
&conn,
opctx,
&authz_service_pool,
&range,
)
.await
.map_err(|e| {
warn!(
log,
"Initializing Rack: Failed to add IP pool range"
);
err.set(RackInitError::AddingIp(e)).unwrap();
DieselError::RollbackTransaction
})?;
}
// Allocate records for all services.
for service in services {
self.rack_populate_service_records(
&conn,
&log,
&service_pool,
service,
)
.await
.map_err(|e| {
err.set(e).unwrap();
DieselError::RollbackTransaction
})?;
}
info!(log, "Inserted services");
for dataset in datasets {
use db::schema::dataset::dsl;
let zpool_id = dataset.pool_id;
<Zpool as DatastoreCollection<Dataset>>::insert_resource(
zpool_id,
diesel::insert_into(dsl::dataset)
.values(dataset.clone())
.on_conflict(dsl::id)
.do_update()
.set((
dsl::time_modified.eq(Utc::now()),
dsl::pool_id.eq(excluded(dsl::pool_id)),
dsl::ip.eq(excluded(dsl::ip)),
dsl::port.eq(excluded(dsl::port)),
dsl::kind.eq(excluded(dsl::kind)),
)),
)
.insert_and_get_result_async(&conn)
.await
.map_err(|e| {
err.set(RackInitError::DatasetInsert {
err: e,
zpool_id,
}).unwrap();
DieselError::RollbackTransaction
})?;
}
info!(log, "Inserted datasets");
// Insert the initial contents of the internal and external DNS
// zones.
Self::load_dns_data(&conn, internal_dns)
.await
.map_err(|e| {
err.set(RackInitError::DnsSerialization(e)).unwrap();
DieselError::RollbackTransaction
})?;
info!(log, "Populated DNS tables for internal DNS");
Self::load_dns_data(&conn, external_dns)
.await
.map_err(|e| {
err.set(RackInitError::DnsSerialization(e)).unwrap();
DieselError::RollbackTransaction
})?;
info!(log, "Populated DNS tables for external DNS");
// Create the initial Recovery Silo
self.rack_create_recovery_silo(
&opctx,
&conn,
&log,
rack_init.recovery_silo,
rack_init.recovery_silo_fq_dns_name,
rack_init.recovery_user_id,
rack_init.recovery_user_password_hash,
rack_init.dns_update,
)
.await
.map_err(|e| match e {
RackInitError::Retryable(e) => e,
_ => {
err.set(e).unwrap();
DieselError::RollbackTransaction
},
})?;
let rack = diesel::update(rack_dsl::rack)
.filter(rack_dsl::id.eq(rack_id))
.set((
rack_dsl::initialized.eq(true),
rack_dsl::time_modified.eq(Utc::now()),
))
.returning(Rack::as_returning())
.get_result_async::<Rack>(&conn)
.await
.map_err(|e| {
if retryable(&e) {
return e;
}
err.set(RackInitError::RackUpdate {
err: e,
rack_id,
}).unwrap();
DieselError::RollbackTransaction
})?;
Ok(rack)
}
},
)
.await
.map_err(|e| {
if let Some(err) = Arc::try_unwrap(err).unwrap().take() {
err.into()
} else {
Error::internal_error(&format!("Transaction error: {}", e))
}
})?;
Ok(rack)
}
pub async fn load_builtin_rack_data(
&self,
opctx: &OpContext,
rack_id: Uuid,
) -> Result<(), Error> {
use omicron_common::api::external::Name;
self.rack_insert(opctx, &db::model::Rack::new(rack_id)).await?;
let internal_pool =
db::model::IpPool::new(&IdentityMetadataCreateParams {
name: SERVICE_IP_POOL_NAME.parse::<Name>().unwrap(),
description: String::from("IP Pool for Oxide Services"),
});
let internal_pool_id = internal_pool.id();
let internal_created = self
.ip_pool_create(opctx, internal_pool)
.await
.map(|_| true)
.or_else(|e| match e {
Error::ObjectAlreadyExists { .. } => Ok(false),
_ => Err(e),
})?;
// make default for the internal silo. only need to do this if
// the create went through, i.e., if it wasn't already there
if internal_created {
self.ip_pool_link_silo(
opctx,
db::model::IpPoolResource {
ip_pool_id: internal_pool_id,
resource_type: db::model::IpPoolResourceType::Silo,
resource_id: *INTERNAL_SILO_ID,
is_default: true,
},
)
.await?;
}
Ok(())
}
pub async fn nexus_external_addresses(
&self,
opctx: &OpContext,
) -> Result<(Vec<IpAddr>, Vec<DnsZone>), Error> {
opctx.authorize(authz::Action::Read, &authz::DNS_CONFIG).await?;
use crate::db::schema::external_ip::dsl as extip_dsl;
use crate::db::schema::service::dsl as service_dsl;
let err = OptionalError::new();
let conn = self.pool_connection_authorized(opctx).await?;
self.transaction_retry_wrapper("nexus_external_addresses")
.transaction(&conn, |conn| {
let err = err.clone();
async move {
let ips = extip_dsl::external_ip
.inner_join(
service_dsl::service.on(service_dsl::id
.eq(extip_dsl::parent_id.assume_not_null())),
)
.filter(extip_dsl::parent_id.is_not_null())
.filter(extip_dsl::time_deleted.is_null())
.filter(extip_dsl::is_service)
.filter(
service_dsl::kind.eq(db::model::ServiceKind::Nexus),
)
.select(ExternalIp::as_select())
.get_results_async(&conn)
.await?
.into_iter()
.map(|external_ip| external_ip.ip.ip())
.collect();
let dns_zones = self
.dns_zones_list_all_on_connection(
opctx,
&conn,
DnsGroup::External,
)
.await
.map_err(|e| match e.retryable() {
NotRetryable(not_retryable_err) => {
err.bail(not_retryable_err)
}
Retryable(retryable_err) => retryable_err,
})?;
Ok((ips, dns_zones))
}
})
.await
.map_err(|e| {
if let Some(err) = err.take() {
return err.into();
}
public_error_from_diesel(e, ErrorHandler::Server)
})
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::db::datastore::datastore_test;
use crate::db::datastore::test::{
sled_baseboard_for_test, sled_system_hardware_for_test,
};
use crate::db::datastore::Discoverability;
use crate::db::lookup::LookupPath;
use crate::db::model::ExternalIp;
use crate::db::model::IpKind;
use crate::db::model::IpPoolRange;
use crate::db::model::Service;
use crate::db::model::ServiceKind;
use crate::db::model::Sled;
use async_bb8_diesel::AsyncSimpleConnection;
use internal_params::DnsRecord;
use nexus_db_model::{DnsGroup, InitialDnsGroup, SledUpdate};
use nexus_test_utils::db::test_setup_database;
use nexus_types::external_api::shared::SiloIdentityMode;
use nexus_types::identity::Asset;
use nexus_types::internal_api::params::ServiceNic;
use omicron_common::address::{
DNS_OPTE_IPV4_SUBNET, NEXUS_OPTE_IPV4_SUBNET, NTP_OPTE_IPV4_SUBNET,
};
use omicron_common::api::external::http_pagination::PaginatedBy;
use omicron_common::api::external::{
IdentityMetadataCreateParams, MacAddr,
};
use omicron_common::api::internal::shared::SourceNatConfig;
use omicron_common::nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES;
use omicron_test_utils::dev;
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV6};
use std::num::NonZeroU32;
// Default impl is for tests only, and really just so that tests can more
// easily specify just the parts that they want.
impl Default for RackInit {
fn default() -> Self {
RackInit {
rack_id: Uuid::parse_str(nexus_test_utils::RACK_UUID).unwrap(),
rack_subnet: nexus_test_utils::RACK_SUBNET.parse().unwrap(),
services: vec![],
datasets: vec![],
service_ip_pool_ranges: vec![],
internal_dns: InitialDnsGroup::new(
DnsGroup::Internal,
internal_dns::DNS_ZONE,
"test suite",
"test suite",
HashMap::new(),
),
external_dns: InitialDnsGroup::new(
DnsGroup::External,
internal_dns::DNS_ZONE,
"test suite",
"test suite",
HashMap::new(),
),
recovery_silo: external_params::SiloCreate {
identity: IdentityMetadataCreateParams {
name: "test-silo".parse().unwrap(),
description: String::new(),
},
// Set a default quota of a half rack's worth of resources
quotas: external_params::SiloQuotasCreate::arbitrarily_high_default(),
discoverable: false,
identity_mode: SiloIdentityMode::LocalOnly,
admin_group_name: None,
tls_certificates: vec![],
mapped_fleet_roles: Default::default(),
},
recovery_silo_fq_dns_name: format!(
"test-silo.sys.{}",
internal_dns::DNS_ZONE
),
recovery_user_id: "test-user".parse().unwrap(),
// empty string password
recovery_user_password_hash: "$argon2id$v=19$m=98304,t=13,\
p=1$d2t2UHhOdWt3NkYyY1l3cA$pIvmXrcTk/\
nsUzWvBQIeuMJk96ijye/oIXHCj15xg+M"
.parse()
.unwrap(),
dns_update: DnsVersionUpdateBuilder::new(
DnsGroup::External,
"test suite".to_string(),
"test suite".to_string(),
),
}
}
}
fn rack_id() -> Uuid {
Uuid::parse_str(nexus_test_utils::RACK_UUID).unwrap()
}
#[tokio::test]
async fn rack_set_initialized_empty() {
let logctx = dev::test_setup_log("rack_set_initialized_empty");
let mut db = test_setup_database(&logctx.log).await;
let (opctx, datastore) = datastore_test(&logctx, &db).await;
let before = Utc::now();
let rack_init = RackInit::default();
// Initializing the rack with no data is odd, but allowed.
let rack = datastore
.rack_set_initialized(&opctx, rack_init.clone())
.await
.expect("Failed to initialize rack");
let after = Utc::now();
assert_eq!(rack.id(), rack_id());
assert!(rack.initialized);
// Verify the DNS configuration.
let dns_internal = datastore
.dns_config_read(&opctx, DnsGroup::Internal)
.await
.unwrap();
assert_eq!(dns_internal.generation, 1);
assert!(dns_internal.time_created >= before);
assert!(dns_internal.time_created <= after);
assert_eq!(dns_internal.zones.len(), 0);
let dns_external = datastore
.dns_config_read(&opctx, DnsGroup::External)
.await
.unwrap();
// The external DNS zone has an extra update due to the initial Silo
// creation.
assert_eq!(dns_internal.generation + 1, dns_external.generation);
assert_eq!(dns_internal.zones, dns_external.zones);
// Verify the details about the initial Silo.
let silos = datastore
.silos_list(
&opctx,
&PaginatedBy::Name(DataPageParams {
marker: None,
limit: NonZeroU32::new(2).unwrap(),
direction: dropshot::PaginationOrder::Ascending,
}),
Discoverability::DiscoverableOnly,
)
.await
.expect("Failed to list Silos");
// It should *not* show up in the list because it's not discoverable.
assert_eq!(silos.len(), 0);
let (authz_silo, db_silo) = LookupPath::new(&opctx, &datastore)