This is an automated email from the ASF dual-hosted git repository.

mssun pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave.git


The following commit(s) were added to refs/heads/develop by this push:
     new 540880b  [services] Support gracefully shutdown services
540880b is described below

commit 540880bcc23ff239dd26be7d9aafccf274f7f294
Author: Mingshen Sun <[email protected]>
AuthorDate: Mon Feb 17 23:28:37 2020 -0800

    [services] Support gracefully shutdown services
---
 binder/src/proto.rs                          |  6 +++
 cmake/scripts/gen_cov.sh                     | 22 +-------
 cmake/scripts/test.sh                        |  2 +-
 services/access_control/app/Cargo.toml       |  8 +--
 services/access_control/app/src/main.rs      | 76 ++++++++++++++++++++--------
 services/authentication/app/Cargo.toml       |  8 +--
 services/authentication/app/src/main.rs      | 76 ++++++++++++++++++++--------
 services/execution/app/Cargo.toml            |  5 +-
 services/execution/app/src/main.rs           | 76 ++++++++++++++++++++--------
 services/execution/enclave/Cargo.toml        |  2 +-
 services/frontend/app/Cargo.toml             |  8 +--
 services/frontend/app/src/main.rs            | 76 ++++++++++++++++++++--------
 services/management/app/Cargo.toml           |  8 +--
 services/management/app/src/main.rs          | 76 ++++++++++++++++++++--------
 services/storage/app/Cargo.toml              |  8 +--
 services/storage/app/src/main.rs             | 76 ++++++++++++++++++++--------
 tests/integration/enclave/Enclave.config.xml |  2 +-
 third_party/crates-io                        |  2 +-
 utils/service_enclave_utils/src/lib.rs       |  4 ++
 19 files changed, 378 insertions(+), 163 deletions(-)

diff --git a/binder/src/proto.rs b/binder/src/proto.rs
index abaf43e..f868314 100644
--- a/binder/src/proto.rs
+++ b/binder/src/proto.rs
@@ -62,6 +62,12 @@ pub struct StartServiceInput {
     pub config: teaclave_config::RuntimeConfig,
 }
 
+impl StartServiceInput {
+    pub fn new(config: teaclave_config::RuntimeConfig) -> Self {
+        Self { config }
+    }
+}
+
 #[derive(Clone, Serialize, Deserialize, Debug, Default)]
 pub struct StartServiceOutput;
 
diff --git a/cmake/scripts/gen_cov.sh b/cmake/scripts/gen_cov.sh
index 1d1afdb..6907a12 100755
--- a/cmake/scripts/gen_cov.sh
+++ b/cmake/scripts/gen_cov.sh
@@ -5,32 +5,12 @@ for var in "${REQUIRED_ENVS[@]}"; do
     [ -z "${!var}" ] && echo "Please set ${var}" && exit -1
 done
 
-
-
 LCOV=lcov
 LCOVOPT="--gcov-tool ${MESATEE_PROJECT_ROOT}/cmake/scripts/llvm-gcov"
 GENHTML=genhtml
 
 cd ${MESATEE_PROJECT_ROOT}
-find . \( -name "*.gcda" -and \( ! -name "sgx_cov*" \
-    -and ! -name "kms*" -and ! -name "fns*" \
-    -and ! -name "tdfs*" -and ! -name "tms*" \
-    -and ! -name "private_join_and_compute*"\
-    -and ! -name "online_decrypt*"\
-    -and ! -name "image_resizing*"\
-    -and ! -name "kmeans*"\
-    -and ! -name "logistic_reg*"\
-    -and ! -name "lin_reg*"\
-    -and ! -name "svm*"\
-    -and ! -name "gen_linear_model*"\
-    -and ! -name "gaussian_mixture_model*"\
-    -and ! -name "gaussian_processes*"\
-    -and ! -name "dbscan*"\
-    -and ! -name "neural_net*"\
-    -and ! -name "naive_bayes*"\
-    -and ! -name "gbdt*"\
-    -and ! -name "mesatee_core*" -and ! -name "teaclave_config*" \) \) \
-    -exec rm {} \;
+find . \( -name "*.gcda" -and \( ! -name "teaclave*" \) \) -exec rm {} \;
 cd ${MESATEE_PROJECT_ROOT} && \
     for tag in `find ${MESATEE_PROJECT_ROOT} -name sgx_cov*.gcda | cut -d'.' 
-f2`; \
     do mkdir -p ${MESATEE_OUT_DIR}/cov_$tag && \
