blob: df2731aa06368a7b7e7ee236f42f24361a08e5b1 [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};
Seth Moore472fcbb2021-05-12 10:07:51 -070025use anyhow::{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},
Seth Moore472fcbb2021-05-12 10:07:51 -070033 sync::Once,
Janis Danisevskis06891072021-02-11 10:28:17 -080034};
Janis Danisevskis77d72042021-01-20 15:36:30 -080035
Seth Moore472fcbb2021-05-12 10:07:51 -070036static DB_SET_WAL_MODE: Once = Once::new();
37
Janis Danisevskis77d72042021-01-20 15:36:30 -080038struct DB {
39 conn: Connection,
40}
41
42impl DB {
43 fn new(db_file: &Path) -> Result<Self> {
Seth Moore472fcbb2021-05-12 10:07:51 -070044 DB_SET_WAL_MODE.call_once(|| {
45 log::info!("Setting VpnProfileStore database to WAL mode first time since boot.");
46 Self::set_wal_mode(&db_file).expect("In vpnprofilestore: Could not set WAL mode.");
47 });
48
Janis Danisevskis77d72042021-01-20 15:36:30 -080049 let mut db = Self {
50 conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
51 };
Janis Danisevskis1be7e182021-04-12 14:31:12 -070052
Janis Danisevskis77d72042021-01-20 15:36:30 -080053 db.init_tables().context("Trying to initialize vpnstore db.")?;
54 Ok(db)
55 }
56
Seth Moore472fcbb2021-05-12 10:07:51 -070057 fn set_wal_mode(db_file: &Path) -> Result<()> {
58 let conn = Connection::open(db_file)
59 .context("In VpnProfileStore set_wal_mode: Failed to open DB.")?;
60 let mode: String = conn
61 .pragma_update_and_check(None, "journal_mode", &"WAL", |row| row.get(0))
62 .context("In VpnProfileStore set_wal_mode: Failed to set journal_mode")?;
63 match mode.as_str() {
64 "wal" => Ok(()),
65 _ => Err(anyhow!("Unable to set WAL mode, db is still in {} mode.", mode)),
66 }
67 }
68
Janis Danisevskis77d72042021-01-20 15:36:30 -080069 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
70 where
71 F: Fn(&Transaction) -> Result<T>,
72 {
73 loop {
74 match self
75 .conn
76 .transaction_with_behavior(behavior)
77 .context("In with_transaction.")
78 .and_then(|tx| f(&tx).map(|result| (result, tx)))
79 .and_then(|(result, tx)| {
80 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
81 Ok(result)
82 }) {
83 Ok(result) => break Ok(result),
84 Err(e) => {
85 if Self::is_locked_error(&e) {
86 std::thread::sleep(std::time::Duration::from_micros(500));
87 continue;
88 } else {
89 return Err(e).context("In with_transaction.");
90 }
91 }
92 }
93 }
94 }
95
96 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070097 matches!(
98 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
99 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
100 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
101 )
Janis Danisevskis77d72042021-01-20 15:36:30 -0800102 }
103
104 fn init_tables(&mut self) -> Result<()> {
105 self.with_transaction(TransactionBehavior::Immediate, |tx| {
106 tx.execute(
107 "CREATE TABLE IF NOT EXISTS profiles (
108 owner INTEGER,
109 alias BLOB,
110 profile BLOB,
111 UNIQUE(owner, alias));",
112 NO_PARAMS,
113 )
114 .context("Failed to initialize \"profiles\" table.")?;
115 Ok(())
116 })
117 }
118
119 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
120 self.with_transaction(TransactionBehavior::Deferred, |tx| {
121 let mut stmt = tx
122 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
123 .context("In list: Failed to prepare statement.")?;
124
125 let aliases = stmt
126 .query_map(params![caller_uid], |row| row.get(0))?
127 .collect::<rusqlite::Result<Vec<String>>>()
128 .context("In list: query_map failed.");
129 aliases
130 })
131 }
132
133 fn put(&mut self, caller_uid: u32, alias: &str, profile: &[u8]) -> Result<()> {
134 self.with_transaction(TransactionBehavior::Immediate, |tx| {
135 tx.execute(
136 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
137 params![caller_uid, alias, profile,],
138 )
139 .context("In put: Failed to insert or replace.")?;
140 Ok(())
141 })
142 }
143
144 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
145 self.with_transaction(TransactionBehavior::Deferred, |tx| {
146 tx.query_row(
147 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
148 params![caller_uid, alias],
149 |row| row.get(0),
150 )
151 .optional()
152 .context("In get: failed loading profile.")
153 })
154 }
155
156 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
157 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
158 tx.execute(
159 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
160 params![caller_uid, alias],
161 )
162 .context("In remove: Failed to delete row.")
163 })?;
164 Ok(removed == 1)
165 }
166}
167
168/// This is the main VpnProfileStore error type, it wraps binder exceptions and the
169/// VnpStore errors.
170#[derive(Debug, thiserror::Error, PartialEq)]
171pub enum Error {
172 /// Wraps a VpnProfileStore error code.
173 #[error("Error::Error({0:?})")]
174 Error(i32),
175 /// Wraps a Binder exception code other than a service specific exception.
176 #[error("Binder exception code {0:?}, {1:?}")]
177 Binder(ExceptionCode, i32),
178}
179
180impl Error {
181 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
182 pub fn sys() -> Self {
183 Error::Error(ERROR_SYSTEM_ERROR)
184 }
185
186 /// Short hand for `Error::Error(ERROR_PROFILE_NOT_FOUND)`
187 pub fn not_found() -> Self {
188 Error::Error(ERROR_PROFILE_NOT_FOUND)
189 }
190}
191
192/// This function should be used by vpnprofilestore service calls to translate error conditions
193/// into service specific exceptions.
194///
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000195/// All error conditions get logged by this function, except for ERROR_PROFILE_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800196///
197/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
198///
199/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
200///
201/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
202/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
203/// typically returns Ok(value).
204fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
205where
206 F: FnOnce(U) -> BinderResult<T>,
207{
208 result.map_or_else(
209 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800210 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000211 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
212 // Make the profile not found errors silent.
213 Some(Error::Error(ERROR_PROFILE_NOT_FOUND)) => (ERROR_PROFILE_NOT_FOUND, false),
214 Some(Error::Error(e)) => (*e, true),
215 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800216 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000217 if log_error {
218 log::error!("{:?}", e);
219 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800220 Err(BinderStatus::new_service_specific_error(rc, None))
221 },
222 handle_ok,
223 )
224}
225
Janis Danisevskis77d72042021-01-20 15:36:30 -0800226/// Implements IVpnProfileStore AIDL interface.
227pub struct VpnProfileStore {
228 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800229 async_task: AsyncTask,
230}
231
232struct AsyncState {
233 recently_imported: HashSet<(u32, String)>,
234 legacy_loader: LegacyBlobLoader,
235 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800236}
237
238impl VpnProfileStore {
239 /// Creates a new VpnProfileStore instance.
Janis Danisevskis06891072021-02-11 10:28:17 -0800240 pub fn new_native_binder(path: &Path) -> Strong<dyn IVpnProfileStore> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800241 let mut db_path = path.to_path_buf();
242 db_path.push("vpnprofilestore.sqlite");
Janis Danisevskis06891072021-02-11 10:28:17 -0800243
244 let result = Self { db_path, async_task: Default::default() };
245 result.init_shelf(path);
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000246 BnVpnProfileStore::new_binder(result, BinderFeatures::default())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800247 }
248
249 fn open_db(&self) -> Result<DB> {
250 DB::new(&self.db_path).context("In open_db: Failed to open db.")
251 }
252
253 fn get(&self, alias: &str) -> Result<Vec<u8>> {
254 let mut db = self.open_db().context("In get.")?;
255 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800256
257 if let Some(profile) =
258 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
259 {
260 return Ok(profile);
261 }
262 if self.get_legacy(calling_uid, alias).context("In get: Trying to migrate legacy blob.")? {
263 // If we were able to migrate a legacy blob try again.
264 if let Some(profile) =
265 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
266 {
267 return Ok(profile);
268 }
269 }
270 Err(Error::not_found()).context("In get: No such profile.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800271 }
272
273 fn put(&self, alias: &str, profile: &[u8]) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800274 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800275 // In order to make sure that we don't have stale legacy profiles, make sure they are
276 // migrated before replacing them.
277 let _ = self.get_legacy(calling_uid, alias);
278 let mut db = self.open_db().context("In put.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800279 db.put(calling_uid, alias, profile).context("In put: Trying to insert profile into DB.")
280 }
281
282 fn remove(&self, alias: &str) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800283 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800284 let mut db = self.open_db().context("In remove.")?;
285 // In order to make sure that we don't have stale legacy profiles, make sure they are
286 // migrated before removing them.
287 let _ = self.get_legacy(calling_uid, alias);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800288 let removed = db
289 .remove(calling_uid, alias)
290 .context("In remove: Trying to remove profile from DB.")?;
291 if removed {
292 Ok(())
293 } else {
294 Err(Error::not_found()).context("In remove: No such profile.")
295 }
296 }
297
298 fn list(&self, prefix: &str) -> Result<Vec<String>> {
299 let mut db = self.open_db().context("In list.")?;
300 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800301 let mut result = self.list_legacy(calling_uid).context("In list.")?;
302 result
303 .append(&mut db.list(calling_uid).context("In list: Trying to get list of profiles.")?);
304 result = result.into_iter().filter(|s| s.starts_with(prefix)).collect();
305 result.sort_unstable();
306 result.dedup();
307 Ok(result)
308 }
309
310 fn init_shelf(&self, path: &Path) {
311 let mut db_path = path.to_path_buf();
312 self.async_task.queue_hi(move |shelf| {
313 let legacy_loader = LegacyBlobLoader::new(&db_path);
314 db_path.push("vpnprofilestore.sqlite");
315
316 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
317 })
318 }
319
320 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
321 where
322 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
323 {
324 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
325 self.async_task.queue_hi(move |shelf| {
326 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
327 sender.send(f(state)).expect("Failed to send result.");
328 });
329 receiver.recv().context("In do_serialized: Failed to receive result.")?
330 }
331
332 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
333 self.do_serialized(move |state| {
334 state
335 .legacy_loader
336 .list_vpn_profiles(uid)
337 .context("Trying to list legacy vnp profiles.")
338 })
339 .context("In list_legacy.")
340 }
341
342 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
343 let alias = alias.to_string();
344 self.do_serialized(move |state| {
345 if state.recently_imported.contains(&(uid, alias.clone())) {
346 return Ok(true);
347 }
348 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
349 let migrated =
350 Self::migrate_one_legacy_profile(uid, &alias, &state.legacy_loader, &mut db)
351 .context("Trying to migrate legacy vpn profile.")?;
352 if migrated {
353 state.recently_imported.insert((uid, alias));
354 }
355 Ok(migrated)
356 })
357 .context("In get_legacy.")
358 }
359
360 fn migrate_one_legacy_profile(
361 uid: u32,
362 alias: &str,
363 legacy_loader: &LegacyBlobLoader,
364 db: &mut DB,
365 ) -> Result<bool> {
366 let blob = legacy_loader
367 .read_vpn_profile(uid, alias)
368 .context("In migrate_one_legacy_profile: Trying to read legacy vpn profile.")?;
369 if let Some(profile) = blob {
370 db.put(uid, alias, &profile)
371 .context("In migrate_one_legacy_profile: Trying to insert profile into DB.")?;
372 legacy_loader
373 .remove_vpn_profile(uid, alias)
374 .context("In migrate_one_legacy_profile: Trying to delete legacy profile.")?;
375 Ok(true)
376 } else {
377 Ok(false)
378 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800379 }
380}
381
382impl binder::Interface for VpnProfileStore {}
383
384impl IVpnProfileStore for VpnProfileStore {
385 fn get(&self, alias: &str) -> BinderResult<Vec<u8>> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000386 let _wp = wd::watch_millis("IVpnProfileStore::get", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800387 map_or_log_err(self.get(alias), Ok)
388 }
389 fn put(&self, alias: &str, profile: &[u8]) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000390 let _wp = wd::watch_millis("IVpnProfileStore::put", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800391 map_or_log_err(self.put(alias, profile), Ok)
392 }
393 fn remove(&self, alias: &str) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000394 let _wp = wd::watch_millis("IVpnProfileStore::remove", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800395 map_or_log_err(self.remove(alias), Ok)
396 }
397 fn list(&self, prefix: &str) -> BinderResult<Vec<String>> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000398 let _wp = wd::watch_millis("IVpnProfileStore::list", 500);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800399 map_or_log_err(self.list(prefix), Ok)
400 }
401}
402
403#[cfg(test)]
404mod db_test {
405 use super::*;
406 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700407 use std::sync::Arc;
408 use std::thread;
409 use std::time::Duration;
410 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800411
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700412 static TEST_ALIAS: &str = &"test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800413 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
414 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
415 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
416 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
417
418 #[test]
419 fn test_profile_db() {
420 let test_dir = TempDir::new("profiledb_test_").expect("Failed to create temp dir.");
421 let mut db =
422 DB::new(&test_dir.build().push("vpnprofile.sqlite")).expect("Failed to open database.");
423
424 // Insert three profiles for owner 2.
425 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
426 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
427 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
428
429 // Check list returns all inserted aliases.
430 assert_eq!(
431 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
432 db.list(2).expect("Failed to list profiles.")
433 );
434
435 // There should be no profiles for owner 1.
436 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list profiles."));
437
438 // Check the content of the three entries.
439 assert_eq!(
440 Some(TEST_BLOB1),
441 db.get(2, "test1").expect("Failed to get profile.").as_deref()
442 );
443 assert_eq!(
444 Some(TEST_BLOB2),
445 db.get(2, "test2").expect("Failed to get profile.").as_deref()
446 );
447 assert_eq!(
448 Some(TEST_BLOB3),
449 db.get(2, "test3").expect("Failed to get profile.").as_deref()
450 );
451
452 // Remove test2 and check and check that it is no longer retrievable.
453 assert!(db.remove(2, "test2").expect("Failed to remove profile."));
454 assert!(db.get(2, "test2").expect("Failed to get profile.").is_none());
455
456 // test2 should now no longer be in the list.
457 assert_eq!(
458 vec!["test1".to_string(), "test3".to_string(),],
459 db.list(2).expect("Failed to list profiles.")
460 );
461
462 // Put on existing alias replaces it.
463 // Verify test1 is TEST_BLOB1.
464 assert_eq!(
465 Some(TEST_BLOB1),
466 db.get(2, "test1").expect("Failed to get profile.").as_deref()
467 );
468 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
469 // Verify test1 is TEST_BLOB4.
470 assert_eq!(
471 Some(TEST_BLOB4),
472 db.get(2, "test1").expect("Failed to get profile.").as_deref()
473 );
474 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700475
476 #[test]
477 fn concurrent_vpn_profile_test() -> Result<()> {
478 let temp_dir = Arc::new(
479 TempDir::new("concurrent_vpn_profile_test_").expect("Failed to create temp dir."),
480 );
481
482 let db_path = temp_dir.build().push("vpnprofile.sqlite").to_owned();
483
484 let test_begin = Instant::now();
485
486 let mut db = DB::new(&db_path).expect("Failed to open database.");
487 const PROFILE_COUNT: u32 = 5000u32;
488 const PROFILE_DB_COUNT: u32 = 5000u32;
489
Seth Moore472fcbb2021-05-12 10:07:51 -0700490 let mode: String = db.conn.pragma_query_value(None, "journal_mode", |row| row.get(0))?;
491 assert_eq!(mode, "wal");
492
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700493 let mut actual_profile_count = PROFILE_COUNT;
494 // First insert PROFILE_COUNT profiles.
495 for count in 0..PROFILE_COUNT {
496 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
497 actual_profile_count = count;
498 break;
499 }
500 let alias = format!("test_alias_{}", count);
501 db.put(1, &alias, TEST_BLOB1).expect("Failed to add profile (1).");
502 }
503
504 // Insert more keys from a different thread and into a different namespace.
505 let db_path1 = db_path.clone();
506 let handle1 = thread::spawn(move || {
507 let mut db = DB::new(&db_path1).expect("Failed to open database.");
508
509 for count in 0..actual_profile_count {
510 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
511 return;
512 }
513 let alias = format!("test_alias_{}", count);
514 db.put(2, &alias, TEST_BLOB2).expect("Failed to add profile (2).");
515 }
516
517 // Then delete them again.
518 for count in 0..actual_profile_count {
519 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
520 return;
521 }
522 let alias = format!("test_alias_{}", count);
523 db.remove(2, &alias).expect("Remove Failed (2).");
524 }
525 });
526
527 // And start deleting the first set of profiles.
528 let db_path2 = db_path.clone();
529 let handle2 = thread::spawn(move || {
530 let mut db = DB::new(&db_path2).expect("Failed to open database.");
531
532 for count in 0..actual_profile_count {
533 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
534 return;
535 }
536 let alias = format!("test_alias_{}", count);
537 db.remove(1, &alias).expect("Remove Failed (1)).");
538 }
539 });
540
541 // While a lot of inserting and deleting is going on we have to open database connections
542 // successfully and then insert and delete a specific profile.
543 let db_path3 = db_path.clone();
544 let handle3 = thread::spawn(move || {
545 for _count in 0..PROFILE_DB_COUNT {
546 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
547 return;
548 }
549 let mut db = DB::new(&db_path3).expect("Failed to open database.");
550
551 db.put(3, &TEST_ALIAS, TEST_BLOB3).expect("Failed to add profile (3).");
552
553 db.remove(3, &TEST_ALIAS).expect("Remove failed (3).");
554 }
555 });
556
557 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
558 // This may yield an entry or none, but it must not fail.
559 let handle4 = thread::spawn(move || {
560 for _count in 0..PROFILE_DB_COUNT {
561 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
562 return;
563 }
564 let mut db = DB::new(&db_path).expect("Failed to open database.");
565
566 // This may return Some or None but it must not fail.
567 db.get(3, &TEST_ALIAS).expect("Failed to get profile (4).");
568 }
569 });
570
571 handle1.join().expect("Thread 1 panicked.");
572 handle2.join().expect("Thread 2 panicked.");
573 handle3.join().expect("Thread 3 panicked.");
574 handle4.join().expect("Thread 4 panicked.");
575
576 Ok(())
577 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800578}