-
Notifications
You must be signed in to change notification settings - Fork 296
/
canister_settings.rs
520 lines (468 loc) · 18.7 KB
/
canister_settings.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
use ic_base_types::{NumBytes, NumSeconds};
use ic_cycles_account_manager::{CyclesAccountManager, ResourceSaturation};
use ic_error_types::{ErrorCode, UserError};
use ic_ic00_types::{CanisterSettingsArgs, LogVisibility};
use ic_interfaces::execution_environment::SubnetAvailableMemory;
use ic_types::{
ComputeAllocation, Cycles, InvalidComputeAllocationError, InvalidMemoryAllocationError,
MemoryAllocation, PrincipalId,
};
use num_traits::cast::ToPrimitive;
use std::convert::TryFrom;
use crate::canister_manager::CanisterManagerError;
/// Struct used for decoding CanisterSettingsArgs
#[derive(Default)]
pub(crate) struct CanisterSettings {
pub(crate) controller: Option<PrincipalId>,
pub(crate) controllers: Option<Vec<PrincipalId>>,
pub(crate) compute_allocation: Option<ComputeAllocation>,
pub(crate) memory_allocation: Option<MemoryAllocation>,
pub(crate) freezing_threshold: Option<NumSeconds>,
pub(crate) reserved_cycles_limit: Option<Cycles>,
pub(crate) log_visibility: Option<LogVisibility>,
}
impl CanisterSettings {
pub fn new(
controller: Option<PrincipalId>,
controllers: Option<Vec<PrincipalId>>,
compute_allocation: Option<ComputeAllocation>,
memory_allocation: Option<MemoryAllocation>,
freezing_threshold: Option<NumSeconds>,
reserved_cycles_limit: Option<Cycles>,
log_visibility: Option<LogVisibility>,
) -> Self {
Self {
controller,
controllers,
compute_allocation,
memory_allocation,
freezing_threshold,
reserved_cycles_limit,
log_visibility,
}
}
pub fn controller(&self) -> Option<PrincipalId> {
self.controller
}
pub fn controllers(&self) -> Option<Vec<PrincipalId>> {
self.controllers.clone()
}
pub fn compute_allocation(&self) -> Option<ComputeAllocation> {
self.compute_allocation
}
pub fn memory_allocation(&self) -> Option<MemoryAllocation> {
self.memory_allocation
}
pub fn freezing_threshold(&self) -> Option<NumSeconds> {
self.freezing_threshold
}
pub fn reserved_cycles_limit(&self) -> Option<Cycles> {
self.reserved_cycles_limit
}
pub fn log_visibility(&self) -> Option<LogVisibility> {
self.log_visibility
}
}
impl TryFrom<CanisterSettingsArgs> for CanisterSettings {
type Error = UpdateSettingsError;
fn try_from(input: CanisterSettingsArgs) -> Result<Self, Self::Error> {
let controller = input.get_controller();
let compute_allocation = match input.compute_allocation {
Some(ca) => Some(ComputeAllocation::try_from(ca.0.to_u64().ok_or_else(
|| UpdateSettingsError::ComputeAllocation(InvalidComputeAllocationError::new(ca)),
)?)?),
None => None,
};
let memory_allocation = match input.memory_allocation {
Some(ma) => Some(MemoryAllocation::try_from(NumBytes::from(
ma.0.to_u64().ok_or_else(|| {
UpdateSettingsError::MemoryAllocation(InvalidMemoryAllocationError::new(ma))
})?,
))?),
None => None,
};
let freezing_threshold = match input.freezing_threshold {
Some(ft) => Some(NumSeconds::from(ft.0.to_u64().ok_or(
UpdateSettingsError::FreezingThresholdOutOfRange { provided: ft },
)?)),
None => None,
};
let reserved_cycles_limit = match input.reserved_cycles_limit {
Some(limit) => Some(Cycles::from(limit.0.to_u128().ok_or(
UpdateSettingsError::ReservedCyclesLimitOutOfRange { provided: limit },
)?)),
None => None,
};
Ok(CanisterSettings::new(
controller,
input
.controllers
.map(|controllers| controllers.get().clone()),
compute_allocation,
memory_allocation,
freezing_threshold,
reserved_cycles_limit,
input.log_visibility,
))
}
}
impl TryFrom<Option<CanisterSettingsArgs>> for CanisterSettings {
type Error = UpdateSettingsError;
fn try_from(input: Option<CanisterSettingsArgs>) -> Result<Self, Self::Error> {
match input {
Some(settings) => CanisterSettings::try_from(settings),
None => Ok(CanisterSettings::default()),
}
}
}
pub(crate) struct CanisterSettingsBuilder {
controller: Option<PrincipalId>,
controllers: Option<Vec<PrincipalId>>,
compute_allocation: Option<ComputeAllocation>,
memory_allocation: Option<MemoryAllocation>,
freezing_threshold: Option<NumSeconds>,
reserved_cycles_limit: Option<Cycles>,
log_visibility: Option<LogVisibility>,
}
#[allow(dead_code)]
impl CanisterSettingsBuilder {
pub fn new() -> Self {
Self {
controller: None,
controllers: None,
compute_allocation: None,
memory_allocation: None,
freezing_threshold: None,
reserved_cycles_limit: None,
log_visibility: None,
}
}
pub fn build(self) -> CanisterSettings {
CanisterSettings {
controller: self.controller,
controllers: self.controllers,
compute_allocation: self.compute_allocation,
memory_allocation: self.memory_allocation,
freezing_threshold: self.freezing_threshold,
reserved_cycles_limit: self.reserved_cycles_limit,
log_visibility: self.log_visibility,
}
}
pub fn with_controller(self, controller: PrincipalId) -> Self {
Self {
controller: Some(controller),
..self
}
}
pub fn with_controllers(self, controllers: Vec<PrincipalId>) -> Self {
Self {
controllers: Some(controllers),
..self
}
}
pub fn with_compute_allocation(self, compute_allocation: ComputeAllocation) -> Self {
Self {
compute_allocation: Some(compute_allocation),
..self
}
}
pub fn with_memory_allocation(self, memory_allocation: MemoryAllocation) -> Self {
Self {
memory_allocation: Some(memory_allocation),
..self
}
}
pub fn with_freezing_threshold(self, freezing_threshold: NumSeconds) -> Self {
Self {
freezing_threshold: Some(freezing_threshold),
..self
}
}
pub fn with_reserved_cycles_limit(self, reserved_cycles_limit: Cycles) -> Self {
Self {
reserved_cycles_limit: Some(reserved_cycles_limit),
..self
}
}
pub fn with_log_visibility(self, log_visibility: LogVisibility) -> Self {
Self {
log_visibility: Some(log_visibility),
..self
}
}
}
pub enum UpdateSettingsError {
ComputeAllocation(InvalidComputeAllocationError),
MemoryAllocation(InvalidMemoryAllocationError),
FreezingThresholdOutOfRange { provided: candid::Nat },
ReservedCyclesLimitOutOfRange { provided: candid::Nat },
}
impl From<UpdateSettingsError> for UserError {
fn from(err: UpdateSettingsError) -> Self {
match err {
UpdateSettingsError::ComputeAllocation(err) => UserError::new(
ErrorCode::CanisterContractViolation,
format!(
"ComputeAllocation expected to be in the range [{}..{}], got {}",
err.min(),
err.max(),
err.given()
),
),
UpdateSettingsError::MemoryAllocation(err) => UserError::new(
ErrorCode::CanisterContractViolation,
format!(
"MemoryAllocation expected to be in the range [{}..{}], got {}",
err.min, err.max, err.given
),
),
UpdateSettingsError::FreezingThresholdOutOfRange { provided } => UserError::new(
ErrorCode::CanisterContractViolation,
format!(
"Freezing threshold expected to be in the range of [0..2^64-1], got {}",
provided
),
),
UpdateSettingsError::ReservedCyclesLimitOutOfRange { provided } => UserError::new(
ErrorCode::CanisterContractViolation,
format!(
"Reserved cycles limit expected to be in the range of [0..2^128-1], got {}",
provided
),
),
}
}
}
impl From<InvalidComputeAllocationError> for UpdateSettingsError {
fn from(err: InvalidComputeAllocationError) -> Self {
Self::ComputeAllocation(err)
}
}
impl From<InvalidMemoryAllocationError> for UpdateSettingsError {
fn from(err: InvalidMemoryAllocationError) -> Self {
Self::MemoryAllocation(err)
}
}
pub(crate) struct ValidatedCanisterSettings {
controller: Option<PrincipalId>,
controllers: Option<Vec<PrincipalId>>,
compute_allocation: Option<ComputeAllocation>,
memory_allocation: Option<MemoryAllocation>,
freezing_threshold: Option<NumSeconds>,
reserved_cycles_limit: Option<Cycles>,
reservation_cycles: Cycles,
log_visibility: Option<LogVisibility>,
}
impl ValidatedCanisterSettings {
pub fn controller(&self) -> Option<PrincipalId> {
self.controller
}
pub fn controllers(&self) -> Option<Vec<PrincipalId>> {
self.controllers.clone()
}
pub fn compute_allocation(&self) -> Option<ComputeAllocation> {
self.compute_allocation
}
pub fn memory_allocation(&self) -> Option<MemoryAllocation> {
self.memory_allocation
}
pub fn freezing_threshold(&self) -> Option<NumSeconds> {
self.freezing_threshold
}
pub fn reserved_cycles_limit(&self) -> Option<Cycles> {
self.reserved_cycles_limit
}
pub fn reservation_cycles(&self) -> Cycles {
self.reservation_cycles
}
pub fn log_visibility(&self) -> Option<LogVisibility> {
self.log_visibility
}
}
/// Validates the new canisters settings:
/// - memory allocation:
/// - it cannot be lower than the current canister memory usage.
/// - there must be enough available subnet capacity for the change.
/// - there must be enough cycles for storage reservation.
/// - there must be enough cycles to avoid freezing the canister.
/// - compute allocation:
/// - there must be enough available compute capacity for the change.
/// - there must be enough cycles to avoid freezing the canister.
/// - controllers:
/// - the number of controllers cannot exceed the given maximum.
/// Keep this function in sync with `do_update_settings()`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn validate_canister_settings(
settings: CanisterSettings,
canister_memory_usage: NumBytes,
canister_message_memory_usage: NumBytes,
canister_memory_allocation: MemoryAllocation,
subnet_available_memory: &SubnetAvailableMemory,
subnet_memory_saturation: &ResourceSaturation,
canister_compute_allocation: ComputeAllocation,
subnet_compute_allocation_usage: u64,
subnet_compute_allocation_capacity: u64,
max_controllers: usize,
canister_freezing_threshold: NumSeconds,
canister_cycles_balance: Cycles,
cycles_account_manager: &CyclesAccountManager,
subnet_size: usize,
canister_reserved_balance: Cycles,
canister_reserved_balance_limit: Option<Cycles>,
) -> Result<ValidatedCanisterSettings, CanisterManagerError> {
let old_memory_bytes = canister_memory_allocation.allocated_bytes(canister_memory_usage);
let new_memory_bytes = match settings.memory_allocation {
None => canister_memory_usage,
Some(new_memory_allocation) => {
// The new memory allocation cannot be lower than the current canister
// memory usage.
if let MemoryAllocation::Reserved(reserved_bytes) = new_memory_allocation {
if reserved_bytes < canister_memory_usage {
return Err(CanisterManagerError::NotEnoughMemoryAllocationGiven {
memory_allocation_given: new_memory_allocation,
memory_usage_needed: canister_memory_usage,
});
}
}
new_memory_allocation.allocated_bytes(canister_memory_usage)
}
};
// If the available memory in the subnet is negative, then we must cap
// it at zero such that the new memory allocation can change between
// zero and the old memory allocation. Note that capping at zero also
// makes conversion from `i64` to `u64` valid.
let subnet_available_memory = subnet_available_memory.get_execution_memory().max(0) as u64;
let subnet_available_memory = subnet_available_memory.saturating_add(old_memory_bytes.get());
if new_memory_bytes.get() > subnet_available_memory {
return Err(CanisterManagerError::SubnetMemoryCapacityOverSubscribed {
requested: new_memory_bytes,
available: NumBytes::from(subnet_available_memory),
});
}
if let Some(new_compute_allocation) = settings.compute_allocation {
// The saturating `u64` subtractions ensure that the available compute
// capacity of the subnet never goes below zero. This means that even if
// compute capacity is oversubscribed, the new compute allocation can
// change between zero and the old compute allocation.
let available_compute_allocation = subnet_compute_allocation_capacity
.saturating_sub(subnet_compute_allocation_usage)
// Minus 1 below guarantees there is always at least 1% of free compute
// if the subnet was not already oversubscribed.
.saturating_sub(1)
.saturating_add(canister_compute_allocation.as_percent());
if new_compute_allocation.as_percent() > available_compute_allocation {
return Err(CanisterManagerError::SubnetComputeCapacityOverSubscribed {
requested: new_compute_allocation,
available: available_compute_allocation,
});
}
}
// Field `controller` is kept for backward compatibility. However, specifying
// both `controller` and `controllers` fields in the same request results in an
// error.
let controllers = settings.controllers();
if let (Some(_), Some(_)) = (settings.controller(), &controllers) {
return Err(CanisterManagerError::InvalidSettings {
message: "Invalid settings: 'controller' and 'controllers' fields cannot be set simultaneously".to_string(),
});
}
match &controllers {
Some(controllers) => {
if controllers.len() > max_controllers {
return Err(CanisterManagerError::InvalidSettings {
message: "Invalid settings: 'controllers' length exceeds maximum size allowed"
.to_string(),
});
}
}
None => {}
}
let new_memory_allocation = settings
.memory_allocation
.unwrap_or(canister_memory_allocation);
let new_compute_allocation = settings
.compute_allocation()
.unwrap_or(canister_compute_allocation);
let freezing_threshold = settings
.freezing_threshold
.unwrap_or(canister_freezing_threshold);
let threshold = cycles_account_manager.freeze_threshold_cycles(
freezing_threshold,
new_memory_allocation,
canister_memory_usage,
canister_message_memory_usage,
new_compute_allocation,
subnet_size,
canister_reserved_balance,
);
if canister_cycles_balance < threshold {
if new_compute_allocation > canister_compute_allocation {
// Note that the error is produced only if allocation increases.
// This is to allow increasing of the freezing threshold to make the
// canister frozen.
return Err(
CanisterManagerError::InsufficientCyclesInComputeAllocation {
compute_allocation: new_compute_allocation,
available: canister_cycles_balance,
threshold,
},
);
}
if new_memory_allocation > canister_memory_allocation {
// Note that the error is produced only if allocation increases.
// This is to allow increasing of the freezing threshold to make the
// canister frozen.
return Err(CanisterManagerError::InsufficientCyclesInMemoryAllocation {
memory_allocation: new_memory_allocation,
available: canister_cycles_balance,
threshold,
});
}
}
let reservation_cycles = if new_memory_bytes <= old_memory_bytes {
Cycles::zero()
} else {
let allocated_bytes = new_memory_bytes - old_memory_bytes;
let reservation_cycles = cycles_account_manager.storage_reservation_cycles(
allocated_bytes,
subnet_memory_saturation,
subnet_size,
);
let reserved_balance_limit = settings
.reserved_cycles_limit()
.or(canister_reserved_balance_limit);
if let Some(limit) = reserved_balance_limit {
if canister_reserved_balance + reservation_cycles > limit {
return Err(
CanisterManagerError::ReservedCyclesLimitExceededInMemoryAllocation {
memory_allocation: new_memory_allocation,
requested: canister_reserved_balance + reservation_cycles,
limit,
},
);
}
}
// Note that this check does not include the freezing threshold to be
// consistent with the `reserve_cycles()` function, which moves
// cycles between the main and reserved balances without checking
// the freezing threshold.
if canister_cycles_balance < reservation_cycles {
return Err(CanisterManagerError::InsufficientCyclesInMemoryAllocation {
memory_allocation: new_memory_allocation,
available: canister_cycles_balance,
threshold: reservation_cycles,
});
}
reservation_cycles
};
Ok(ValidatedCanisterSettings {
controller: settings.controller(),
controllers: settings.controllers(),
compute_allocation: settings.compute_allocation(),
memory_allocation: settings.memory_allocation(),
freezing_threshold: settings.freezing_threshold(),
reserved_cycles_limit: settings.reserved_cycles_limit(),
reservation_cycles,
log_visibility: settings.log_visibility(),
})
}