diff --git a/cmake/scripts/test.sh b/cmake/scripts/test.sh
index 42e210d..e2c6eba 100755
--- a/cmake/scripts/test.sh
+++ b/cmake/scripts/test.sh
@@ -66,7 +66,7 @@ run_functional_tests() {
   popd
 
   # kill all background services
-  [[ -z "$(jobs -p)" ]] || kill $(jobs -p)
+  [[ -z "$(jobs -p)" ]] || kill -s SIGTERM $(jobs -p)
 }
 
 case "$1" in
diff --git a/services/access_control/app/Cargo.toml 
b/services/access_control/app/Cargo.toml
index 7b93228..3a50613 100644
--- a/services/access_control/app/Cargo.toml
+++ b/services/access_control/app/Cargo.toml
@@ -8,9 +8,11 @@ build = "build.rs"
 edition = "2018"
 
 [dependencies]
-log        = { version = "0.4.6" }
-env_logger = { version = "0.7.1" }
-anyhow     = { version = "1.0.26" }
+log         = { version = "0.4.6" }
+env_logger  = { version = "0.7.1" }
+anyhow      = { version = "1.0.26" }
+signal-hook = { version = "0.1.13" }
+libc        = { version = "0.2.66" }
 
 teaclave_binder            = { path = "../../../binder", features = ["app"] }
 teaclave_config            = { path = "../../../config" }
diff --git a/services/access_control/app/src/main.rs 
b/services/access_control/app/src/main.rs
index 37b19b8..d90122c 100644
--- a/services/access_control/app/src/main.rs
+++ b/services/access_control/app/src/main.rs
@@ -15,38 +15,74 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#[macro_use]
-extern crate log;
-
-use anyhow::Result;
+use anyhow::{Context, Result};
+use signal_hook;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
 use teaclave_binder::proto::{ECallCommand, StartServiceInput, 
StartServiceOutput};
 use teaclave_binder::TeeBinder;
+use teaclave_config::RuntimeConfig;
 use teaclave_types::TeeServiceResult;
 
-fn main() -> Result<()> {
-    env_logger::init();
-    let tee = TeeBinder::new(env!("CARGO_PKG_NAME"))?;
-    run(&tee)?;
+const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
+
+fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
+    for signal in &[
+        signal_hook::SIGTERM,
+        signal_hook::SIGINT,
+        signal_hook::SIGHUP,
+    ] {
+        let term_ref = term.clone();
+        let thread = std::thread::current();
+        unsafe {
+            signal_hook::register(*signal, move || {
+                term_ref.store(true, Ordering::Relaxed);
+                thread.unpark();
+            })?;
+        }
+    }
 
     Ok(())
 }
 
-fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
-    info!("Start enclave service");
-    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let input = StartServiceInput { config };
-    let cmd = ECallCommand::StartService;
-    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(cmd, input) {
-        Err(e) => error!("{:?}", e),
-        Ok(Err(e)) => error!("{:?}", e),
-        _ => (),
+fn start_enclave_service(tee: Arc<TeeBinder>, config: RuntimeConfig) {
+    let input = StartServiceInput::new(config);
+    let command = ECallCommand::StartService;
+    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(command, input) {
+        Err(e) => {
+            eprintln!("TEE invocation error: {:?}", e);
+        }
+        Ok(Err(e)) => {
+            eprintln!("Service exit with error: {:?}", e);
+        }
+        _ => {
+            println!("Service successfully exit");
+        }
     }
 
-    Ok(())
+    unsafe { libc::raise(signal_hook::SIGTERM) };
 }
 
-fn run(tee: &TeeBinder) -> Result<()> {
-    start_enclave_service(tee)?;
+fn main() -> Result<()> {
+    env_logger::init();
+
+    let tee = Arc::new(TeeBinder::new(PACKAGE_NAME).context("Failed to new the 
enclave.")?);
+    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")
+        .context("Failed to load config file.")?;
+
+    let tee_ref = tee.clone();
+    std::thread::spawn(move || {
+        start_enclave_service(tee_ref, config);
+    });
+
+    let term = Arc::new(AtomicBool::new(false));
+    register_signals(term.clone()).context("Failed to register signal 
handler")?;
+
+    while !term.load(Ordering::Relaxed) {
+        std::thread::park();
+    }
+
+    tee.finalize();
 
     Ok(())
 }
diff --git a/services/authentication/app/Cargo.toml 
b/services/authentication/app/Cargo.toml
index 1621a8d..0f0a66e 100644
--- a/services/authentication/app/Cargo.toml
+++ b/services/authentication/app/Cargo.toml
@@ -8,9 +8,11 @@ build = "build.rs"
 edition = "2018"
 
 [dependencies]
-log        = { version = "0.4.6" }
-env_logger = { version = "0.7.1" }
-anyhow     = { version = "1.0.26" }
+log         = { version = "0.4.6" }
+env_logger  = { version = "0.7.1" }
+anyhow      = { version = "1.0.26" }
+signal-hook = { version = "0.1.13" }
+libc        = { version = "0.2.66" }
 
 teaclave_binder            = { path = "../../../binder", features = ["app"] }
 teaclave_config            = { path = "../../../config" }
diff --git a/services/authentication/app/src/main.rs 
b/services/authentication/app/src/main.rs
index 37b19b8..d90122c 100644
--- a/services/authentication/app/src/main.rs
+++ b/services/authentication/app/src/main.rs
@@ -15,38 +15,74 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#[macro_use]
-extern crate log;
-
-use anyhow::Result;
+use anyhow::{Context, Result};
+use signal_hook;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
 use teaclave_binder::proto::{ECallCommand, StartServiceInput, 
StartServiceOutput};
 use teaclave_binder::TeeBinder;
+use teaclave_config::RuntimeConfig;
 use teaclave_types::TeeServiceResult;
 
-fn main() -> Result<()> {
-    env_logger::init();
-    let tee = TeeBinder::new(env!("CARGO_PKG_NAME"))?;
-    run(&tee)?;
+const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
+
+fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
+    for signal in &[
+        signal_hook::SIGTERM,
+        signal_hook::SIGINT,
+        signal_hook::SIGHUP,
+    ] {
+        let term_ref = term.clone();
+        let thread = std::thread::current();
+        unsafe {
+            signal_hook::register(*signal, move || {
+                term_ref.store(true, Ordering::Relaxed);
+                thread.unpark();
+            })?;
+        }
+    }
 
     Ok(())
 }
 
-fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
-    info!("Start enclave service");
-    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let input = StartServiceInput { config };
-    let cmd = ECallCommand::StartService;
-    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(cmd, input) {
-        Err(e) => error!("{:?}", e),
-        Ok(Err(e)) => error!("{:?}", e),
-        _ => (),
+fn start_enclave_service(tee: Arc<TeeBinder>, config: RuntimeConfig) {
+    let input = StartServiceInput::new(config);
+    let command = ECallCommand::StartService;
+    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(command, input) {
+        Err(e) => {
+            eprintln!("TEE invocation error: {:?}", e);
+        }
+        Ok(Err(e)) => {
+            eprintln!("Service exit with error: {:?}", e);
+        }
+        _ => {
+            println!("Service successfully exit");
+        }
     }
 
-    Ok(())
+    unsafe { libc::raise(signal_hook::SIGTERM) };
 }
 
-fn run(tee: &TeeBinder) -> Result<()> {
-    start_enclave_service(tee)?;
+fn main() -> Result<()> {
+    env_logger::init();
+
+    let tee = Arc::new(TeeBinder::new(PACKAGE_NAME).context("Failed to new the 
enclave.")?);
+    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")
+        .context("Failed to load config file.")?;
+
+    let tee_ref = tee.clone();
+    std::thread::spawn(move || {
+        start_enclave_service(tee_ref, config);
+    });
+
+    let term = Arc::new(AtomicBool::new(false));
+    register_signals(term.clone()).context("Failed to register signal 
handler")?;
+
+    while !term.load(Ordering::Relaxed) {
+        std::thread::park();
+    }
+
+    tee.finalize();
 
     Ok(())
 }
diff --git a/services/execution/app/Cargo.toml 
b/services/execution/app/Cargo.toml
index 83bd8d3..f2a34c8 100644
--- a/services/execution/app/Cargo.toml
+++ b/services/execution/app/Cargo.toml
@@ -7,13 +7,12 @@ license = "Apache-2.0"
 build = "build.rs"
 edition = "2018"
 
-[features]
-default = []
-
 [dependencies]
 log         = { version = "0.4.6" }
 env_logger  = { version = "0.7.1" }
 anyhow      = { version = "1.0.26" }
+signal-hook = { version = "0.1.13" }
+libc        = { version = "0.2.66" }
 
 teaclave_binder            = { path = "../../../binder", features = ["app"] }
 teaclave_config            = { path = "../../../config" }
diff --git a/services/execution/app/src/main.rs 
b/services/execution/app/src/main.rs
index 37b19b8..d90122c 100644
--- a/services/execution/app/src/main.rs
+++ b/services/execution/app/src/main.rs
@@ -15,38 +15,74 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#[macro_use]
-extern crate log;
-
-use anyhow::Result;
+use anyhow::{Context, Result};
+use signal_hook;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
 use teaclave_binder::proto::{ECallCommand, StartServiceInput, 
StartServiceOutput};
 use teaclave_binder::TeeBinder;
+use teaclave_config::RuntimeConfig;
 use teaclave_types::TeeServiceResult;
 
-fn main() -> Result<()> {
-    env_logger::init();
-    let tee = TeeBinder::new(env!("CARGO_PKG_NAME"))?;
-    run(&tee)?;
+const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
+
+fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
+    for signal in &[
+        signal_hook::SIGTERM,
+        signal_hook::SIGINT,
+        signal_hook::SIGHUP,
+    ] {
+        let term_ref = term.clone();
+        let thread = std::thread::current();
+        unsafe {
+            signal_hook::register(*signal, move || {
+                term_ref.store(true, Ordering::Relaxed);
+                thread.unpark();
+            })?;
+        }
+    }
 
     Ok(())
 }
 
-fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
-    info!("Start enclave service");
-    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let input = StartServiceInput { config };
-    let cmd = ECallCommand::StartService;
-    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(cmd, input) {
-        Err(e) => error!("{:?}", e),
-        Ok(Err(e)) => error!("{:?}", e),
-        _ => (),
+fn start_enclave_service(tee: Arc<TeeBinder>, config: RuntimeConfig) {
+    let input = StartServiceInput::new(config);
+    let command = ECallCommand::StartService;
+    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(command, input) {
+        Err(e) => {
+            eprintln!("TEE invocation error: {:?}", e);
+        }
+        Ok(Err(e)) => {
+            eprintln!("Service exit with error: {:?}", e);
+        }
+        _ => {
+            println!("Service successfully exit");
+        }
     }
 
-    Ok(())
+    unsafe { libc::raise(signal_hook::SIGTERM) };
 }
 
-fn run(tee: &TeeBinder) -> Result<()> {
-    start_enclave_service(tee)?;
+fn main() -> Result<()> {
+    env_logger::init();
+
+    let tee = Arc::new(TeeBinder::new(PACKAGE_NAME).context("Failed to new the 
enclave.")?);
+    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")
+        .context("Failed to load config file.")?;
+
+    let tee_ref = tee.clone();
+    std::thread::spawn(move || {
+        start_enclave_service(tee_ref, config);
+    });
+
+    let term = Arc::new(AtomicBool::new(false));
+    register_signals(term.clone()).context("Failed to register signal 
handler")?;
+
+    while !term.load(Ordering::Relaxed) {
+        std::thread::park();
+    }
+
+    tee.finalize();
 
     Ok(())
 }
diff --git a/services/execution/enclave/Cargo.toml 
b/services/execution/enclave/Cargo.toml
index cb9d739..4fbc9c3 100644
--- a/services/execution/enclave/Cargo.toml
+++ b/services/execution/enclave/Cargo.toml
@@ -23,7 +23,7 @@ mesalock_sgx = [
   "teaclave_config/mesalock_sgx",
   "teaclave_worker/mesalock_sgx",
 ]
-cov = ["sgx_cov"]
+cov = ["teaclave_service_enclave_utils/cov"]
 enclave_unit_test = ["teaclave_binder/enclave_unit_test", 
"teaclave_test_utils/mesalock_sgx"]
 
 [dependencies]
diff --git a/services/frontend/app/Cargo.toml b/services/frontend/app/Cargo.toml
index 40b5c21..c44d442 100644
--- a/services/frontend/app/Cargo.toml
+++ b/services/frontend/app/Cargo.toml
@@ -8,9 +8,11 @@ build = "build.rs"
 edition = "2018"
 
 [dependencies]
-log        = { version = "0.4.6" }
-env_logger = { version = "0.7.1" }
-anyhow     = { version = "1.0.26" }
+log         = { version = "0.4.6" }
+env_logger  = { version = "0.7.1" }
+anyhow      = { version = "1.0.26" }
+signal-hook = { version = "0.1.13" }
+libc        = { version = "0.2.66" }
 
 teaclave_binder            = { path = "../../../binder", features = ["app"] }
 teaclave_config            = { path = "../../../config" }
diff --git a/services/frontend/app/src/main.rs 
b/services/frontend/app/src/main.rs
index 37b19b8..d90122c 100644
--- a/services/frontend/app/src/main.rs
+++ b/services/frontend/app/src/main.rs
@@ -15,38 +15,74 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#[macro_use]
-extern crate log;
-
-use anyhow::Result;
+use anyhow::{Context, Result};
+use signal_hook;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
 use teaclave_binder::proto::{ECallCommand, StartServiceInput, 
StartServiceOutput};
 use teaclave_binder::TeeBinder;
+use teaclave_config::RuntimeConfig;
 use teaclave_types::TeeServiceResult;
 
-fn main() -> Result<()> {
-    env_logger::init();
-    let tee = TeeBinder::new(env!("CARGO_PKG_NAME"))?;
-    run(&tee)?;
+const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
+
+fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
+    for signal in &[
+        signal_hook::SIGTERM,
+        signal_hook::SIGINT,
+        signal_hook::SIGHUP,
+    ] {
+        let term_ref = term.clone();
+        let thread = std::thread::current();
+        unsafe {
+            signal_hook::register(*signal, move || {
+                term_ref.store(true, Ordering::Relaxed);
+                thread.unpark();
+            })?;
+        }
+    }
 
     Ok(())
 }
 
-fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
-    info!("Start enclave service");
-    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let input = StartServiceInput { config };
-    let cmd = ECallCommand::StartService;
-    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(cmd, input) {
-        Err(e) => error!("{:?}", e),
-        Ok(Err(e)) => error!("{:?}", e),
-        _ => (),
+fn start_enclave_service(tee: Arc<TeeBinder>, config: RuntimeConfig) {
+    let input = StartServiceInput::new(config);
+    let command = ECallCommand::StartService;
+    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(command, input) {
+        Err(e) => {
+            eprintln!("TEE invocation error: {:?}", e);
+        }
+        Ok(Err(e)) => {
+            eprintln!("Service exit with error: {:?}", e);
+        }
+        _ => {
+            println!("Service successfully exit");
+        }
     }
 
-    Ok(())
+    unsafe { libc::raise(signal_hook::SIGTERM) };
 }
 
-fn run(tee: &TeeBinder) -> Result<()> {
-    start_enclave_service(tee)?;
+fn main() -> Result<()> {
+    env_logger::init();
+
+    let tee = Arc::new(TeeBinder::new(PACKAGE_NAME).context("Failed to new the 
enclave.")?);
+    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")
+        .context("Failed to load config file.")?;
+
+    let tee_ref = tee.clone();
+    std::thread::spawn(move || {
+        start_enclave_service(tee_ref, config);
+    });
+
+    let term = Arc::new(AtomicBool::new(false));
+    register_signals(term.clone()).context("Failed to register signal 
handler")?;
+
+    while !term.load(Ordering::Relaxed) {
+        std::thread::park();
+    }
+
+    tee.finalize();
 
     Ok(())
 }
diff --git a/services/management/app/Cargo.toml 
b/services/management/app/Cargo.toml
index f9fd7e7..198e259 100644
--- a/services/management/app/Cargo.toml
+++ b/services/management/app/Cargo.toml
@@ -8,9 +8,11 @@ build = "build.rs"
 edition = "2018"
 
 [dependencies]
-log        = { version = "0.4.6" }
-env_logger = { version = "0.7.1" }
-anyhow     = { version = "1.0.26" }
+log         = { version = "0.4.6" }
+env_logger  = { version = "0.7.1" }
+anyhow      = { version = "1.0.26" }
+signal-hook = { version = "0.1.13" }
+libc        = { version = "0.2.66" }
 
 teaclave_binder            = { path = "../../../binder", features = ["app"] }
 teaclave_config            = { path = "../../../config" }
diff --git a/services/management/app/src/main.rs 
b/services/management/app/src/main.rs
index 37b19b8..d90122c 100644
--- a/services/management/app/src/main.rs
+++ b/services/management/app/src/main.rs
@@ -15,38 +15,74 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#[macro_use]
-extern crate log;
-
-use anyhow::Result;
+use anyhow::{Context, Result};
+use signal_hook;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
 use teaclave_binder::proto::{ECallCommand, StartServiceInput, 
StartServiceOutput};
 use teaclave_binder::TeeBinder;
+use teaclave_config::RuntimeConfig;
 use teaclave_types::TeeServiceResult;
 
-fn main() -> Result<()> {
-    env_logger::init();
-    let tee = TeeBinder::new(env!("CARGO_PKG_NAME"))?;
-    run(&tee)?;
+const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
+
+fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
+    for signal in &[
+        signal_hook::SIGTERM,
+        signal_hook::SIGINT,
+        signal_hook::SIGHUP,
+    ] {
+        let term_ref = term.clone();
+        let thread = std::thread::current();
+        unsafe {
+            signal_hook::register(*signal, move || {
+                term_ref.store(true, Ordering::Relaxed);
+                thread.unpark();
+            })?;
+        }
+    }
 
     Ok(())
 }
 
-fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
-    info!("Start enclave service");
-    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let input = StartServiceInput { config };
-    let cmd = ECallCommand::StartService;
-    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(cmd, input) {
-        Err(e) => error!("{:?}", e),
-        Ok(Err(e)) => error!("{:?}", e),
-        _ => (),
+fn start_enclave_service(tee: Arc<TeeBinder>, config: RuntimeConfig) {
+    let input = StartServiceInput::new(config);
+    let command = ECallCommand::StartService;
+    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(command, input) {
+        Err(e) => {
+            eprintln!("TEE invocation error: {:?}", e);
+        }
+        Ok(Err(e)) => {
+            eprintln!("Service exit with error: {:?}", e);
+        }
+        _ => {
+            println!("Service successfully exit");
+        }
     }
 
-    Ok(())
+    unsafe { libc::raise(signal_hook::SIGTERM) };
 }
 
-fn run(tee: &TeeBinder) -> Result<()> {
-    start_enclave_service(tee)?;
+fn main() -> Result<()> {
+    env_logger::init();
+
+    let tee = Arc::new(TeeBinder::new(PACKAGE_NAME).context("Failed to new the 
enclave.")?);
+    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")
+        .context("Failed to load config file.")?;
+
+    let tee_ref = tee.clone();
+    std::thread::spawn(move || {
+        start_enclave_service(tee_ref, config);
+    });
+
+    let term = Arc::new(AtomicBool::new(false));
+    register_signals(term.clone()).context("Failed to register signal 
handler")?;
+
+    while !term.load(Ordering::Relaxed) {
+        std::thread::park();
+    }
+
+    tee.finalize();
 
     Ok(())
 }
diff --git a/services/storage/app/Cargo.toml b/services/storage/app/Cargo.toml
index f26371b..929c25c 100644
--- a/services/storage/app/Cargo.toml
+++ b/services/storage/app/Cargo.toml
@@ -8,9 +8,11 @@ build = "build.rs"
 edition = "2018"
 
 [dependencies]
-log        = { version = "0.4.6" }
-env_logger = { version = "0.7.1" }
-anyhow     = { version = "1.0.26" }
+log         = { version = "0.4.6" }
+env_logger  = { version = "0.7.1" }
+anyhow      = { version = "1.0.26" }
+signal-hook = { version = "0.1.13" }
+libc        = { version = "0.2.66" }
 
 teaclave_binder            = { path = "../../../binder", features = ["app"] }
 teaclave_config            = { path = "../../../config" }
diff --git a/services/storage/app/src/main.rs b/services/storage/app/src/main.rs
index 37b19b8..d90122c 100644
--- a/services/storage/app/src/main.rs
+++ b/services/storage/app/src/main.rs
@@ -15,38 +15,74 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#[macro_use]
-extern crate log;
-
-use anyhow::Result;
+use anyhow::{Context, Result};
+use signal_hook;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
 use teaclave_binder::proto::{ECallCommand, StartServiceInput, 
StartServiceOutput};
 use teaclave_binder::TeeBinder;
+use teaclave_config::RuntimeConfig;
 use teaclave_types::TeeServiceResult;
 
-fn main() -> Result<()> {
-    env_logger::init();
-    let tee = TeeBinder::new(env!("CARGO_PKG_NAME"))?;
-    run(&tee)?;
+const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
+
+fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
+    for signal in &[
+        signal_hook::SIGTERM,
+        signal_hook::SIGINT,
+        signal_hook::SIGHUP,
+    ] {
+        let term_ref = term.clone();
+        let thread = std::thread::current();
+        unsafe {
+            signal_hook::register(*signal, move || {
+                term_ref.store(true, Ordering::Relaxed);
+                thread.unpark();
+            })?;
+        }
+    }
 
     Ok(())
 }
 
-fn start_enclave_service(tee: &TeeBinder) -> Result<()> {
-    info!("Start enclave service");
-    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")?;
-    let input = StartServiceInput { config };
-    let cmd = ECallCommand::StartService;
-    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(cmd, input) {
-        Err(e) => error!("{:?}", e),
-        Ok(Err(e)) => error!("{:?}", e),
-        _ => (),
+fn start_enclave_service(tee: Arc<TeeBinder>, config: RuntimeConfig) {
+    let input = StartServiceInput::new(config);
+    let command = ECallCommand::StartService;
+    match tee.invoke::<StartServiceInput, 
TeeServiceResult<StartServiceOutput>>(command, input) {
+        Err(e) => {
+            eprintln!("TEE invocation error: {:?}", e);
+        }
+        Ok(Err(e)) => {
+            eprintln!("Service exit with error: {:?}", e);
+        }
+        _ => {
+            println!("Service successfully exit");
+        }
     }
 
-    Ok(())
+    unsafe { libc::raise(signal_hook::SIGTERM) };
 }
 
-fn run(tee: &TeeBinder) -> Result<()> {
-    start_enclave_service(tee)?;
+fn main() -> Result<()> {
+    env_logger::init();
+
+    let tee = Arc::new(TeeBinder::new(PACKAGE_NAME).context("Failed to new the 
enclave.")?);
+    let config = 
teaclave_config::RuntimeConfig::from_toml("runtime.config.toml")
+        .context("Failed to load config file.")?;
+
+    let tee_ref = tee.clone();
+    std::thread::spawn(move || {
+        start_enclave_service(tee_ref, config);
+    });
+
+    let term = Arc::new(AtomicBool::new(false));
+    register_signals(term.clone()).context("Failed to register signal 
handler")?;
+
+    while !term.load(Ordering::Relaxed) {
+        std::thread::park();
+    }
+
+    tee.finalize();
 
     Ok(())
 }
diff --git a/tests/integration/enclave/Enclave.config.xml 
b/tests/integration/enclave/Enclave.config.xml
index 705edcd..daf190d 100644
--- a/tests/integration/enclave/Enclave.config.xml
+++ b/tests/integration/enclave/Enclave.config.xml
@@ -2,7 +2,7 @@
 <EnclaveConfiguration>
   <ProdID>0</ProdID>
   <ISVSVN>0</ISVSVN>
-  <StackMaxSize>0x200000</StackMaxSize>
+  <StackMaxSize>0x500000</StackMaxSize>
   <HeapMaxSize>0x1000000</HeapMaxSize>
   <TCSNum>22</TCSNum>
   <TCSPolicy>0</TCSPolicy>
diff --git a/third_party/crates-io b/third_party/crates-io
index 32da588..6d7fe60 160000
--- a/third_party/crates-io
+++ b/third_party/crates-io
@@ -1 +1 @@
-Subproject commit 32da588d18a0f1981e5acb8cbe4322bfa81b0945
+Subproject commit 6d7fe60e437c067d991c3bfb3ad0f02e103e5971
diff --git a/utils/service_enclave_utils/src/lib.rs 
b/utils/service_enclave_utils/src/lib.rs
index a8db3db..cfcce02 100644
--- a/utils/service_enclave_utils/src/lib.rs
+++ b/utils/service_enclave_utils/src/lib.rs
@@ -12,6 +12,7 @@ use sgx_trts::global_dtors_object;
 #[cfg(feature = "cov")]
 global_dtors_object! {
     SGX_COV_FINALIZE, sgx_cov_exit = {
+        debug!("cov_writeout");
         sgx_cov::cov_writeout();
     }
 }
@@ -37,6 +38,9 @@ impl ServiceEnclave {
     pub fn finalize() -> teaclave_types::TeeServiceResult<()> {
         debug!("Enclave finalizing");
 
+        #[cfg(feature = "cov")]
+        sgx_cov::cov_writeout();
+
         Ok(())
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to