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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use crate::task_file_manager::TaskFileManager;
use anyhow::Result;
use teaclave_proto::teaclave_common::{ExecutorCommand, ExecutorStatus};
use teaclave_proto::teaclave_scheduler_service::*;
use teaclave_rpc::transport::{channel::Endpoint, Channel};
use teaclave_types::*;
use teaclave_worker::Worker;
use uuid::Uuid;
static WORKER_BASE_DIR: &str = "/tmp/teaclave_agent/";
#[derive(Clone)]
pub(crate) struct TeaclaveExecutionService {
#[allow(dead_code)]
worker: Arc<Worker>,
scheduler_client: TeaclaveSchedulerClient<Channel>,
fusion_base: PathBuf,
id: Uuid,
status: ExecutorStatus,
}
impl TeaclaveExecutionService {
pub(crate) async fn new(
scheduler_service_endpoint: Endpoint,
fusion_base: impl AsRef<Path>,
) -> Result<Self> {
let channel = scheduler_service_endpoint.connect().await?;
let scheduler_client = TeaclaveSchedulerClient::new_with_builtin_config(channel);
Ok(TeaclaveExecutionService {
worker: Arc::new(Worker::default()),
scheduler_client,
fusion_base: fusion_base.as_ref().to_owned(),
id: Uuid::new_v4(),
status: ExecutorStatus::Idle,
})
}
pub(crate) async fn start(&mut self) -> Result<()> {
let (tx, rx) = mpsc::channel();
let mut current_task: Arc<Option<StagedTask>> = Arc::new(None);
let mut task_handle: Option<thread::JoinHandle<()>> = None;
loop {
std::thread::sleep(std::time::Duration::from_secs(3));
match self.heartbeat().await {
Ok(ExecutorCommand::Stop) => {
log::info!("Executor {} is stopped", self.id);
return Err(anyhow::anyhow!("EnclaveForceTermination"));
}
Ok(ExecutorCommand::NewTask) if self.status == ExecutorStatus::Idle => {
match self.pull_task().await {
Ok(task) => {
self.status = ExecutorStatus::Executing;
self.update_task_status(&task.task_id, TaskStatus::Running)
.await?;
let tx_task = tx.clone();
let fusion_base = self.fusion_base.clone();
current_task = Arc::new(Some(task));
let task_copy = current_task.clone();
let handle = thread::spawn(move || {
let result =
invoke_task(task_copy.as_ref().as_ref().unwrap(), &fusion_base);
tx_task.send(result).unwrap();
});
task_handle = Some(handle);
}
Err(e) => {
log::error!("Executor {} failed to pull task: {}", self.id, e);
}
};
}
Err(e) => {
log::error!("Executor {} failed to heartbeat: {}", self.id, e);
return Err(e);
}
_ => {}
}
match rx.try_recv() {
Ok(result) => {
let task_unwrapped = current_task.as_ref().as_ref().unwrap();
match result {
Ok(_) => log::debug!(
"InvokeTask: {:?}, {:?}, success",
task_unwrapped.task_id,
task_unwrapped.function_id
),
Err(_) => log::debug!(
"InvokeTask: {:?}, {:?}, failure",
task_unwrapped.task_id,
task_unwrapped.function_id
),
}
log::debug!("InvokeTask result: {:?}", result);
let task_copy = current_task.clone();
match self
.update_task_result(&task_copy.as_ref().as_ref().unwrap().task_id, result)
.await
{
Ok(_) => (),
Err(e) => {
log::error!("UpdateResult Error: {:?}", e);
continue;
}
}
current_task = Arc::new(None);
task_handle.unwrap().join().unwrap();
task_handle = None;
self.status = ExecutorStatus::Idle;
}
Err(mpsc::TryRecvError::Disconnected) => {
log::error!(
"Executor {} failed to receive, sender disconnected",
self.id
);
}
Err(_) => {}
}
}
}
async fn pull_task(&mut self) -> Result<StagedTask> {
let request = PullTaskRequest {
executor_id: self.id.to_string(),
};
let response = self.scheduler_client.pull_task(request).await?.into_inner();
log::debug!("pull_stask response: {:?}", response);
let staged_task = StagedTask::from_slice(&response.staged_task)?;
Ok(staged_task)
}
async fn heartbeat(&mut self) -> Result<ExecutorCommand> {
let request = HeartbeatRequest::new(self.id, self.status);
let response = self.scheduler_client.heartbeat(request).await?.into_inner();
log::debug!("heartbeat_with_result response: {:?}", response);
response.command.try_into()
}
async fn update_task_result(
&mut self,
task_id: &Uuid,
task_result: Result<TaskOutputs>,
) -> Result<()> {
let request = UpdateTaskResultRequest::new(*task_id, task_result);
let _response = self.scheduler_client.update_task_result(request).await?;
Ok(())
}
async fn update_task_status(&mut self, task_id: &Uuid, task_status: TaskStatus) -> Result<()> {
let request = UpdateTaskStatusRequest::new(task_id.to_owned(), task_status);
let _response = self.scheduler_client.update_task_status(request).await?;
Ok(())
}
}
fn invoke_task(task: &StagedTask, fusion_base: &PathBuf) -> Result<TaskOutputs> {
let save_log = task
.function_arguments
.get("save_log")
.ok()
.and_then(|v| v.as_str().and_then(|s| s.parse().ok()))
.unwrap_or(false);
let log_arc = Arc::new(Mutex::new(Vec::<String>::new()));
if save_log {
let log_arc = Arc::into_raw(log_arc.clone());
log::info!(buffer = log_arc.expose_addr(); "");
}
let file_mgr = TaskFileManager::new(
WORKER_BASE_DIR,
fusion_base,
&task.task_id,
&task.input_data,
&task.output_data,
)?;
let invocation = prepare_task(task, &file_mgr)?;
log::debug!("Invoke function: {:?}", invocation);
let worker = Worker::default();
let summary = worker.invoke_function(invocation)?;
let outputs_tag = finalize_task(&file_mgr)?;
if save_log {
log::info!(buffer = 0; "");
}
let log = Arc::try_unwrap(log_arc)
.map_err(|_| anyhow::anyhow!("log buffer is referenced more than once"))?
.into_inner()?;
let task_outputs = TaskOutputs::new(summary.as_bytes(), outputs_tag, log);
Ok(task_outputs)
}
fn prepare_task(task: &StagedTask, file_mgr: &TaskFileManager) -> Result<StagedFunction> {
let input_files = file_mgr.prepare_staged_inputs()?;
let output_files = file_mgr.prepare_staged_outputs()?;
let staged_function = StagedFunctionBuilder::new()
.executor_type(task.executor_type)
.executor(task.executor)
.name(&task.function_name)
.arguments(task.function_arguments.clone())
.payload(task.function_payload.clone())
.input_files(input_files)
.output_files(output_files)
.runtime_name("default")
.build();
Ok(staged_function)
}
fn finalize_task(file_mgr: &TaskFileManager) -> Result<HashMap<String, FileAuthTag>> {
file_mgr.upload_outputs()
}
#[cfg(feature = "enclave_unit_test")]
pub mod tests {
use super::*;
use serde_json::json;
use std::format;
use teaclave_crypto::*;
use url::Url;
use uuid::Uuid;
pub fn test_invoke_echo() {
let task_id = Uuid::new_v4();
let function_arguments =
FunctionArguments::from_json(json!({"message": "Hello, Teaclave!"})).unwrap();
let staged_task = StagedTaskBuilder::new()
.task_id(task_id)
.executor(Executor::Builtin)
.function_name("builtin-echo")
.function_arguments(function_arguments)
.build();
let file_mgr = TaskFileManager::new(
WORKER_BASE_DIR,
"/tmp/fusion_base",
&staged_task.task_id,
&staged_task.input_data,
&staged_task.output_data,
)
.unwrap();
let invocation = prepare_task(&staged_task, &file_mgr).unwrap();
let worker = Worker::default();
let result = worker.invoke_function(invocation);
if result.is_ok() {
finalize_task(&file_mgr).unwrap();
}
assert_eq!(result.unwrap(), "Hello, Teaclave!");
}
pub fn test_invoke_gbdt_train() {
let task_id = Uuid::new_v4();
let function_arguments = FunctionArguments::from_json(json!({
"feature_size": 4,
"max_depth": 4,
"iterations": 100,
"shrinkage": 0.1,
"feature_sample_ratio": 1.0,
"data_sample_ratio": 1.0,
"min_leaf_size": 1,
"loss": "LAD",
"training_optimization_level": 2,
}))
.unwrap();
let fixture_dir = format!(
"file:///{}/fixtures/functions/gbdt_training",
env!("TEACLAVE_TEST_INSTALL_DIR")
);
let input_url = Url::parse(&format!("{}/train.enc", fixture_dir)).unwrap();
let output_url = Url::parse(&format!("{}/model-{}.enc.out", fixture_dir, task_id)).unwrap();
let crypto = TeaclaveFile128Key::new(&[0; 16]).unwrap();
let input_cmac = FileAuthTag::from_hex("860030495909b84864b991865e9ad94f").unwrap();
let training_input_data = FunctionInputFile::new(input_url, input_cmac, crypto);
let model_output_data = FunctionOutputFile::new(output_url, crypto);
let input_data = hashmap!("training_data" => training_input_data);
let output_data = hashmap!("trained_model" => model_output_data);
let staged_task = StagedTaskBuilder::new()
.task_id(task_id)
.executor(Executor::Builtin)
.function_name("builtin-gbdt-train")
.function_arguments(function_arguments)
.input_data(input_data)
.output_data(output_data)
.build();
let file_mgr = TaskFileManager::new(
WORKER_BASE_DIR,
"/tmp/fusion_base",
&staged_task.task_id,
&staged_task.input_data,
&staged_task.output_data,
)
.unwrap();
let invocation = prepare_task(&staged_task, &file_mgr).unwrap();
let worker = Worker::default();
let result = worker.invoke_function(invocation);
if result.is_ok() {
finalize_task(&file_mgr).unwrap();
}
log::debug!("summary: {:?}", result);
assert!(result.is_ok());
}
}