-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathip_pool.rs
427 lines (402 loc) · 15.4 KB
/
ip_pool.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
// 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 [`IpPool`]s.
use super::DataStore;
use crate::authz;
use crate::authz::ApiResource;
use crate::context::OpContext;
use crate::db;
use crate::db::collection_insert::AsyncInsertError;
use crate::db::collection_insert::DatastoreCollection;
use crate::db::error::diesel_pool_result_optional;
use crate::db::error::public_error_from_diesel_pool;
use crate::db::error::ErrorHandler;
use crate::db::identity::Resource;
use crate::db::lookup::LookupPath;
use crate::db::model::IpPool;
use crate::db::model::IpPoolRange;
use crate::db::model::IpPoolUpdate;
use crate::db::model::Name;
use crate::db::pagination::paginated;
use crate::db::pool::DbConnection;
use crate::db::queries::ip_pool::FilterOverlappingIpRanges;
use async_bb8_diesel::{AsyncRunQueryDsl, PoolError};
use chrono::Utc;
use diesel::prelude::*;
use ipnetwork::IpNetwork;
use nexus_types::external_api::params;
use nexus_types::external_api::shared::IpRange;
use omicron_common::api::external::http_pagination::PaginatedBy;
use omicron_common::api::external::CreateResult;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::DeleteResult;
use omicron_common::api::external::Error;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupResult;
use omicron_common::api::external::LookupType;
use omicron_common::api::external::Name as ExternalName;
use omicron_common::api::external::ResourceType;
use omicron_common::api::external::UpdateResult;
use ref_cast::RefCast;
use std::str::FromStr;
use uuid::Uuid;
impl DataStore {
/// List IP Pools
pub async fn ip_pools_list(
&self,
opctx: &OpContext,
pagparams: &PaginatedBy<'_>,
) -> ListResultVec<IpPool> {
use db::schema::ip_pool::dsl;
opctx
.authorize(authz::Action::ListChildren, &authz::IP_POOL_LIST)
.await?;
match pagparams {
PaginatedBy::Id(pagparams) => {
paginated(dsl::ip_pool, dsl::id, pagparams)
}
PaginatedBy::Name(pagparams) => paginated(
dsl::ip_pool,
dsl::name,
&pagparams.map_name(|n| Name::ref_cast(n)),
),
}
.filter(dsl::internal.eq(false))
.filter(dsl::time_deleted.is_null())
.select(db::model::IpPool::as_select())
.get_results_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
}
/// Looks up the default IP pool by name.
pub async fn ip_pools_fetch_default_for(
&self,
opctx: &OpContext,
action: authz::Action,
) -> LookupResult<(authz::IpPool, IpPool)> {
self.ip_pools_fetch_for(
opctx,
action,
&Name(ExternalName::from_str("default").unwrap()),
)
.await
}
/// Looks up an IP pool by name.
pub(crate) async fn ip_pools_fetch_for(
&self,
opctx: &OpContext,
action: authz::Action,
name: &Name,
) -> LookupResult<(authz::IpPool, IpPool)> {
let (.., authz_pool, pool) = LookupPath::new(opctx, &self)
.ip_pool_name(&name)
.fetch_for(action)
.await?;
if pool.internal {
return Err(authz_pool.not_found());
}
Ok((authz_pool, pool))
}
/// Looks up an IP pool intended for internal services.
///
/// This method may require an index by Availability Zone in the future.
pub async fn ip_pools_service_lookup(
&self,
opctx: &OpContext,
) -> LookupResult<(authz::IpPool, IpPool)> {
use db::schema::ip_pool::dsl;
opctx
.authorize(authz::Action::ListChildren, &authz::IP_POOL_LIST)
.await?;
// Look up this IP pool by rack ID.
let (authz_pool, pool) = dsl::ip_pool
.filter(dsl::internal.eq(true))
.filter(dsl::time_deleted.is_null())
.select(IpPool::as_select())
.get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))
.map(|ip_pool| {
(
authz::IpPool::new(
authz::FLEET,
ip_pool.id(),
LookupType::ByCompositeId(
"Service IP Pool".to_string(),
),
),
ip_pool,
)
})?;
Ok((authz_pool, pool))
}
/// Creates a new IP pool.
///
/// - If `internal` is set, this IP pool is used for Oxide services.
pub async fn ip_pool_create(
&self,
opctx: &OpContext,
new_pool: ¶ms::IpPoolCreate,
internal: bool,
) -> CreateResult<IpPool> {
use db::schema::ip_pool::dsl;
opctx
.authorize(authz::Action::CreateChild, &authz::IP_POOL_LIST)
.await?;
let pool = IpPool::new(&new_pool.identity, internal);
let pool_name = pool.name().as_str().to_string();
diesel::insert_into(dsl::ip_pool)
.values(pool)
.returning(IpPool::as_returning())
.get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::Conflict(ResourceType::IpPool, &pool_name),
)
})
}
pub async fn ip_pool_delete(
&self,
opctx: &OpContext,
authz_pool: &authz::IpPool,
db_pool: &IpPool,
) -> DeleteResult {
use db::schema::ip_pool::dsl;
use db::schema::ip_pool_range;
opctx.authorize(authz::Action::Delete, authz_pool).await?;
// Verify there are no IP ranges still in this pool
let range = diesel_pool_result_optional(
ip_pool_range::dsl::ip_pool_range
.filter(ip_pool_range::dsl::ip_pool_id.eq(authz_pool.id()))
.filter(ip_pool_range::dsl::time_deleted.is_null())
.select(ip_pool_range::dsl::id)
.limit(1)
.first_async::<Uuid>(self.pool_authorized(opctx).await?)
.await,
)
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))?;
if range.is_some() {
return Err(Error::InvalidRequest {
message:
"IP Pool cannot be deleted while it contains IP ranges"
.to_string(),
});
}
// Delete the pool, conditional on the rcgen not having changed. This
// protects the delete from occuring if clients created a new IP range
// in between the above check for children and this query.
let now = Utc::now();
let updated_rows = diesel::update(dsl::ip_pool)
.filter(dsl::internal.eq(false))
.filter(dsl::time_deleted.is_null())
.filter(dsl::id.eq(authz_pool.id()))
.filter(dsl::rcgen.eq(db_pool.rcgen))
.set(dsl::time_deleted.eq(now))
.execute_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByResource(authz_pool),
)
})?;
if updated_rows == 0 {
return Err(Error::InvalidRequest {
message: "deletion failed due to concurrent modification"
.to_string(),
});
}
Ok(())
}
pub async fn ip_pool_update(
&self,
opctx: &OpContext,
authz_pool: &authz::IpPool,
updates: IpPoolUpdate,
) -> UpdateResult<IpPool> {
use db::schema::ip_pool::dsl;
opctx.authorize(authz::Action::Modify, authz_pool).await?;
diesel::update(dsl::ip_pool)
.filter(dsl::internal.eq(false))
.filter(dsl::id.eq(authz_pool.id()))
.filter(dsl::time_deleted.is_null())
.set(updates)
.returning(IpPool::as_returning())
.get_result_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByResource(authz_pool),
)
})
}
pub async fn ip_pool_list_ranges(
&self,
opctx: &OpContext,
authz_pool: &authz::IpPool,
pag_params: &DataPageParams<'_, IpNetwork>,
) -> ListResultVec<IpPoolRange> {
use db::schema::ip_pool_range::dsl;
opctx.authorize(authz::Action::ListChildren, authz_pool).await?;
paginated(dsl::ip_pool_range, dsl::first_address, pag_params)
.filter(dsl::ip_pool_id.eq(authz_pool.id()))
.filter(dsl::time_deleted.is_null())
.select(IpPoolRange::as_select())
.get_results_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| {
public_error_from_diesel_pool(
e,
ErrorHandler::NotFoundByResource(authz_pool),
)
})
}
pub async fn ip_pool_add_range(
&self,
opctx: &OpContext,
authz_pool: &authz::IpPool,
range: &IpRange,
) -> CreateResult<IpPoolRange> {
let conn = self.pool_authorized(opctx).await?;
Self::ip_pool_add_range_on_connection(conn, opctx, authz_pool, range)
.await
}
/// Variant of [Self::ip_pool_add_range] which may be called from a
/// transaction context.
pub(crate) async fn ip_pool_add_range_on_connection<ConnErr>(
conn: &(impl async_bb8_diesel::AsyncConnection<DbConnection, ConnErr>
+ Sync),
opctx: &OpContext,
authz_pool: &authz::IpPool,
range: &IpRange,
) -> CreateResult<IpPoolRange>
where
ConnErr: From<diesel::result::Error> + Send + 'static,
PoolError: From<ConnErr>,
{
use db::schema::ip_pool_range::dsl;
opctx.authorize(authz::Action::CreateChild, authz_pool).await?;
let pool_id = authz_pool.id();
let new_range = IpPoolRange::new(range, pool_id);
let filter_subquery = FilterOverlappingIpRanges { range: new_range };
let insert_query =
diesel::insert_into(dsl::ip_pool_range).values(filter_subquery);
IpPool::insert_resource(pool_id, insert_query)
.insert_and_get_result_async(conn)
.await
.map_err(|e| {
use async_bb8_diesel::ConnectionError::Query;
use async_bb8_diesel::PoolError::Connection;
use diesel::result::Error::NotFound;
match e {
AsyncInsertError::DatabaseError(Connection(Query(
NotFound,
))) => {
// We've filtered out the IP addresses the client provided,
// i.e., there's some overlap with existing addresses.
Error::invalid_request(
format!(
"The provided IP range {}-{} overlaps with \
an existing range",
range.first_address(),
range.last_address(),
)
.as_str(),
)
}
AsyncInsertError::CollectionNotFound => {
Error::ObjectNotFound {
type_name: ResourceType::IpPool,
lookup_type: LookupType::ById(pool_id),
}
}
AsyncInsertError::DatabaseError(err) => {
public_error_from_diesel_pool(err, ErrorHandler::Server)
}
}
})
}
pub async fn ip_pool_delete_range(
&self,
opctx: &OpContext,
authz_pool: &authz::IpPool,
range: &IpRange,
) -> DeleteResult {
use db::schema::external_ip;
use db::schema::ip_pool_range::dsl;
opctx.authorize(authz::Action::Modify, authz_pool).await?;
let pool_id = authz_pool.id();
let first_address = range.first_address();
let last_address = range.last_address();
let first_net = ipnetwork::IpNetwork::from(first_address);
let last_net = ipnetwork::IpNetwork::from(last_address);
// Fetch the range itself, if it exists. We'll need to protect against
// concurrent inserts of new external IPs from the target range by
// comparing the rcgen.
let range = diesel_pool_result_optional(
dsl::ip_pool_range
.filter(dsl::ip_pool_id.eq(pool_id))
.filter(dsl::first_address.eq(first_net))
.filter(dsl::last_address.eq(last_net))
.filter(dsl::time_deleted.is_null())
.select(IpPoolRange::as_select())
.get_result_async::<IpPoolRange>(
self.pool_authorized(opctx).await?,
)
.await,
)
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))?
.ok_or_else(|| {
Error::invalid_request(
format!(
"The provided range {}-{} does not exist",
first_address, last_address,
)
.as_str(),
)
})?;
// Find external IPs allocated out of this pool and range.
let range_id = range.id;
let has_children = diesel::dsl::select(diesel::dsl::exists(
external_ip::table
.filter(external_ip::dsl::ip_pool_id.eq(pool_id))
.filter(external_ip::dsl::ip_pool_range_id.eq(range_id))
.filter(external_ip::dsl::time_deleted.is_null()),
))
.get_result_async::<bool>(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))?;
if has_children {
return Err(Error::invalid_request(
"IP pool ranges cannot be deleted while \
external IP addresses are allocated from them",
));
}
// Delete the range, conditional on the rcgen not having changed. This
// protects the delete from occuring if clients allocated a new external
// IP address in between the above check for children and this query.
let rcgen = range.rcgen;
let now = Utc::now();
let updated_rows = diesel::update(
dsl::ip_pool_range
.find(range_id)
.filter(dsl::time_deleted.is_null())
.filter(dsl::rcgen.eq(rcgen)),
)
.set(dsl::time_deleted.eq(now))
.execute_async(self.pool_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel_pool(e, ErrorHandler::Server))?;
if updated_rows == 1 {
Ok(())
} else {
Err(Error::invalid_request(
"IP range deletion failed due to concurrent modification",
))
}
}
}