Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 67bf1ac

Browse files
Use CLI to configure max instances cache (#5177)
* Use CLI to configure max instances cache * Fix tests * Move default value into CLI * Use SmallVec * Apply review comments * Get rid of `SmallVec` Co-authored-by: Bastian Köcher <git@kchr.de>
1 parent 475df46 commit 67bf1ac

File tree

23 files changed

+139
-71
lines changed

23 files changed

+139
-71
lines changed

bin/node/executor/benches/bench.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,8 @@ fn bench_execute_block(c: &mut Criterion) {
170170
ExecutionMethod::Native => (true, WasmExecutionMethod::Interpreted),
171171
ExecutionMethod::Wasm(wasm_method) => (false, *wasm_method),
172172
};
173-
let executor = NativeExecutor::new(wasm_method, None);
173+
174+
let executor = NativeExecutor::new(wasm_method, None, 8);
174175
let runtime_code = RuntimeCode {
175176
code_fetcher: &sp_core::traits::WrappedRuntimeCode(COMPACT_CODE.into()),
176177
hash: vec![1, 2, 3],

bin/node/executor/tests/common.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub fn from_block_number(n: u32) -> Header {
5858
}
5959

6060
pub fn executor() -> NativeExecutor<Executor> {
61-
NativeExecutor::new(WasmExecutionMethod::Interpreted, None)
61+
NativeExecutor::new(WasmExecutionMethod::Interpreted, None, 8)
6262
}
6363

6464
pub fn executor_call<

bin/node/runtime/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
8383
// implementation changes and behavior does not, then leave spec_version as
8484
// is and increment impl_version.
8585
spec_version: 235,
86-
impl_version: 0,
86+
impl_version: 1,
8787
apis: RUNTIME_API_VERSIONS,
8888
};
8989

bin/node/testing/src/bench.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ impl BenchDb {
150150

151151
let (client, backend) = sc_client_db::new_client(
152152
db_config,
153-
NativeExecutor::new(WasmExecutionMethod::Compiled, None),
153+
NativeExecutor::new(WasmExecutionMethod::Compiled, None, 8),
154154
&keyring.generate_genesis(),
155155
None,
156156
None,

client/cli/src/commands/runcmd.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,13 @@ pub struct RunCmd {
265265
parse(from_os_str),
266266
conflicts_with_all = &[ "password-interactive", "password" ]
267267
)]
268-
pub password_filename: Option<PathBuf>
268+
pub password_filename: Option<PathBuf>,
269+
270+
/// The size of the instances cache for each runtime.
271+
///
272+
/// The default value is 8 and the values higher than 256 are ignored.
273+
#[structopt(long = "max-runtime-instances", default_value = "8")]
274+
pub max_runtime_instances: usize,
269275
}
270276

271277
impl RunCmd {
@@ -435,6 +441,8 @@ impl RunCmd {
435441
// Imply forced authoring on --dev
436442
config.force_authoring = self.shared_params.dev || self.force_authoring;
437443

444+
config.max_runtime_instances = self.max_runtime_instances.min(256);
445+
438446
Ok(())
439447
}
440448

client/executor/src/integration_tests/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ fn call_in_wasm<E: Externalities>(
4646
Some(1024),
4747
HostFunctions::host_functions(),
4848
true,
49+
8,
4950
);
5051
executor.call_in_wasm(
5152
&WASM_BINARY[..],
@@ -511,6 +512,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) {
511512
Some(17), // `17` is the initial number of pages compiled into the binary.
512513
HostFunctions::host_functions(),
513514
true,
515+
8,
514516
);
515517
executor.call_in_wasm(
516518
&WASM_BINARY[..],

client/executor/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ mod tests {
7878
Some(8),
7979
sp_io::SubstrateHostFunctions::host_functions(),
8080
true,
81+
8,
8182
);
8283
let res = executor.call_in_wasm(
8384
&WASM_BINARY[..],

client/executor/src/native_executor.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ pub struct WasmExecutor {
8585
cache: Arc<RuntimeCache>,
8686
/// Allow missing function imports.
8787
allow_missing_func_imports: bool,
88+
/// The size of the instances cache.
89+
max_runtime_instances: usize,
8890
}
8991

9092
impl WasmExecutor {
@@ -101,13 +103,15 @@ impl WasmExecutor {
101103
default_heap_pages: Option<u64>,
102104
host_functions: Vec<&'static dyn Function>,
103105
allow_missing_func_imports: bool,
106+
max_runtime_instances: usize,
104107
) -> Self {
105108
WasmExecutor {
106109
method,
107110
default_heap_pages: default_heap_pages.unwrap_or(DEFAULT_HEAP_PAGES),
108111
host_functions: Arc::new(host_functions),
109-
cache: Arc::new(RuntimeCache::new()),
112+
cache: Arc::new(RuntimeCache::new(max_runtime_instances)),
110113
allow_missing_func_imports,
114+
max_runtime_instances,
111115
}
112116
}
113117

@@ -223,7 +227,11 @@ impl<D: NativeExecutionDispatch> NativeExecutor<D> {
223227
///
224228
/// `default_heap_pages` - Number of 64KB pages to allocate for Wasm execution.
225229
/// Defaults to `DEFAULT_HEAP_PAGES` if `None` is provided.
226-
pub fn new(fallback_method: WasmExecutionMethod, default_heap_pages: Option<u64>) -> Self {
230+
pub fn new(
231+
fallback_method: WasmExecutionMethod,
232+
default_heap_pages: Option<u64>,
233+
max_runtime_instances: usize,
234+
) -> Self {
227235
let mut host_functions = sp_io::SubstrateHostFunctions::host_functions();
228236

229237
// Add the custom host functions provided by the user.
@@ -233,6 +241,7 @@ impl<D: NativeExecutionDispatch> NativeExecutor<D> {
233241
default_heap_pages,
234242
host_functions,
235243
false,
244+
max_runtime_instances,
236245
);
237246

238247
NativeExecutor {
@@ -463,7 +472,11 @@ mod tests {
463472

464473
#[test]
465474
fn native_executor_registers_custom_interface() {
466-
let executor = NativeExecutor::<MyExecutor>::new(WasmExecutionMethod::Interpreted, None);
475+
let executor = NativeExecutor::<MyExecutor>::new(
476+
WasmExecutionMethod::Interpreted,
477+
None,
478+
8,
479+
);
467480
my_interface::HostFunctions::host_functions().iter().for_each(|function| {
468481
assert_eq!(
469482
executor.wasm.host_functions.iter().filter(|f| f == &function).count(),

client/executor/src/wasm_runtime.rs

Lines changed: 83 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
2222
use std::sync::Arc;
2323
use crate::error::{Error, WasmError};
24-
use parking_lot::{Mutex, RwLock};
24+
use parking_lot::Mutex;
2525
use codec::Decode;
2626
use sp_core::traits::{Externalities, RuntimeCode, FetchRuntimeCode};
2727
use sp_version::RuntimeVersion;
@@ -53,11 +53,77 @@ struct VersionedRuntime {
5353
/// Runtime version according to `Core_version` if any.
5454
version: Option<RuntimeVersion>,
5555
/// Cached instance pool.
56-
instances: RwLock<[Option<Arc<Mutex<Box<dyn WasmInstance>>>>; MAX_INSTANCES]>,
56+
instances: Vec<Mutex<Option<Box<dyn WasmInstance>>>>,
57+
}
58+
59+
impl VersionedRuntime {
60+
/// Run the given closure `f` with an instance of this runtime.
61+
fn with_instance<'c, R, F>(
62+
&self,
63+
ext: &mut dyn Externalities,
64+
f: F,
65+
) -> Result<R, Error>
66+
where F: FnOnce(
67+
&dyn WasmInstance,
68+
Option<&RuntimeVersion>,
69+
&mut dyn Externalities)
70+
-> Result<R, Error>,
71+
{
72+
// Find a free instance
73+
let instance = self.instances
74+
.iter()
75+
.enumerate()
76+
.find_map(|(index, i)| i.try_lock().map(|i| (index, i)));
77+
78+
match instance {
79+
Some((index, mut locked)) => {
80+
let (instance, new_inst) = locked.take()
81+
.map(|r| Ok((r, false)))
82+
.unwrap_or_else(|| self.module.new_instance().map(|i| (i, true)))?;
83+
84+
let result = f(&*instance, self.version.as_ref(), ext);
85+
if let Err(e) = &result {
86+
if new_inst {
87+
log::warn!(
88+
target: "wasm-runtime",
89+
"Fresh runtime instance failed with {:?}",
90+
e,
91+
)
92+
} else {
93+
log::warn!(
94+
target: "wasm-runtime",
95+
"Evicting failed runtime instance: {:?}",
96+
e,
97+
);
98+
}
99+
} else {
100+
*locked = Some(instance);
101+
102+
if new_inst {
103+
log::debug!(
104+
target: "wasm-runtime",
105+
"Allocated WASM instance {}/{}",
106+
index + 1,
107+
self.instances.len(),
108+
);
109+
}
110+
}
111+
112+
result
113+
},
114+
None => {
115+
log::warn!(target: "wasm-runtime", "Ran out of free WASM instances");
116+
117+
// Allocate a new instance
118+
let instance = self.module.new_instance()?;
119+
120+
f(&*instance, self.version.as_ref(), ext)
121+
}
122+
}
123+
}
57124
}
58125

59126
const MAX_RUNTIMES: usize = 2;
60-
const MAX_INSTANCES: usize = 8;
61127

62128
/// Cache for the runtimes.
63129
///
@@ -69,20 +135,22 @@ const MAX_INSTANCES: usize = 8;
69135
/// the memory reset to the initial memory. So, one runtime instance is reused for every fetch
70136
/// request.
71137
///
72-
/// For now the cache grows indefinitely, but that should be fine for now since runtimes can only be
73-
/// upgraded rarely and there are no other ways to make the node to execute some other runtime.
138+
/// The size of cache is equal to `MAX_RUNTIMES`.
74139
pub struct RuntimeCache {
75140
/// A cache of runtimes along with metadata.
76141
///
77142
/// Runtimes sorted by recent usage. The most recently used is at the front.
78143
runtimes: Mutex<[Option<Arc<VersionedRuntime>>; MAX_RUNTIMES]>,
144+
/// The size of the instances cache for each runtime.
145+
max_runtime_instances: usize,
79146
}
80147

81148
impl RuntimeCache {
82149
/// Creates a new instance of a runtimes cache.
83-
pub fn new() -> RuntimeCache {
150+
pub fn new(max_runtime_instances: usize) -> RuntimeCache {
84151
RuntimeCache {
85152
runtimes: Default::default(),
153+
max_runtime_instances,
86154
}
87155
}
88156

@@ -103,6 +171,8 @@ impl RuntimeCache {
103171
///
104172
/// `allow_missing_func_imports` - Ignore missing function imports.
105173
///
174+
/// `max_runtime_instances` - The size of the instances cache.
175+
///
106176
/// `f` - Function to execute.
107177
///
108178
/// # Returns result of `f` wrapped in an additonal result.
@@ -154,6 +224,7 @@ impl RuntimeCache {
154224
heap_pages,
155225
host_functions.into(),
156226
allow_missing_func_imports,
227+
self.max_runtime_instances,
157228
);
158229
if let Err(ref err) = result {
159230
log::warn!(target: "wasm-runtime", "Cannot create a runtime: {:?}", err);
@@ -179,53 +250,7 @@ impl RuntimeCache {
179250
}
180251
drop(runtimes);
181252

182-
let result = {
183-
// Find a free instance
184-
let instance_pool = runtime.instances.read().clone();
185-
let instance = instance_pool
186-
.iter()
187-
.find_map(|i| i.as_ref().and_then(|i| i.try_lock()));
188-
if let Some(mut locked) = instance {
189-
let result = f(&**locked, runtime.version.as_ref(), ext);
190-
if let Err(e) = &result {
191-
log::warn!(target: "wasm-runtime", "Evicting failed runtime instance: {:?}", e);
192-
*locked = runtime.module.new_instance()?;
193-
}
194-
result
195-
} else {
196-
// Allocate a new instance
197-
let instance = runtime.module.new_instance()?;
198-
199-
let result = f(&*instance, runtime.version.as_ref(), ext);
200-
match &result {
201-
Ok(_) => {
202-
let mut instance_pool = runtime.instances.write();
203-
if let Some(ref mut slot) = instance_pool.iter_mut().find(|s| s.is_none()) {
204-
**slot = Some(Arc::new(Mutex::new(instance)));
205-
log::debug!(
206-
target: "wasm-runtime",
207-
"Allocated WASM instance {}/{}",
208-
instance_pool.len(),
209-
MAX_INSTANCES,
210-
);
211-
} else {
212-
log::warn!(target: "wasm-runtime", "Ran out of free WASM instances");
213-
}
214-
}
215-
Err(e) => {
216-
log::warn!(
217-
target:
218-
"wasm-runtime",
219-
"Fresh runtime instance failed with {:?}",
220-
e,
221-
);
222-
}
223-
}
224-
result
225-
}
226-
};
227-
228-
Ok(result)
253+
Ok(runtime.with_instance(ext, f))
229254
}
230255
}
231256

@@ -264,6 +289,7 @@ fn create_versioned_wasm_runtime(
264289
heap_pages: u64,
265290
host_functions: Vec<&'static dyn Function>,
266291
allow_missing_func_imports: bool,
292+
max_instances: usize,
267293
) -> Result<VersionedRuntime, WasmError> {
268294
#[cfg(not(target_os = "unknown"))]
269295
let time = std::time::Instant::now();
@@ -303,13 +329,16 @@ fn create_versioned_wasm_runtime(
303329
time.elapsed().as_millis(),
304330
);
305331

332+
let mut instances = Vec::with_capacity(max_instances);
333+
instances.resize_with(max_instances, || Mutex::new(None));
334+
306335
Ok(VersionedRuntime {
307336
code_hash,
308337
module: runtime,
309338
version,
310339
heap_pages,
311340
wasm_method,
312-
instances: Default::default(),
341+
instances,
313342
})
314343
}
315344

client/finality-grandpa/src/communication/tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ fn peer_with_higher_view_leads_to_catch_up_request() {
482482
.map(move |tester| {
483483
// register a peer with authority role.
484484
tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::AUTHORITY);
485-
((tester, id))
485+
(tester, id)
486486
})
487487
.then(move |(tester, id)| {
488488
// send neighbor message at round 10 and height 50

0 commit comments

Comments
 (0)