blob: 8b3bc2b2c985badfdfdee010802b3efb4883e9a5 [file] [log] [blame]
Janis Danisevskis77d72042021-01-20 15:36:30 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Implements the android.security.vpnprofilestore interface.
16
17use android_security_vpnprofilestore::aidl::android::security::vpnprofilestore::{
18 IVpnProfileStore::BnVpnProfileStore, IVpnProfileStore::IVpnProfileStore,
19 IVpnProfileStore::ERROR_PROFILE_NOT_FOUND, IVpnProfileStore::ERROR_SYSTEM_ERROR,
20};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000021use android_security_vpnprofilestore::binder::{
22 BinderFeatures, ExceptionCode, Result as BinderResult, Status as BinderStatus, Strong,
23 ThreadState,
24};
Janis Danisevskis77d72042021-01-20 15:36:30 -080025use anyhow::{Context, Result};
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +000026use keystore2::{async_task::AsyncTask, legacy_blob::LegacyBlobLoader, utils::watchdog as wd};
Janis Danisevskis77d72042021-01-20 15:36:30 -080027use rusqlite::{
28 params, Connection, OptionalExtension, Transaction, TransactionBehavior, NO_PARAMS,
29};
Janis Danisevskis06891072021-02-11 10:28:17 -080030use std::{
31 collections::HashSet,
32 path::{Path, PathBuf},
33};
Janis Danisevskis77d72042021-01-20 15:36:30 -080034
35struct DB {
36 conn: Connection,
37}
38
39impl DB {
40 fn new(db_file: &Path) -> Result<Self> {
41 let mut db = Self {
42 conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
43 };
Janis Danisevskis1be7e182021-04-12 14:31:12 -070044
45 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
46 db.conn.busy_handler(None).context("Failed to set busy handler.")?;
47
Janis Danisevskis77d72042021-01-20 15:36:30 -080048 db.init_tables().context("Trying to initialize vpnstore db.")?;
49 Ok(db)
50 }
51
52 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
53 where
54 F: Fn(&Transaction) -> Result<T>,
55 {
56 loop {
57 match self
58 .conn
59 .transaction_with_behavior(behavior)
60 .context("In with_transaction.")
61 .and_then(|tx| f(&tx).map(|result| (result, tx)))
62 .and_then(|(result, tx)| {
63 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
64 Ok(result)
65 }) {
66 Ok(result) => break Ok(result),
67 Err(e) => {
68 if Self::is_locked_error(&e) {
69 std::thread::sleep(std::time::Duration::from_micros(500));
70 continue;
71 } else {
72 return Err(e).context("In with_transaction.");
73 }
74 }
75 }
76 }
77 }
78
79 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070080 matches!(
81 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
82 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
83 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
84 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080085 }
86
87 fn init_tables(&mut self) -> Result<()> {
88 self.with_transaction(TransactionBehavior::Immediate, |tx| {
89 tx.execute(
90 "CREATE TABLE IF NOT EXISTS profiles (
91 owner INTEGER,
92 alias BLOB,
93 profile BLOB,
94 UNIQUE(owner, alias));",
95 NO_PARAMS,
96 )
97 .context("Failed to initialize \"profiles\" table.")?;
98 Ok(())
99 })
100 }
101
102 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
103 self.with_transaction(TransactionBehavior::Deferred, |tx| {
104 let mut stmt = tx
105 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
106 .context("In list: Failed to prepare statement.")?;
107
108 let aliases = stmt
109 .query_map(params![caller_uid], |row| row.get(0))?
110 .collect::<rusqlite::Result<Vec<String>>>()
111 .context("In list: query_map failed.");
112 aliases
113 })
114 }
115
116 fn put(&mut self, caller_uid: u32, alias: &str, profile: &[u8]) -> Result<()> {
117 self.with_transaction(TransactionBehavior::Immediate, |tx| {
118 tx.execute(
119 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
120 params![caller_uid, alias, profile,],
121 )
122 .context("In put: Failed to insert or replace.")?;
123 Ok(())
124 })
125 }
126
127 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
128 self.with_transaction(TransactionBehavior::Deferred, |tx| {
129 tx.query_row(
130 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
131 params![caller_uid, alias],
132 |row| row.get(0),
133 )
134 .optional()
135 .context("In get: failed loading profile.")
136 })
137 }
138
139 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
140 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
141 tx.execute(
142 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
143 params![caller_uid, alias],
144 )
145 .context("In remove: Failed to delete row.")
146 })?;
147 Ok(removed == 1)
148 }
149}
150
151/// This is the main VpnProfileStore error type, it wraps binder exceptions and the
152/// VnpStore errors.
153#[derive(Debug, thiserror::Error, PartialEq)]
154pub enum Error {
155 /// Wraps a VpnProfileStore error code.
156 #[error("Error::Error({0:?})")]
157 Error(i32),
158 /// Wraps a Binder exception code other than a service specific exception.
159 #[error("Binder exception code {0:?}, {1:?}")]
160 Binder(ExceptionCode, i32),
161}
162
163impl Error {
164 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
165 pub fn sys() -> Self {
166 Error::Error(ERROR_SYSTEM_ERROR)
167 }
168
169 /// Short hand for `Error::Error(ERROR_PROFILE_NOT_FOUND)`
170 pub fn not_found() -> Self {
171 Error::Error(ERROR_PROFILE_NOT_FOUND)
172 }
173}
174
175/// This function should be used by vpnprofilestore service calls to translate error conditions
176/// into service specific exceptions.
177///
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000178/// All error conditions get logged by this function, except for ERROR_PROFILE_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800179///
180/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
181///
182/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
183///
184/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
185/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
186/// typically returns Ok(value).
187fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
188where
189 F: FnOnce(U) -> BinderResult<T>,
190{
191 result.map_or_else(
192 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800193 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000194 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
195 // Make the profile not found errors silent.
196 Some(Error::Error(ERROR_PROFILE_NOT_FOUND)) => (ERROR_PROFILE_NOT_FOUND, false),
197 Some(Error::Error(e)) => (*e, true),
198 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800199 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000200 if log_error {
201 log::error!("{:?}", e);
202 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800203 Err(BinderStatus::new_service_specific_error(rc, None))
204 },
205 handle_ok,
206 )
207}
208
Janis Danisevskis77d72042021-01-20 15:36:30 -0800209/// Implements IVpnProfileStore AIDL interface.
210pub struct VpnProfileStore {
211 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800212 async_task: AsyncTask,
213}
214
215struct AsyncState {
216 recently_imported: HashSet<(u32, String)>,
217 legacy_loader: LegacyBlobLoader,
218 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800219}
220
221impl VpnProfileStore {
222 /// Creates a new VpnProfileStore instance.
Janis Danisevskis06891072021-02-11 10:28:17 -0800223 pub fn new_native_binder(path: &Path) -> Strong<dyn IVpnProfileStore> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800224 let mut db_path = path.to_path_buf();
225 db_path.push("vpnprofilestore.sqlite");
Janis Danisevskis06891072021-02-11 10:28:17 -0800226
227 let result = Self { db_path, async_task: Default::default() };
228 result.init_shelf(path);
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000229 BnVpnProfileStore::new_binder(result, BinderFeatures::default())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800230 }
231
232 fn open_db(&self) -> Result<DB> {
233 DB::new(&self.db_path).context("In open_db: Failed to open db.")
234 }
235
236 fn get(&self, alias: &str) -> Result<Vec<u8>> {
237 let mut db = self.open_db().context("In get.")?;
238 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800239
240 if let Some(profile) =
241 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
242 {
243 return Ok(profile);
244 }
245 if self.get_legacy(calling_uid, alias).context("In get: Trying to migrate legacy blob.")? {
246 // If we were able to migrate a legacy blob try again.
247 if let Some(profile) =
248 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
249 {
250 return Ok(profile);
251 }
252 }
253 Err(Error::not_found()).context("In get: No such profile.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800254 }
255
256 fn put(&self, alias: &str, profile: &[u8]) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800257 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800258 // In order to make sure that we don't have stale legacy profiles, make sure they are
259 // migrated before replacing them.
260 let _ = self.get_legacy(calling_uid, alias);
261 let mut db = self.open_db().context("In put.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800262 db.put(calling_uid, alias, profile).context("In put: Trying to insert profile into DB.")
263 }
264
265 fn remove(&self, alias: &str) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800266 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800267 let mut db = self.open_db().context("In remove.")?;
268 // In order to make sure that we don't have stale legacy profiles, make sure they are
269 // migrated before removing them.
270 let _ = self.get_legacy(calling_uid, alias);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800271 let removed = db
272 .remove(calling_uid, alias)
273 .context("In remove: Trying to remove profile from DB.")?;
274 if removed {
275 Ok(())
276 } else {
277 Err(Error::not_found()).context("In remove: No such profile.")
278 }
279 }
280
281 fn list(&self, prefix: &str) -> Result<Vec<String>> {
282 let mut db = self.open_db().context("In list.")?;
283 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800284 let mut result = self.list_legacy(calling_uid).context("In list.")?;
285 result
286 .append(&mut db.list(calling_uid).context("In list: Trying to get list of profiles.")?);
287 result = result.into_iter().filter(|s| s.starts_with(prefix)).collect();
288 result.sort_unstable();
289 result.dedup();
290 Ok(result)
291 }
292
293 fn init_shelf(&self, path: &Path) {
294 let mut db_path = path.to_path_buf();
295 self.async_task.queue_hi(move |shelf| {
296 let legacy_loader = LegacyBlobLoader::new(&db_path);
297 db_path.push("vpnprofilestore.sqlite");
298
299 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
300 })
301 }
302
303 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
304 where
305 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
306 {
307 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
308 self.async_task.queue_hi(move |shelf| {
309 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
310 sender.send(f(state)).expect("Failed to send result.");
311 });
312 receiver.recv().context("In do_serialized: Failed to receive result.")?
313 }
314
315 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
316 self.do_serialized(move |state| {
317 state
318 .legacy_loader
319 .list_vpn_profiles(uid)
320 .context("Trying to list legacy vnp profiles.")
321 })
322 .context("In list_legacy.")
323 }
324
325 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
326 let alias = alias.to_string();
327 self.do_serialized(move |state| {
328 if state.recently_imported.contains(&(uid, alias.clone())) {
329 return Ok(true);
330 }
331 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
332 let migrated =
333 Self::migrate_one_legacy_profile(uid, &alias, &state.legacy_loader, &mut db)
334 .context("Trying to migrate legacy vpn profile.")?;
335 if migrated {
336 state.recently_imported.insert((uid, alias));
337 }
338 Ok(migrated)
339 })
340 .context("In get_legacy.")
341 }
342
343 fn migrate_one_legacy_profile(
344 uid: u32,
345 alias: &str,
346 legacy_loader: &LegacyBlobLoader,
347 db: &mut DB,
348 ) -> Result<bool> {
349 let blob = legacy_loader
350 .read_vpn_profile(uid, alias)
351 .context("In migrate_one_legacy_profile: Trying to read legacy vpn profile.")?;
352 if let Some(profile) = blob {
353 db.put(uid, alias, &profile)
354 .context("In migrate_one_legacy_profile: Trying to insert profile into DB.")?;
355 legacy_loader
356 .remove_vpn_profile(uid, alias)
357 .context("In migrate_one_legacy_profile: Trying to delete legacy profile.")?;
358 Ok(true)
359 } else {
360 Ok(false)
361 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800362 }
363}
364
365impl binder::Interface for VpnProfileStore {}
366
367impl IVpnProfileStore for VpnProfileStore {
368 fn get(&self, alias: &str) -> BinderResult<Vec<u8>> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000369 let _wp = wd::watch_millis("IVpnProfileStore::get", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800370 map_or_log_err(self.get(alias), Ok)
371 }
372 fn put(&self, alias: &str, profile: &[u8]) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000373 let _wp = wd::watch_millis("IVpnProfileStore::put", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800374 map_or_log_err(self.put(alias, profile), Ok)
375 }
376 fn remove(&self, alias: &str) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000377 let _wp = wd::watch_millis("IVpnProfileStore::remove", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800378 map_or_log_err(self.remove(alias), Ok)
379 }
380 fn list(&self, prefix: &str) -> BinderResult<Vec<String>> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000381 let _wp = wd::watch_millis("IVpnProfileStore::list", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800382 map_or_log_err(self.list(prefix), Ok)
383 }
384}
385
386#[cfg(test)]
387mod db_test {
388 use super::*;
389 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700390 use std::sync::Arc;
391 use std::thread;
392 use std::time::Duration;
393 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800394
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700395 static TEST_ALIAS: &str = &"test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800396 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
397 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
398 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
399 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
400
401 #[test]
402 fn test_profile_db() {
403 let test_dir = TempDir::new("profiledb_test_").expect("Failed to create temp dir.");
404 let mut db =
405 DB::new(&test_dir.build().push("vpnprofile.sqlite")).expect("Failed to open database.");
406
407 // Insert three profiles for owner 2.
408 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
409 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
410 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
411
412 // Check list returns all inserted aliases.
413 assert_eq!(
414 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
415 db.list(2).expect("Failed to list profiles.")
416 );
417
418 // There should be no profiles for owner 1.
419 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list profiles."));
420
421 // Check the content of the three entries.
422 assert_eq!(
423 Some(TEST_BLOB1),
424 db.get(2, "test1").expect("Failed to get profile.").as_deref()
425 );
426 assert_eq!(
427 Some(TEST_BLOB2),
428 db.get(2, "test2").expect("Failed to get profile.").as_deref()
429 );
430 assert_eq!(
431 Some(TEST_BLOB3),
432 db.get(2, "test3").expect("Failed to get profile.").as_deref()
433 );
434
435 // Remove test2 and check and check that it is no longer retrievable.
436 assert!(db.remove(2, "test2").expect("Failed to remove profile."));
437 assert!(db.get(2, "test2").expect("Failed to get profile.").is_none());
438
439 // test2 should now no longer be in the list.
440 assert_eq!(
441 vec!["test1".to_string(), "test3".to_string(),],
442 db.list(2).expect("Failed to list profiles.")
443 );
444
445 // Put on existing alias replaces it.
446 // Verify test1 is TEST_BLOB1.
447 assert_eq!(
448 Some(TEST_BLOB1),
449 db.get(2, "test1").expect("Failed to get profile.").as_deref()
450 );
451 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
452 // Verify test1 is TEST_BLOB4.
453 assert_eq!(
454 Some(TEST_BLOB4),
455 db.get(2, "test1").expect("Failed to get profile.").as_deref()
456 );
457 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700458
459 #[test]
460 fn concurrent_vpn_profile_test() -> Result<()> {
461 let temp_dir = Arc::new(
462 TempDir::new("concurrent_vpn_profile_test_").expect("Failed to create temp dir."),
463 );
464
465 let db_path = temp_dir.build().push("vpnprofile.sqlite").to_owned();
466
467 let test_begin = Instant::now();
468
469 let mut db = DB::new(&db_path).expect("Failed to open database.");
470 const PROFILE_COUNT: u32 = 5000u32;
471 const PROFILE_DB_COUNT: u32 = 5000u32;
472
473 let mut actual_profile_count = PROFILE_COUNT;
474 // First insert PROFILE_COUNT profiles.
475 for count in 0..PROFILE_COUNT {
476 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
477 actual_profile_count = count;
478 break;
479 }
480 let alias = format!("test_alias_{}", count);
481 db.put(1, &alias, TEST_BLOB1).expect("Failed to add profile (1).");
482 }
483
484 // Insert more keys from a different thread and into a different namespace.
485 let db_path1 = db_path.clone();
486 let handle1 = thread::spawn(move || {
487 let mut db = DB::new(&db_path1).expect("Failed to open database.");
488
489 for count in 0..actual_profile_count {
490 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
491 return;
492 }
493 let alias = format!("test_alias_{}", count);
494 db.put(2, &alias, TEST_BLOB2).expect("Failed to add profile (2).");
495 }
496
497 // Then delete them again.
498 for count in 0..actual_profile_count {
499 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
500 return;
501 }
502 let alias = format!("test_alias_{}", count);
503 db.remove(2, &alias).expect("Remove Failed (2).");
504 }
505 });
506
507 // And start deleting the first set of profiles.
508 let db_path2 = db_path.clone();
509 let handle2 = thread::spawn(move || {
510 let mut db = DB::new(&db_path2).expect("Failed to open database.");
511
512 for count in 0..actual_profile_count {
513 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
514 return;
515 }
516 let alias = format!("test_alias_{}", count);
517 db.remove(1, &alias).expect("Remove Failed (1)).");
518 }
519 });
520
521 // While a lot of inserting and deleting is going on we have to open database connections
522 // successfully and then insert and delete a specific profile.
523 let db_path3 = db_path.clone();
524 let handle3 = thread::spawn(move || {
525 for _count in 0..PROFILE_DB_COUNT {
526 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
527 return;
528 }
529 let mut db = DB::new(&db_path3).expect("Failed to open database.");
530
531 db.put(3, &TEST_ALIAS, TEST_BLOB3).expect("Failed to add profile (3).");
532
533 db.remove(3, &TEST_ALIAS).expect("Remove failed (3).");
534 }
535 });
536
537 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
538 // This may yield an entry or none, but it must not fail.
539 let handle4 = thread::spawn(move || {
540 for _count in 0..PROFILE_DB_COUNT {
541 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
542 return;
543 }
544 let mut db = DB::new(&db_path).expect("Failed to open database.");
545
546 // This may return Some or None but it must not fail.
547 db.get(3, &TEST_ALIAS).expect("Failed to get profile (4).");
548 }
549 });
550
551 handle1.join().expect("Thread 1 panicked.");
552 handle2.join().expect("Thread 2 panicked.");
553 handle3.join().expect("Thread 3 panicked.");
554 handle4.join().expect("Thread 4 panicked.");
555
556 Ok(())
557 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800558}