-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexecution_ctx.rs
233 lines (191 loc) · 8.6 KB
/
execution_ctx.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
//
// Copyright 2022 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
//
// execution_ctx.rs
//
// Struct to store the Wasm Execution Context
use std::collections::HashMap;
use std::sync::{Arc,RwLock};
use rand::Rng;
use once_cell::sync::Lazy;
use anyhow::Result;
use crate::config::WASM_RUNTIME_CONFIGS;
use crate::wasm_engine;
pub struct WasmExecutionCtx {
pub id: String,
pub config_id: String,
pub module_id: String,
pub wasi_args: Vec<String>,
pub wasi_envs: Vec<(String, String)>,
pub wasi_dirs: Vec<String>,
pub wasi_mapdirs: Vec<(String, String)>,
pub wasi_stdin: Vec<u8>,
pub wasi_stdout: Arc<RwLock<Vec<u8>>>,
}
impl WasmExecutionCtx {
/// Create a new Wasm execution context (`WasmExecutionCtx`) and store it into the corresponding `HashMap`
///
/// Returns Result<String, String>, with the ID for the new execution context.
/// Or in case of invalid `config_id`, it returns a String explaing the error.
///
pub fn create_from_config(config_id: &str) -> Result<String, String> {
// get write access to the WasmExecutionCtx HashMap
let mut executionctxs = WASM_RUNTIME_EXECUTIONCTXS.write()
.expect("ERROR! Poisoned RwLock WASM_RUNTIME_EXECUTIONCTXS on write()");
// get read access to the WasmConfig HashMap
let configs = WASM_RUNTIME_CONFIGS.read()
.expect("ERROR! Poisoned RwLock WASM_RUNTIME_CONFIGS on read()");
// check for existing config_id in the loaded configurations
let wasm_config = match configs.get(config_id) {
Some(c) => c,
None => {
let error_msg = format!("Wasm config \'{}\' not found while creating new Wasm execution context", config_id);
return Err(error_msg);
}
};
// generate a random ID of 8 hex digits
let hex_id = Self::generate_random_hex_id(8);
// build the WasmExecutionCtx object based on the WasmConfig object
let wasm_executionctx = WasmExecutionCtx {
id: hex_id.clone(),
config_id: wasm_config.id.clone(),
module_id: wasm_config.module_id.clone(),
wasi_args: wasm_config.wasi_args.clone(),
wasi_envs: wasm_config.wasi_envs.clone(),
wasi_dirs: wasm_config.wasi_dirs.clone(),
wasi_mapdirs: wasm_config.wasi_mapdirs.clone(),
wasi_stdin: Vec::new(),
wasi_stdout: Arc::new(RwLock::new(Vec::new())),
};
// insert created WasmExecutionCtx object into the HashMap
executionctxs.insert(wasm_executionctx.id.clone(), wasm_executionctx);
Ok(hex_id)
}
/// Deallocates an existing Execution Context
///
/// It checks for wrong `executionctx_id`.
/// Returns Result<(), String>, so that in case of error the String will contain the reason.
///
pub fn deallocate(executionctx_id: &str) -> Result<(), String> {
// get write access to the WasmExecutionCtx HashMap
let mut executionctxs = WASM_RUNTIME_EXECUTIONCTXS.write()
.expect("ERROR! Poisoned RwLock WASM_RUNTIME_EXECUTIONCTXS on write()");
match executionctxs.remove(executionctx_id) {
Some(_) => Ok(()),
None => {
let error_msg = format!("Wasm execution context \'{}\' to deallocate not found!", executionctx_id);
Err(error_msg)
}
}
}
/// Add a WASI Enviromental Variable for an existing Wasm execution context
///
/// It checks for wrong `executionctx_id`.
/// Returns Result<(), String>, so that in case of error the String will contain the reason.
///
pub fn add_wasi_env_for_executionctx(executionctx_id: &str, wasi_env: &str, wasi_value: &str) -> Result<(), String> {
// get write access to the WasmExecutionCtx HashMap
let mut executionctxs = WASM_RUNTIME_EXECUTIONCTXS.write()
.expect("ERROR! Poisoned RwLock WASM_RUNTIME_EXECUTIONCTXS on write()");
// get the given WasmExecutionCtx object
let wasm_executionctx = match executionctxs.get_mut(executionctx_id) {
Some(exectx) => exectx,
None => {
let error_msg = format!("Wasm execution context \'{}\' not created previously!", executionctx_id);
return Err(error_msg);
}
};
// add WASI Env into the WasmExecutionCtx object
wasm_executionctx.wasi_envs.push((wasi_env.to_string(), wasi_value.to_string()));
Ok(())
}
/// Add a WASI Stdin for an existing Wasm execution context
///
/// It checks for wrong `executionctx_id`.
/// Returns Result<(), String>, so that in case of error the String will contain the reason.
///
pub fn set_wasi_stdin_for_executionctx(executionctx_id: &str, stdin: Vec<u8>) -> Result<(), String> {
// get write access to the WasmExecutionCtx HashMap
let mut executionctxs = WASM_RUNTIME_EXECUTIONCTXS.write()
.expect("ERROR! Poisoned RwLock WASM_RUNTIME_EXECUTIONCTXS on write()");
// get the given WasmExecutionCtx object
let wasm_executionctx = match executionctxs.get_mut(executionctx_id) {
Some(exectx) => exectx,
None => {
let error_msg = format!("Wasm execution context \'{}\' not created previously!", executionctx_id);
return Err(error_msg);
}
};
// add WASI stdin into the WasmExecutionCtx object
wasm_executionctx.wasi_stdin = stdin;
Ok(())
}
/// Run the given Execution Context
///
/// It checks for wrong `executionctx_id`.
/// Returns Result<String, String>, with the contents of stdout.
/// In case something goes wrong (including invalid `conexecutionctx_id`), it returns a String explaing the error.
///
pub fn run(executionctx_id: &str) -> Result<String, String> {
// get read access to the WasmExecutionCtx HashMap
let executionctxs = WASM_RUNTIME_EXECUTIONCTXS.read()
.expect("ERROR! Poisoned RwLock WASM_RUNTIME_EXECUTIONCTXS on read()");
// get the given WasmExecutionCtx object
let wasm_executionctx = match executionctxs.get(executionctx_id) {
Some(exectx) => exectx,
None => {
let error_msg = format!("Wasm execution context \'{}\' not created previously!", executionctx_id);
return Err(error_msg);
}
};
// invoke "_start" function for the given Wasm execution context
wasm_engine::invoke_wasm_function(wasm_executionctx, "_start")?;
// read stdout from the Wasm execution context and return it
match Self::read_stdout(wasm_executionctx) {
Ok(output) => Ok(output),
Err(e) => Err(e),
}
}
// Helper function to generate random hex IDs for the given length
//
// Returns String with the generated identifier.
//
fn generate_random_hex_id(len: usize) -> String {
const CHARSET: &[u8] = b"0123456789ABCDEF"; // only hex digits
let mut rng = rand::thread_rng();
let id: String = (0..len)
.map(|_| {
let idx = rng.gen_range(0..CHARSET.len());
CHARSET[idx] as char
})
.collect();
id
}
// Helper function to read stdout from the Wasm execution context
//
// Returns Result<String, String> with the succesfully converted stdtout, or a String explaining the error if failure.
//
fn read_stdout(wasm_executionctx: &WasmExecutionCtx) -> Result<String, String> {
let stdout_buf = wasm_executionctx.wasi_stdout.read()
.expect("ERROR! Poisoned RwLock stdout_buf on read()");
// read stdout
let out_string = match String::from_utf8((*stdout_buf).clone()) {
Ok(s) => s,
Err(e) => {
let error_msg = format!("ERROR! Can't convert stdout to UTF-8 string! {}", e);
return Err(error_msg);
}
};
Ok(out_string)
}
}
// The following static variable is used to achieve a global, mutable and thread-safe shareable state.
// For that given purpose, it uses [Once Cell](https://crates.io/crates/once_cell).
// Any object will be protected by `once_cell::sync::Lazy` and `std::sync::{Mutex, RwLock}`.
//
// Stores Wasm Execution Contexts
pub static WASM_RUNTIME_EXECUTIONCTXS: Lazy<RwLock<HashMap<String, WasmExecutionCtx>>> = Lazy::new(|| {
let data: HashMap<String, WasmExecutionCtx> = HashMap::new();
RwLock::new(data)
});