diff --git a/Cargo.lock b/Cargo.lock index ac1c21867..219873a47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -239,9 +239,9 @@ checksum = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" [[package]] name = "autocfg" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" @@ -478,7 +478,7 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", "cfg-if 0.1.10", "crossbeam-utils 0.7.2", "lazy_static", @@ -514,7 +514,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", "cfg-if 0.1.10", "lazy_static", ] @@ -1019,7 +1019,7 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", "hashbrown", ] @@ -1142,10 +1142,11 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.5" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109" +checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" dependencies = [ + "autocfg 1.1.0", "scopeguard 1.1.0", ] @@ -1238,7 +1239,7 @@ version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", ] [[package]] @@ -1274,7 +1275,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" dependencies = [ "adler", - "autocfg 1.0.1", + "autocfg 1.1.0", ] [[package]] @@ -1405,7 +1406,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", "num-traits", ] @@ -1415,7 +1416,7 @@ version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", ] [[package]] @@ -1469,6 +1470,7 @@ dependencies = [ "log 0.4.14", "openssl", "openssl-sys", + "parking_lot 0.12.0", "regex", "rustc-serialize", "serde", @@ -1629,7 +1631,7 @@ version = "0.9.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e46109c383602735fa0a2e48dd2b7c892b048e1bf69e5c3b1d804b7d9c203cb" dependencies = [ - "autocfg 1.0.1", + "autocfg 1.1.0", "cc", "libc", "openssl-src", @@ -1683,10 +1685,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" dependencies = [ "instant", - "lock_api 0.4.5", + "lock_api 0.4.7", "parking_lot_core 0.8.5", ] +[[package]] +name = "parking_lot" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" +dependencies = [ + "lock_api 0.4.7", + "parking_lot_core 0.9.2", +] + [[package]] name = "parking_lot_core" version = "0.4.0" @@ -1729,6 +1741,19 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "parking_lot_core" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "redox_syscall 0.2.10", + "smallvec 1.7.0", + "windows-sys", +] + [[package]] name = "percent-encoding" version = "1.0.1" @@ -3191,6 +3216,49 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-sys" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" + +[[package]] +name = "windows_i686_gnu" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" + +[[package]] +name = "windows_i686_msvc" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" + [[package]] name = "winreg" version = "0.5.1" diff --git a/README.md b/README.md index 25f84899a..cbfe75d6a 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,21 @@ Read the [setup](./docs/setup.md) for instructions on building OPCUA for Rust. Read [cross compilation](./docs/cross-compile.md) for hints for cross compiling OPC UA for Rust to other platforms. -# Migrating from 0.9 and below +# Migration notes + +## Migration from 0.10 and below + +OPC UA for Rust uses synchronization `RwLock` and `Mutex` from the [parking_lot](https://crates.io/crates/parking_lot) crate instead +of `std`. So if you have compiler errors, replace your imports with: + +```rust +use opcua::sync::*; +``` + +They haven't been added to the `opcua::client::prelude` or `opcua::server::prelude` in case +your code uses `std::sync` types for other reasons that you need to resolve manually. + +## Migrating from 0.9 and below OPC UA for Rust is now a single crate instead of many crates as it used to be. This makes it simpler to use, and also maintain and publish. If you are using 0.9 or below, you will have to make some minor adjustments to use the new diff --git a/integration/src/harness.rs b/integration/src/harness.rs index c359b6c1b..8733a2613 100644 --- a/integration/src/harness.rs +++ b/integration/src/harness.rs @@ -4,7 +4,7 @@ use std::{ atomic::{AtomicUsize, Ordering}, mpsc, mpsc::channel, - Arc, Mutex, RwLock, + Arc, }, thread, time, }; @@ -19,6 +19,7 @@ use opcua::{ builder::ServerBuilder, callbacks, config::ServerEndpoint, prelude::*, session::SessionManager, }, + sync::*, }; use crate::*; @@ -217,13 +218,13 @@ pub fn new_server(port: u16) -> Server { // Allow untrusted access to the server { let certificate_store = server.certificate_store(); - let mut certificate_store = certificate_store.write().unwrap(); + let mut certificate_store = certificate_store.write(); certificate_store.set_trust_unknown_certs(true); } { let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Populate the address space with some variables let v1_node = v1_node_id(); @@ -558,7 +559,7 @@ pub fn regular_client_test( let session = client .connect_to_endpoint(client_endpoint, identity_token) .unwrap(); - let session = session.read().unwrap(); + let session = session.read(); // Read the variable let mut values = { @@ -592,7 +593,7 @@ pub fn invalid_session_client_test( let session = client .connect_to_endpoint(client_endpoint, identity_token) .unwrap(); - let session = session.read().unwrap(); + let session = session.read(); // Read the variable and expect that to fail let read_nodes = vec![ReadValueId::from(v1_node_id())]; @@ -643,7 +644,7 @@ pub fn regular_server_test(rx_server_command: mpsc::Receiver, ser // Tell the server to quit { info!("1. ------------------------ Server test received quit"); - let mut server = server2.write().unwrap(); + let mut server = server2.write(); server.abort(); } // wait for server thread to quit @@ -696,7 +697,7 @@ pub fn connect_with_invalid_token( pub fn connect_with( port: u16, - mut client_endpoint: EndpointDescription, + client_endpoint: EndpointDescription, identity_token: IdentityToken, ) { connect_with_client_test( diff --git a/integration/src/tests.rs b/integration/src/tests.rs index c86e732e6..ff20d4a37 100644 --- a/integration/src/tests.rs +++ b/integration/src/tests.rs @@ -1,5 +1,5 @@ use std::{ - sync::{mpsc, mpsc::channel, Arc, RwLock}, + sync::{mpsc, mpsc::channel, Arc}, thread, }; @@ -8,6 +8,7 @@ use log::*; use opcua::client::prelude::*; use opcua::server::prelude::*; +use opcua::sync::*; use crate::harness::*; @@ -139,7 +140,7 @@ fn server_abort() { { // Set the abort flag - server2.write().unwrap().abort(); + server2.write().abort(); } // Wait for the message or timeout to occur @@ -423,7 +424,7 @@ fn read_write_read() { // Read the existing value { - let session = session.read().unwrap(); + let session = session.read(); let results = session .read(&[node_id.clone().into()], TimestampsToReturn::Both, 1.0) .unwrap(); @@ -433,7 +434,7 @@ fn read_write_read() { } { - let session = session.read().unwrap(); + let session = session.read(); let results = session .write(&[WriteValue { node_id: node_id.clone(), @@ -447,7 +448,7 @@ fn read_write_read() { } { - let session = session.read().unwrap(); + let session = session.read(); let results = session .read(&[node_id.into()], TimestampsToReturn::Both, 1.0) .unwrap(); @@ -456,7 +457,7 @@ fn read_write_read() { } { - let session = session.read().unwrap(); + let session = session.read(); session.disconnect(); } }, @@ -481,7 +482,7 @@ fn subscribe_1000() { let session = client .connect_to_endpoint(client_endpoint, identity_token) .unwrap(); - let session = session.read().unwrap(); + let session = session.read(); let start_time = Utc::now(); @@ -558,7 +559,7 @@ fn method_call() { let session = client .connect_to_endpoint(client_endpoint, IdentityToken::Anonymous) .unwrap(); - let session = session.read().unwrap(); + let session = session.read(); // Call the method let input_arguments = Some(vec![Variant::from("Foo")]); diff --git a/lib/Cargo.toml b/lib/Cargo.toml index b421ab7cb..b83eef387 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -43,6 +43,8 @@ http = ["actix-web"] [dependencies] log = "0.4" chrono = { version = "0.4", features = ["serde"] } +# Enable deadlock_detection if there are any deadlocks in sync code +parking_lot = { version = "0.12", features = ["send_guard"] } futures = "0.3" tokio = { version = "1", features = ["full"] } tokio-util = { version = "0.6", features = ["codec"] } diff --git a/lib/src/client/client.rs b/lib/src/client/client.rs index c929d2483..ca2ab0b90 100644 --- a/lib/src/client/client.rs +++ b/lib/src/client/client.rs @@ -4,6 +4,19 @@ //! Client setup and session creation. +use std::{path::PathBuf, str::FromStr, sync::Arc}; + +use chrono::Duration; + +use super::{ + config::{ClientConfig, ClientEndpoint, ANONYMOUS_USER_TOKEN_ID}, + session::{ + services::*, + session::{Session, SessionInfo}, + }, + session_retry_policy::SessionRetryPolicy, +}; + use crate::{ core::{ comms::url::{ @@ -13,6 +26,7 @@ use crate::{ config::Config, }, crypto::{CertificateStore, SecurityPolicy}, + sync::RwLock, trace_read_lock, types::{ service_types::{ApplicationDescription, EndpointDescription, RegisteredServer}, @@ -21,23 +35,6 @@ use crate::{ }, }; -use std::{ - path::PathBuf, - str::FromStr, - sync::{Arc, RwLock}, -}; - -use chrono::Duration; - -use super::{ - config::{ClientConfig, ClientEndpoint, ANONYMOUS_USER_TOKEN_ID}, - session::{ - services::*, - session::{Session, SessionInfo}, - }, - session_retry_policy::SessionRetryPolicy, -}; - #[derive(Debug, Clone)] pub enum IdentityToken { /// Anonymous identity token @@ -221,7 +218,7 @@ impl Client { { // Connect to the server - let mut session = session.write().unwrap(); + let mut session = session.write(); session.connect_and_activate().map_err(|err| { error!("Got an error while creating the default session - {}", err); err @@ -287,7 +284,7 @@ impl Client { { // Connect to the server - let mut session = session.write().unwrap(); + let mut session = session.write(); session.connect_and_activate().map_err(|err| { error!("Got an error while creating the default session - {}", err); err diff --git a/lib/src/client/comms/tcp_transport.rs b/lib/src/client/comms/tcp_transport.rs index 71bb97f09..f1a9e5bc5 100644 --- a/lib/src/client/comms/tcp_transport.rs +++ b/lib/src/client/comms/tcp_transport.rs @@ -11,7 +11,7 @@ use std::{ collections::HashMap, net::{SocketAddr, ToSocketAddrs}, result::Result, - sync::{Arc, Mutex, RwLock}, + sync::Arc, thread, }; @@ -36,6 +36,7 @@ use crate::core::{ prelude::*, RUNTIME, }; +use crate::sync::*; use crate::types::status_code::StatusCode; use crate::{deregister_runtime_component, register_runtime_component}; diff --git a/lib/src/client/mod.rs b/lib/src/client/mod.rs index 9c7028a91..d0ef79618 100644 --- a/lib/src/client/mod.rs +++ b/lib/src/client/mod.rs @@ -36,8 +36,9 @@ //! described in the in docs/client.md tutorial. //! //! ```no_run -//! use std::sync::{Arc, RwLock}; +//! use std::sync::Arc; //! use opcua::client::prelude::*; +//! use opcua::sync::*; //! //! fn main() { //! let mut client = ClientBuilder::new() @@ -64,7 +65,7 @@ //! } //! //! fn subscribe_to_values(session: Arc>) -> Result<(), StatusCode> { -//! let mut session = session.write().unwrap(); +//! let mut session = session.write(); //! // Create a subscription polling every 2s with a callback //! let subscription_id = session.create_subscription(2000.0, 10, 30, 0, 0, true, DataChangeCallback::new(|changed_monitored_items| { //! println!("Data change from server:"); diff --git a/lib/src/client/session/session.rs b/lib/src/client/session/session.rs index 256e7b2ab..2c6a39dff 100644 --- a/lib/src/client/session/session.rs +++ b/lib/src/client/session/session.rs @@ -12,7 +12,7 @@ use std::{ collections::HashSet, result::Result, str::FromStr, - sync::{mpsc::SyncSender, Arc, Mutex, RwLock}, + sync::{mpsc::SyncSender, Arc}, thread, }; @@ -21,8 +21,6 @@ use tokio::{ time::{interval, Duration, Instant}, }; -use crate::{deregister_runtime_component, register_runtime_component}; - use crate::core::{ comms::{ secure_channel::{Role, SecureChannel}, @@ -35,7 +33,9 @@ use crate::crypto::{ self as crypto, user_identity::make_user_name_identity_token, CertificateStore, SecurityPolicy, X509, }; +use crate::sync::*; use crate::types::{node_ids::ObjectId, status_code::StatusCode, *}; +use crate::{deregister_runtime_component, register_runtime_component}; use crate::client::{ callbacks::{OnConnectionStatusChange, OnSessionClosed, OnSubscriptionNotification}, @@ -661,7 +661,7 @@ impl Session { loop { // Poll the session. let poll_result = { - let mut session = session.write().unwrap(); + let mut session = session.write(); session.poll() }; match poll_result { @@ -1062,7 +1062,7 @@ impl Session { /// Returns a string identifier for the session pub(crate) fn session_id(&self) -> String { let session_state = self.session_state(); - let session_state = session_state.read().unwrap(); + let session_state = session_state.read(); format!("session:{}", session_state.id()) } @@ -1619,7 +1619,7 @@ impl SessionService for Session { }; // Create a signature data - // let session_state = self.session_state.lock().unwrap(); + // let session_state = self.session_state.lock(); if client_pkey.is_none() { session_error!(self, "Cannot create client signature - no pkey!"); return Err(StatusCode::BadUnexpectedError); diff --git a/lib/src/client/session/session_state.rs b/lib/src/client/session/session_state.rs index bff0cc0bb..9d6598aef 100644 --- a/lib/src/client/session/session_state.rs +++ b/lib/src/client/session/session_state.rs @@ -6,7 +6,7 @@ use std::{ sync::{ atomic::{AtomicU32, Ordering}, mpsc::{self, Receiver, SyncSender}, - Arc, RwLock, + Arc, }, u32, }; @@ -19,6 +19,7 @@ use crate::core::{ comms::secure_channel::SecureChannel, handle::Handle, supported_message::SupportedMessage, }; use crate::crypto::SecurityPolicy; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::client::{ diff --git a/lib/src/client/subscription.rs b/lib/src/client/subscription.rs index 5fd7525f0..83c7e1e3e 100644 --- a/lib/src/client/subscription.rs +++ b/lib/src/client/subscription.rs @@ -15,9 +15,10 @@ use std::{ collections::{BTreeSet, HashMap, HashSet}, marker::Sync, - sync::{Arc, Mutex}, + sync::Arc, }; +use crate::sync::*; use crate::types::{ service_types::{DataChangeNotification, ReadValueId}, *, diff --git a/lib/src/core/comms/secure_channel.rs b/lib/src/core/comms/secure_channel.rs index 23e2673e5..8c601538e 100644 --- a/lib/src/core/comms/secure_channel.rs +++ b/lib/src/core/comms/secure_channel.rs @@ -5,7 +5,7 @@ use std::{ io::{Cursor, Write}, ops::Range, - sync::{Arc, RwLock}, + sync::Arc, }; use chrono::Duration; @@ -17,6 +17,7 @@ use crate::crypto::{ x509::X509, CertificateStore, SecurityPolicy, }; +use crate::sync::*; use crate::types::{ service_types::ChannelSecurityToken, status_code::StatusCode, write_bytes, write_u8, BinaryEncoder, ByteString, DateTime, DecodingOptions, MessageSecurityMode, @@ -104,7 +105,7 @@ impl SecureChannel { decoding_options: DecodingOptions, ) -> SecureChannel { let (cert, private_key) = { - let certificate_store = certificate_store.read().unwrap(); + let certificate_store = certificate_store.read(); if let Ok((cert, pkey)) = certificate_store.read_own_cert_and_pkey() { (Some(cert), Some(pkey)) } else { diff --git a/lib/src/core/comms/tcp_codec.rs b/lib/src/core/comms/tcp_codec.rs index 0217feae2..d506e56bf 100644 --- a/lib/src/core/comms/tcp_codec.rs +++ b/lib/src/core/comms/tcp_codec.rs @@ -12,11 +12,12 @@ //! * OPN - Open Secure Channel message //! * CLO - Close Secure Channel message use std::io; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use bytes::{BufMut, BytesMut}; use tokio_util::codec::{Decoder, Encoder}; +use crate::sync::*; use crate::types::{ encoding::{BinaryEncoder, DecodingOptions}, status_code::StatusCode, @@ -124,7 +125,7 @@ impl TcpCodec { } fn is_abort(&self) -> bool { - let abort = self.abort.read().unwrap(); + let abort = self.abort.read(); *abort } diff --git a/lib/src/core/fuzz/fuzz_targets/fuzz_comms.rs b/lib/src/core/fuzz/fuzz_targets/fuzz_comms.rs index 0edd70543..cee7f34f4 100644 --- a/lib/src/core/fuzz/fuzz_targets/fuzz_comms.rs +++ b/lib/src/core/fuzz/fuzz_targets/fuzz_comms.rs @@ -1,7 +1,7 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use bytes::BytesMut; use tokio_util::codec::Decoder; diff --git a/lib/src/core/runtime.rs b/lib/src/core/runtime.rs index 74166975e..2c6cd2c32 100644 --- a/lib/src/core/runtime.rs +++ b/lib/src/core/runtime.rs @@ -2,11 +2,9 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::{ - collections::BTreeSet, - sync::{Arc, Mutex}, -}; +use std::{collections::BTreeSet, sync::Arc}; +use crate::sync::*; use crate::trace_lock; /// The `Runtime` is for debugging / diagnostics purposes and tracks which substantial system objects diff --git a/lib/src/lib.rs b/lib/src/lib.rs index c5f5d511e..e4077a4e5 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -15,6 +15,13 @@ extern crate serde_json; #[macro_use] extern crate derivative; +// Synchronization structs. This is a wrapper mod around `parking_lot` types so opcua users don't have +// to reference that other crate. +pub mod sync { + pub type RwLock = parking_lot::RwLock; + pub type Mutex = parking_lot::Mutex; +} + /// Tracing macro for obtaining a lock on a `Mutex`. Sometimes deadlocks can happen in code, /// and if they do, this macro is useful for finding out where they happened. #[macro_export] @@ -23,7 +30,7 @@ macro_rules! trace_lock { { // use std::thread; // trace!("Thread {:?}, {} locking at {}, line {}", thread::current().id(), stringify!($x), file!(), line!()); - let v = $x.lock().unwrap(); + let v = $x.lock(); // trace!("Thread {:?}, {} lock completed", thread::current().id(), stringify!($x)); v } @@ -37,7 +44,7 @@ macro_rules! trace_read_lock { { // use std::thread; // trace!("Thread {:?}, {} read locking at {}, line {}", thread::current().id(), stringify!($x), file!(), line!()); - let v = $x.read().unwrap(); + let v = $x.read(); // trace!("Thread {:?}, {} read lock completed", thread::current().id(), stringify!($x)); v } @@ -51,7 +58,7 @@ macro_rules! trace_write_lock { { // use std::thread; // trace!("Thread {:?}, {} write locking at {}, line {}", thread::current().id(), stringify!($x), file!(), line!()); - let v = $x.write().unwrap(); + let v = $x.write(); // trace!("Thread {:?}, {} write lock completed", thread::current().id(), stringify!($x)); v } diff --git a/lib/src/server/address_space/address_space.rs b/lib/src/server/address_space/address_space.rs index 9f238bbbc..7ea0b3a60 100644 --- a/lib/src/server/address_space/address_space.rs +++ b/lib/src/server/address_space/address_space.rs @@ -4,10 +4,11 @@ //! Implementation of `AddressSpace`. use std::collections::HashMap; -use std::sync::{Arc, Mutex, RwLock}; +use std::sync::Arc; use chrono::Utc; +use crate::sync::*; use crate::types::{ node_ids::VariableId::*, service_types::{BrowseDirection, CallMethodRequest, CallMethodResult, NodeClass}, @@ -104,7 +105,7 @@ macro_rules! server_diagnostics_summary { $address_space.set_variable_getter( $variable_id, move |_, timestamps_to_return, _, _, _, _| { - let server_diagnostics = server_diagnostics.read().unwrap(); + let server_diagnostics = server_diagnostics.read(); let server_diagnostics_summary = server_diagnostics.server_diagnostics_summary(); debug!( diff --git a/lib/src/server/address_space/method.rs b/lib/src/server/address_space/method.rs index 88db69f1f..75cf47784 100644 --- a/lib/src/server/address_space/method.rs +++ b/lib/src/server/address_space/method.rs @@ -4,8 +4,9 @@ //! Contains the implementation of `Method` and `MethodBuilder`. -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use crate::sync::*; use crate::types::service_types::{Argument, MethodAttributes}; use super::{ diff --git a/lib/src/server/address_space/method_impls.rs b/lib/src/server/address_space/method_impls.rs index b2e7a9473..a83f00ccd 100644 --- a/lib/src/server/address_space/method_impls.rs +++ b/lib/src/server/address_space/method_impls.rs @@ -2,8 +2,9 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use crate::sync::*; use crate::types::{ service_types::{CallMethodRequest, CallMethodResult}, status_code::StatusCode, diff --git a/lib/src/server/address_space/mod.rs b/lib/src/server/address_space/mod.rs index 1dc05d60b..105d582e8 100644 --- a/lib/src/server/address_space/mod.rs +++ b/lib/src/server/address_space/mod.rs @@ -5,11 +5,9 @@ //! Provides functionality to create an address space, find nodes, add nodes, change attributes //! and values on nodes. -use std::{ - result::Result, - sync::{Arc, Mutex}, -}; +use std::{result::Result, sync::Arc}; +use crate::sync::*; use crate::types::status_code::StatusCode; use crate::types::{ AttributeId, DataValue, NodeId, NumericRange, QualifiedName, TimestampsToReturn, diff --git a/lib/src/server/address_space/variable.rs b/lib/src/server/address_space/variable.rs index 9ae11fab5..a65ebd547 100644 --- a/lib/src/server/address_space/variable.rs +++ b/lib/src/server/address_space/variable.rs @@ -5,8 +5,9 @@ //! Contains the implementation of `Variable` and `VariableBuilder`. use std::convert::{Into, TryFrom}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use crate::sync::*; use crate::types::service_types::VariableAttributes; use crate::server::{ @@ -463,7 +464,7 @@ impl Variable { use std::i32; if let Some(ref value_getter) = self.value_getter { - let mut value_getter = value_getter.lock().unwrap(); + let mut value_getter = value_getter.lock(); value_getter .get( &self.node_id(), @@ -533,7 +534,7 @@ impl Variable { // The value is set to the value getter if let Some(ref value_setter) = self.value_setter { - let mut value_setter = value_setter.lock().unwrap(); + let mut value_setter = value_setter.lock(); value_setter.set( &self.node_id(), AttributeId::Value, diff --git a/lib/src/server/callbacks.rs b/lib/src/server/callbacks.rs index 38e20ac49..e789aee5d 100644 --- a/lib/src/server/callbacks.rs +++ b/lib/src/server/callbacks.rs @@ -4,8 +4,9 @@ //! Callbacks that a server implementation may register with the library -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use crate::sync::*; use crate::types::{ service_types::{CallMethodRequest, CallMethodResult, TimestampsToReturn}, status_code::StatusCode, diff --git a/lib/src/server/comms/tcp_transport.rs b/lib/src/server/comms/tcp_transport.rs index 984528c7f..5dbecdefb 100644 --- a/lib/src/server/comms/tcp_transport.rs +++ b/lib/src/server/comms/tcp_transport.rs @@ -9,11 +9,7 @@ //! responses. i.e. the client is expected to call and wait for a response to their request. //! Publish requests are sent based on the number of subscriptions and the responses / handling are //! left to asynchronous event handlers. -use std::{ - collections::VecDeque, - net::SocketAddr, - sync::{Arc, Mutex, RwLock}, -}; +use std::{collections::VecDeque, net::SocketAddr, sync::Arc}; use chrono::{self, Utc}; use futures::StreamExt; @@ -29,8 +25,6 @@ use tokio::{ }; use tokio_util::codec::FramedRead; -use crate::{deregister_runtime_component, register_runtime_component}; - use crate::core::{ comms::{ message_writer::MessageWriter, @@ -41,7 +35,9 @@ use crate::core::{ RUNTIME, }; use crate::crypto::CertificateStore; +use crate::sync::*; use crate::types::status_code::StatusCode; +use crate::{deregister_runtime_component, register_runtime_component}; use crate::server::{ address_space::types::AddressSpace, diff --git a/lib/src/server/comms/transport.rs b/lib/src/server/comms/transport.rs index 448704ede..49a0369c1 100644 --- a/lib/src/server/comms/transport.rs +++ b/lib/src/server/comms/transport.rs @@ -6,11 +6,9 @@ //! Provides a level of abstraction for the server to call through when it doesn't require specific //! knowledge of the transport it is using. -use std::{ - net::SocketAddr, - sync::{Arc, RwLock}, -}; +use std::{net::SocketAddr, sync::Arc}; +use crate::sync::*; use crate::types::status_code::StatusCode; use crate::server::session::SessionManager; diff --git a/lib/src/server/continuation_point.rs b/lib/src/server/continuation_point.rs index 1c2882a28..184b0c3cb 100644 --- a/lib/src/server/continuation_point.rs +++ b/lib/src/server/continuation_point.rs @@ -4,8 +4,9 @@ //! Provides a browse continuation point type for tracking a browse operation initiated by a client. -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use crate::sync::*; use crate::types::{service_types::ReferenceDescription, ByteString, DateTimeUtc}; use crate::prelude::AddressSpace; diff --git a/lib/src/server/events/audit/mod.rs b/lib/src/server/events/audit/mod.rs index 03717d3c5..6c2d7abab 100644 --- a/lib/src/server/events/audit/mod.rs +++ b/lib/src/server/events/audit/mod.rs @@ -8,8 +8,9 @@ //! builder functions on each type in the hierarchy. They're not optimal at all (impls call base impls call base impls in some cases), //! but they should suffice for the purpose they'll be used for. -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use crate::sync::*; use crate::types::*; use crate::server::{address_space::address_space::AddressSpace, events::event::Event}; diff --git a/lib/src/server/historical/mod.rs b/lib/src/server/historical/mod.rs index 2454077e3..c2496133c 100644 --- a/lib/src/server/historical/mod.rs +++ b/lib/src/server/historical/mod.rs @@ -2,11 +2,9 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::{ - result::Result, - sync::{Arc, RwLock}, -}; +use std::{result::Result, sync::Arc}; +use crate::sync::*; use crate::types::status_code::StatusCode; use crate::types::*; diff --git a/lib/src/server/http/mod.rs b/lib/src/server/http/mod.rs index ffbf0cf96..72e63dccc 100644 --- a/lib/src/server/http/mod.rs +++ b/lib/src/server/http/mod.rs @@ -4,14 +4,15 @@ use std::{ path::PathBuf, - sync::{mpsc, Arc, RwLock}, + sync::{mpsc, Arc}, thread, }; use actix_web::{actix, fs, http, server, App, HttpRequest, HttpResponse, Responder}; - use tokio::time::{interval_at, Duration, Instant}; +use crate::sync::*; + use crate::server::{metrics::ServerMetrics, server::Connections, state::ServerState}; /// This is our metrics service, the thing called to handle requests coming from hyper @@ -26,7 +27,7 @@ fn abort(req: &HttpRequest) -> impl Responder { if cfg!(debug_assertions) { let state = req.state(); // Abort the server from the command - let mut server_state = state.server_state.write().unwrap(); + let mut server_state = state.server_state.write(); server_state.abort(); HttpResponse::Ok().content_type("text/plain").body("OK") } else { @@ -47,17 +48,17 @@ fn metrics(req: &HttpRequest) -> impl Responder { // Careful with the ordering here to avoid potential deadlock. Metrics are locked // several times in scope to avoid deadlocks issues. { - let server_state = state.server_state.read().unwrap(); - let mut server_metrics = state.server_metrics.write().unwrap(); + let server_state = state.server_state.read(); + let mut server_metrics = state.server_metrics.write(); server_metrics.update_from_server_state(&server_state); } // Take a copy of connections let connections = { - let connections = state.connections.read().unwrap(); + let connections = state.connections.read(); connections.clone() }; - let mut server_metrics = state.server_metrics.write().unwrap(); + let mut server_metrics = state.server_metrics.write(); server_metrics.update_from_connections(connections); serde_json::to_string_pretty(server_metrics.deref()).unwrap() }; diff --git a/lib/src/server/metrics.rs b/lib/src/server/metrics.rs index 1f14922ee..b83355b08 100644 --- a/lib/src/server/metrics.rs +++ b/lib/src/server/metrics.rs @@ -7,7 +7,6 @@ //! and when subscriptions / monitored items are added, removed. use crate::runtime_components; - use crate::types::DateTime; use crate::server::{ diff --git a/lib/src/server/server.rs b/lib/src/server/server.rs index 5d302c7b5..89c2cca3e 100644 --- a/lib/src/server/server.rs +++ b/lib/src/server/server.rs @@ -4,11 +4,7 @@ //! Provides the [`Server`] type and functionality related to it. -use std::{ - marker::Sync, - net::SocketAddr, - sync::{Arc, RwLock}, -}; +use std::{marker::Sync, net::SocketAddr, panic::AssertUnwindSafe, sync::Arc}; use tokio::{ self, @@ -19,6 +15,7 @@ use tokio::{ use crate::core::{config::Config, prelude::*}; use crate::crypto::*; +use crate::sync::*; use crate::types::service_types::ServerState as ServerStateType; use crate::server::{ @@ -433,7 +430,7 @@ impl Server { // Try to obtain the lock on the transport and the session and check if session is terminated // if it is, then we'll use its termination status to sweep it out. let lock = transport.try_read(); - if let Ok(ref transport) = lock { + if let Some(ref transport) = lock { let session_manager = transport.session_manager(); let session_manager = trace_read_lock!(session_manager); !session_manager.sessions_terminated() @@ -515,7 +512,6 @@ impl Server { #[cfg(feature = "discovery-server-registration")] fn start_discovery_server_registration_timer(&self, discovery_server_url: &str) { use crate::server::discovery; - use std::sync::Mutex; let discovery_server_url = discovery_server_url.to_string(); info!( @@ -560,7 +556,7 @@ impl Server { let server_state = server_state.clone(); let discovery_server_url = discovery_server_url.clone(); let _ = std::thread::spawn(move || { - let _ = std::panic::catch_unwind(move || { + let _ = std::panic::catch_unwind(AssertUnwindSafe(move || { let server_state = trace_read_lock!(server_state); if server_state.is_running() { discovery::register_with_discovery_server( @@ -568,7 +564,7 @@ impl Server { &server_state, ); } - }); + })); }); } } diff --git a/lib/src/server/services/attribute.rs b/lib/src/server/services/attribute.rs index 3b86f0134..87df8a5c9 100644 --- a/lib/src/server/services/attribute.rs +++ b/lib/src/server/services/attribute.rs @@ -2,13 +2,11 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::{ - result::Result, - sync::{Arc, RwLock}, -}; +use std::{result::Result, sync::Arc}; use crate::{ core::supported_message::SupportedMessage, + sync::*, types::{status_code::StatusCode, *}, }; diff --git a/lib/src/server/services/audit.rs b/lib/src/server/services/audit.rs index 6291af9ff..83213f5f1 100644 --- a/lib/src/server/services/audit.rs +++ b/lib/src/server/services/audit.rs @@ -2,8 +2,9 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::prelude::SecureChannel; diff --git a/lib/src/server/services/discovery.rs b/lib/src/server/services/discovery.rs index a6c980484..7c53141fc 100644 --- a/lib/src/server/services/discovery.rs +++ b/lib/src/server/services/discovery.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::{config::Config, supported_message::SupportedMessage}; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::state::ServerState; diff --git a/lib/src/server/services/message_handler.rs b/lib/src/server/services/message_handler.rs index 3d68bad66..704fb6ef8 100644 --- a/lib/src/server/services/message_handler.rs +++ b/lib/src/server/services/message_handler.rs @@ -2,14 +2,14 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use chrono::Utc; use crate::core::comms::secure_channel::SecureChannel; use crate::core::supported_message::SupportedMessage; - use crate::crypto::CertificateStore; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/method.rs b/lib/src/server/services/method.rs index 9b900787b..43b3faa80 100644 --- a/lib/src/server/services/method.rs +++ b/lib/src/server/services/method.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::supported_message::SupportedMessage; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/monitored_item.rs b/lib/src/server/services/monitored_item.rs index fe706d6b7..fc8b2b07c 100644 --- a/lib/src/server/services/monitored_item.rs +++ b/lib/src/server/services/monitored_item.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::supported_message::SupportedMessage; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/node_management.rs b/lib/src/server/services/node_management.rs index fadec71cb..8a276dec3 100644 --- a/lib/src/server/services/node_management.rs +++ b/lib/src/server/services/node_management.rs @@ -2,12 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::{ - result::Result, - sync::{Arc, RwLock}, -}; +use std::{result::Result, sync::Arc}; use crate::core::supported_message::SupportedMessage; +use crate::sync::*; use crate::types::{node_ids::ObjectId, status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/query.rs b/lib/src/server/services/query.rs index fbd786396..c20776f5a 100644 --- a/lib/src/server/services/query.rs +++ b/lib/src/server/services/query.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::supported_message::SupportedMessage; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/session.rs b/lib/src/server/services/session.rs index 839e947d6..10815455d 100644 --- a/lib/src/server/services/session.rs +++ b/lib/src/server/services/session.rs @@ -2,11 +2,12 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::comms::secure_channel::SecureChannel; use crate::core::supported_message::SupportedMessage; use crate::crypto::{self as crypto, random, CertificateStore, SecurityPolicy}; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/subscription.rs b/lib/src/server/services/subscription.rs index 9554063eb..b7d7714ef 100644 --- a/lib/src/server/services/subscription.rs +++ b/lib/src/server/services/subscription.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::supported_message::SupportedMessage; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/services/view.rs b/lib/src/server/services/view.rs index 14acb37f2..f070ea93a 100644 --- a/lib/src/server/services/view.rs +++ b/lib/src/server/services/view.rs @@ -3,10 +3,11 @@ // Copyright (C) 2017-2022 Adam Lock use std::result::Result; -use std::sync::{Arc, Mutex, RwLock}; +use std::sync::Arc; use crate::core::supported_message::SupportedMessage; use crate::crypto::random; +use crate::sync::*; use crate::types::{node_ids::ReferenceTypeId, status_code::StatusCode, *}; use crate::server::{ @@ -16,7 +17,6 @@ use crate::server::{ session::Session, state::ServerState, }; - /// The view service. Allows the client to browse the address space of the server. pub(crate) struct ViewService; @@ -480,7 +480,7 @@ impl ViewService { "Browsing from continuation point {}", continuation_point.id.as_base64() ); - let reference_descriptions = continuation_point.reference_descriptions.lock().unwrap(); + let reference_descriptions = continuation_point.reference_descriptions.lock(); // Use the existing result. This may result in another continuation point being created Self::reference_description_to_browse_result( session, diff --git a/lib/src/server/session.rs b/lib/src/server/session.rs index 4cb5ffe8e..ebac268ec 100644 --- a/lib/src/server/session.rs +++ b/lib/src/server/session.rs @@ -5,13 +5,14 @@ use std::{ collections::{HashMap, HashSet, VecDeque}, sync::{ atomic::{AtomicI32, Ordering}, - Arc, RwLock, + Arc, }, }; use chrono::Utc; use crate::crypto::X509; +use crate::sync::*; use crate::types::{service_types::PublishRequest, status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/state.rs b/lib/src/server/state.rs index 1670dd467..73b488e93 100644 --- a/lib/src/server/state.rs +++ b/lib/src/server/state.rs @@ -4,10 +4,11 @@ //! Provides server state information, such as status, configuration, running servers and so on. -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::core::prelude::*; use crate::crypto::{user_identity, PrivateKey, SecurityPolicy, X509}; +use crate::sync::*; use crate::types::{ profiles, service_types::{ diff --git a/lib/src/server/subscriptions/subscription.rs b/lib/src/server/subscriptions/subscription.rs index d5a9b7545..c6252906f 100644 --- a/lib/src/server/subscriptions/subscription.rs +++ b/lib/src/server/subscriptions/subscription.rs @@ -3,8 +3,9 @@ // Copyright (C) 2017-2022 Adam Lock use std::collections::{BTreeSet, HashMap, VecDeque}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use crate::sync::*; use crate::types::{ service_types::{ MonitoredItemCreateRequest, MonitoredItemCreateResult, MonitoredItemModifyRequest, diff --git a/lib/src/server/tests/address_space.rs b/lib/src/server/tests/address_space.rs index 50e46913b..585dd59a2 100644 --- a/lib/src/server/tests/address_space.rs +++ b/lib/src/server/tests/address_space.rs @@ -1,4 +1,4 @@ -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::server::{ address_space::{ diff --git a/lib/src/server/tests/mod.rs b/lib/src/server/tests/mod.rs index 890425b35..c8a812fcc 100644 --- a/lib/src/server/tests/mod.rs +++ b/lib/src/server/tests/mod.rs @@ -1,12 +1,10 @@ -use std::{ - path::PathBuf, - sync::{Arc, RwLock}, -}; +use std::{path::PathBuf, sync::Arc}; use chrono; use time; use crate::core::{config::Config, supported_message::SupportedMessage}; +use crate::sync::*; use crate::types::{status_code::StatusCode, *}; use crate::server::{ diff --git a/lib/src/server/tests/services/attribute.rs b/lib/src/server/tests/services/attribute.rs index 5a42b0d32..097756902 100644 --- a/lib/src/server/tests/services/attribute.rs +++ b/lib/src/server/tests/services/attribute.rs @@ -2,6 +2,7 @@ use chrono::Duration; use crate::server::{address_space::AccessLevel, services::attribute::AttributeService}; use crate::supported_message_as; +use crate::sync::*; use crate::types::{Variant, WriteMask}; use super::*; @@ -667,7 +668,7 @@ fn history_read_nothing_history_operation_invalid() { fn history_read_nothing_data_provider() { do_attribute_service_test(|server_state, session, address_space, ats| { { - let mut server_state = server_state.write().unwrap(); + let mut server_state = server_state.write(); let data_provider = DataProvider; server_state.set_historical_data_provider(Box::new(data_provider)); } @@ -799,7 +800,7 @@ fn history_update_data_provider() { do_attribute_service_test(|server_state, session, address_space, ats| { // Register a data provider { - let mut server_state = server_state.write().unwrap(); + let mut server_state = server_state.write(); let data_provider = DataProvider; server_state.set_historical_data_provider(Box::new(data_provider)); } diff --git a/lib/src/server/tests/services/discovery.rs b/lib/src/server/tests/services/discovery.rs index ee3cd36b6..1553b493e 100644 --- a/lib/src/server/tests/services/discovery.rs +++ b/lib/src/server/tests/services/discovery.rs @@ -1,5 +1,6 @@ use crate::server::services::discovery::DiscoveryService; use crate::supported_message_as; +use crate::sync::*; use crate::types::UAString; use super::*; diff --git a/lib/src/server/tests/services/method.rs b/lib/src/server/tests/services/method.rs index 3993a9b5b..2ffbc02f7 100644 --- a/lib/src/server/tests/services/method.rs +++ b/lib/src/server/tests/services/method.rs @@ -1,4 +1,5 @@ use crate::supported_message_as; +use crate::sync::*; use crate::types::{ node_ids::{MethodId, ObjectId}, service_types::{CallMethodRequest, CallMethodResult, CallRequest, CallResponse}, diff --git a/lib/src/server/tests/services/mod.rs b/lib/src/server/tests/services/mod.rs index 509e97fab..1b7ac4c5e 100644 --- a/lib/src/server/tests/services/mod.rs +++ b/lib/src/server/tests/services/mod.rs @@ -1,4 +1,4 @@ -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::server::{ prelude::*, diff --git a/lib/src/server/tests/services/node_management.rs b/lib/src/server/tests/services/node_management.rs index e95ff301a..23a8e9ba5 100644 --- a/lib/src/server/tests/services/node_management.rs +++ b/lib/src/server/tests/services/node_management.rs @@ -1,5 +1,6 @@ use crate::server::services::node_management::NodeManagementService; use crate::supported_message_as; +use crate::sync::*; use crate::types::node_ids::{DataTypeId, MethodId, ObjectId, ObjectTypeId, ReferenceTypeId}; use super::*; diff --git a/lib/src/server/tests/services/session.rs b/lib/src/server/tests/services/session.rs index 8792ab2c6..e588386ce 100644 --- a/lib/src/server/tests/services/session.rs +++ b/lib/src/server/tests/services/session.rs @@ -49,7 +49,7 @@ where #[test] fn anonymous_user_token() { do_session_service_test(None, |server_state, session_service| { - let server_state = server_state.read().unwrap(); + let server_state = server_state.read(); // Makes an anonymous token and sticks it into an extension object let token = AnonymousIdentityToken { @@ -149,7 +149,7 @@ fn user_name_pass_token() { |server_state, session_service| { let server_nonce = random::byte_string(20); - let server_state = server_state.read().unwrap(); + let server_state = server_state.read(); let server_cert = server_state.server_certificate.clone(); assert!(server_cert.is_some()); diff --git a/lib/src/server/tests/services/subscription.rs b/lib/src/server/tests/services/subscription.rs index 7c3b33302..384444aee 100644 --- a/lib/src/server/tests/services/subscription.rs +++ b/lib/src/server/tests/services/subscription.rs @@ -9,6 +9,7 @@ use crate::server::{ subscriptions::subscription::*, }; use crate::supported_message_as; +use crate::sync::*; use super::*; diff --git a/lib/src/server/tests/services/view.rs b/lib/src/server/tests/services/view.rs index b761f70b4..dc5575e55 100644 --- a/lib/src/server/tests/services/view.rs +++ b/lib/src/server/tests/services/view.rs @@ -2,6 +2,7 @@ use std::sync::Weak; use crate::server::services::view::ViewService; use crate::supported_message_as; +use crate::sync::*; use super::*; diff --git a/lib/src/server/tests/subscriptions/subscription.rs b/lib/src/server/tests/subscriptions/subscription.rs index 77e234d72..f3aecd889 100644 --- a/lib/src/server/tests/subscriptions/subscription.rs +++ b/lib/src/server/tests/subscriptions/subscription.rs @@ -1,4 +1,4 @@ -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use crate::server::{ diagnostics::ServerDiagnostics, @@ -7,6 +7,7 @@ use crate::server::{ UpdateStateAction, }, }; +use crate::sync::*; const DEFAULT_LIFETIME_COUNT: u32 = 300; const DEFAULT_KEEPALIVE_COUNT: u32 = 100; diff --git a/lib/src/server/util/mod.rs b/lib/src/server/util/mod.rs index 394b66ca5..e1bb7e5f2 100644 --- a/lib/src/server/util/mod.rs +++ b/lib/src/server/util/mod.rs @@ -4,10 +4,11 @@ //! Provides utility routines for things that might be used in a number of places elsewhere. -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use tokio::time::{interval_at, Duration, Instant}; +use crate::sync::*; use crate::types::service_types::ServerState as ServerStateType; use crate::server::state::ServerState; diff --git a/samples/chess-server/src/main.rs b/samples/chess-server/src/main.rs index dfa1064db..9cfead933 100644 --- a/samples/chess-server/src/main.rs +++ b/samples/chess-server/src/main.rs @@ -4,10 +4,11 @@ use std::env; use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::thread; use opcua::server::prelude::*; +use opcua::sync::Mutex; mod game; @@ -45,7 +46,7 @@ fn main() { let address_space = server.address_space(); let ns = { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let ns = address_space .register_namespace("urn:chess-server") @@ -75,7 +76,7 @@ fn main() { .insert(&mut address_space); }); - let game = game.lock().unwrap(); + let game = game.lock(); update_board_state(&game, &mut address_space, ns); ns @@ -90,7 +91,7 @@ fn main() { use std::time::Duration; let sleep_time = Duration::from_millis(1500); - let mut game = game.lock().unwrap(); + let mut game = game.lock(); loop { game.set_position(); let bestmove = game.bestmove().unwrap(); @@ -114,7 +115,7 @@ fn main() { game.print_board(); { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); update_board_state(&game, &mut address_space, ns); } } diff --git a/samples/demo-server/src/control.rs b/samples/demo-server/src/control.rs index 3f31c8cb8..a80056e07 100644 --- a/samples/demo-server/src/control.rs +++ b/samples/demo-server/src/control.rs @@ -12,7 +12,7 @@ pub fn add_control_switches(server: &mut Server, ns: u16) { let server_state = server.server_state(); { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let folder_id = address_space .add_folder("Control", "Control", &NodeId::objects_folder_id()) .unwrap(); @@ -26,7 +26,7 @@ pub fn add_control_switches(server: &mut Server, ns: u16) { } server.add_polling_action(1000, move || { - let address_space = address_space.read().unwrap(); + let address_space = address_space.read(); // Test for abort flag let abort = if let Ok(v) = address_space.get_variable_value(abort_node_id.clone()) { match v.value { @@ -40,7 +40,7 @@ pub fn add_control_switches(server: &mut Server, ns: u16) { }; // Check if abort has been set to true, in which case abort if abort { - let mut server_state = server_state.write().unwrap(); + let mut server_state = server_state.write(); server_state.abort(); } }); diff --git a/samples/demo-server/src/historical.rs b/samples/demo-server/src/historical.rs index 8569a5a70..20a459260 100644 --- a/samples/demo-server/src/historical.rs +++ b/samples/demo-server/src/historical.rs @@ -3,14 +3,15 @@ // Copyright (C) 2017-2022 Adam Lock //! Implementations of HistoricalDataProvider and HistoricalEventProvider -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use opcua::server::prelude::*; +use opcua::sync::RwLock; // Register some historical data providers pub fn add_providers(server: &mut Server) { let server_state = server.server_state(); - let mut server_state = server_state.write().unwrap(); + let mut server_state = server_state.write(); server_state.set_historical_data_provider(Box::new(DataProvider)); server_state.set_historical_event_provider(Box::new(EventProvider)); } diff --git a/samples/demo-server/src/machine.rs b/samples/demo-server/src/machine.rs index 775d60a5d..81d88ff60 100644 --- a/samples/demo-server/src/machine.rs +++ b/samples/demo-server/src/machine.rs @@ -18,7 +18,7 @@ pub fn add_machinery(server: &mut Server, ns: u16, raise_event: bool) { let machine2_counter = Arc::new(AtomicU16::new(50)); let (machine1_id, machine2_id) = { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); add_machinery_model(&mut address_space, ns); // Create a folder under static folder @@ -54,7 +54,7 @@ pub fn add_machinery(server: &mut Server, ns: u16, raise_event: bool) { // Increment counters server.add_polling_action(300, move || { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); increment_counter( &mut address_space, ns, diff --git a/samples/demo-server/src/main.rs b/samples/demo-server/src/main.rs index 72b569fc3..3e0e69be3 100644 --- a/samples/demo-server/src/main.rs +++ b/samples/demo-server/src/main.rs @@ -75,7 +75,7 @@ fn main() { let ns = { let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); address_space.register_namespace("urn:demo-server").unwrap() }; diff --git a/samples/demo-server/src/methods.rs b/samples/demo-server/src/methods.rs index f8e3da3e2..c37523aca 100644 --- a/samples/demo-server/src/methods.rs +++ b/samples/demo-server/src/methods.rs @@ -4,15 +4,16 @@ //! A sample method -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use opcua::server::{ address_space::method::MethodBuilder, callbacks, prelude::*, session::SessionManager, }; +use opcua::sync::RwLock; pub fn add_methods(server: &mut Server, ns: u16) { let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let object_id = NodeId::new(ns, "Functions"); ObjectBuilder::new(&object_id, "Functions", "Functions") diff --git a/samples/demo-server/src/scalar.rs b/samples/demo-server/src/scalar.rs index deb94385d..afa01e4db 100644 --- a/samples/demo-server/src/scalar.rs +++ b/samples/demo-server/src/scalar.rs @@ -10,7 +10,7 @@ use opcua::server::prelude::*; pub fn add_scalar_variables(server: &mut Server, ns: u16) { let (static_folder_id, dynamic_folder_id) = { let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); ( address_space .add_folder("Static", "Static", &NodeId::objects_folder_id()) @@ -170,7 +170,7 @@ pub fn scalar_random_value(id: DataTypeId) -> Variant { fn add_static_scalar_variables(server: &mut Server, ns: u16, static_folder_id: &NodeId) { // The address space is guarded so obtain a lock to change it let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Create a folder under static folder let folder_id = address_space @@ -192,7 +192,7 @@ fn add_static_scalar_variables(server: &mut Server, ns: u16, static_folder_id: & fn add_static_array_variables(server: &mut Server, ns: u16, static_folder_id: &NodeId) { // The address space is guarded so obtain a lock to change it let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Create a folder under static folder let folder_id = address_space @@ -220,7 +220,7 @@ fn add_static_array_variables(server: &mut Server, ns: u16, static_folder_id: &N fn add_dynamic_scalar_variables(server: &mut Server, ns: u16, dynamic_folder_id: &NodeId) { // The address space is guarded so obtain a lock to change it let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Create a folder under static folder let folder_id = address_space @@ -241,7 +241,7 @@ fn add_dynamic_scalar_variables(server: &mut Server, ns: u16, dynamic_folder_id: fn add_dynamic_array_variables(server: &mut Server, ns: u16, dynamic_folder_id: &NodeId) { // The address space is guarded so obtain a lock to change it let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Create a folder under static folder let folder_id = address_space @@ -269,7 +269,7 @@ fn set_dynamic_timers(server: &mut Server, ns: u16) { // Standard change timers server.add_polling_action(250, move || { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Scalar let now = DateTime::now(); SCALAR_TYPES.iter().for_each(|sn| { @@ -298,7 +298,7 @@ pub fn add_stress_variables(server: &mut Server, ns: u16) { .collect::>(); let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let folder_id = address_space .add_folder("Stress", "Stress", &NodeId::objects_folder_id()) @@ -320,7 +320,7 @@ fn set_stress_timer(server: &mut Server, node_ids: Vec) { let address_space = server.address_space(); server.add_polling_action(100, move || { let mut rng = rand::thread_rng(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let now = DateTime::now(); node_ids.iter().for_each(|node_id| { let value: Variant = rng.gen::().into(); diff --git a/samples/event-client/src/main.rs b/samples/event-client/src/main.rs index cb579fa46..dcb625b8b 100644 --- a/samples/event-client/src/main.rs +++ b/samples/event-client/src/main.rs @@ -8,9 +8,10 @@ //! 2. Connect to an endpoint specified by the url with security None //! 3. Subscribe to values and loop forever printing out their values use std::str::FromStr; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use opcua::client::prelude::*; +use opcua::sync::RwLock; struct Args { help: bool, @@ -103,7 +104,7 @@ fn subscribe_to_events( event_source: &str, event_fields: &str, ) -> Result<(), StatusCode> { - let session = session.read().unwrap(); + let session = session.read(); let event_fields: Vec = event_fields.split(',').map(|s| s.into()).collect(); diff --git a/samples/modbus-server/src/main.rs b/samples/modbus-server/src/main.rs index ae1ba6bb9..19429e4f5 100644 --- a/samples/modbus-server/src/main.rs +++ b/samples/modbus-server/src/main.rs @@ -10,13 +10,10 @@ #[macro_use] extern crate serde_derive; -use std::{ - path::PathBuf, - sync::{Arc, RwLock}, - thread, -}; +use std::{path::PathBuf, sync::Arc, thread}; use ::opcua::console_logging; +use ::opcua::sync::RwLock; mod config; mod master; diff --git a/samples/modbus-server/src/master.rs b/samples/modbus-server/src/master.rs index 2452e5765..be6b78b7c 100644 --- a/samples/modbus-server/src/master.rs +++ b/samples/modbus-server/src/master.rs @@ -3,7 +3,7 @@ // Copyright (C) 2017-2022 Adam Lock use std::{ - sync::{Arc, RwLock}, + sync::Arc, thread, time::{Duration, Instant}, }; @@ -14,6 +14,8 @@ use tokio_core::reactor::Core; use tokio_modbus::{client, prelude::*}; use tokio_timer::Interval; +use opcua::sync::RwLock; + use crate::Runtime; pub struct MODBUS { @@ -26,7 +28,7 @@ pub struct MODBUS { impl MODBUS { pub fn run(runtime: Arc>) -> MODBUS { let socket_addr = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); runtime.config.slave_address.parse().unwrap() }; @@ -94,13 +96,13 @@ impl MODBUS { } fn store_values_in_coils(values: Vec, coils: Arc>>) { - let mut coils = coils.write().unwrap(); + let mut coils = coils.write(); coils.clear(); coils.extend(values); } fn store_values_in_registers(values: Vec, registers: Arc>>) { - let mut registers = registers.write().unwrap(); + let mut registers = registers.write(); registers.clear(); registers.extend(values); } @@ -133,7 +135,7 @@ impl InputCoil { fn begin_read_input_coils( runtime: &Arc>, ) -> (Arc>>, u16, u16) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_input_coils = true; ( runtime.input_coils.clone(), @@ -143,7 +145,7 @@ impl InputCoil { } fn end_read_input_coils(runtime: &Arc>) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_input_coils = false; } } @@ -185,7 +187,7 @@ impl OutputCoil { fn begin_read_output_coils( runtime: &Arc>, ) -> (Arc>>, u16, u16) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_output_coils = true; ( runtime.output_coils.clone(), @@ -195,7 +197,7 @@ impl OutputCoil { } fn end_read_output_coils(runtime: &Arc>) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_output_coils = false; } } @@ -228,7 +230,7 @@ impl InputRegister { fn begin_read_input_registers( runtime: &Arc>, ) -> (Arc>>, u16, u16) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_input_registers = true; ( runtime.input_registers.clone(), @@ -238,7 +240,7 @@ impl InputRegister { } fn end_read_input_registers(runtime: &Arc>) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_input_registers = false; } } @@ -289,7 +291,7 @@ impl OutputRegister { fn begin_read_output_registers( runtime: &Arc>, ) -> (Arc>>, u16, u16) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_input_registers = true; ( runtime.output_registers.clone(), @@ -299,7 +301,7 @@ impl OutputRegister { } fn end_read_output_registers(runtime: &Arc>) { - let mut runtime = runtime.write().unwrap(); + let mut runtime = runtime.write(); runtime.reading_output_registers = false; } } @@ -329,7 +331,7 @@ fn spawn_receiver( read_input_coils, read_output_coils, ) = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); ( !runtime.reading_input_registers && runtime.config.input_registers.readable(), @@ -353,19 +355,19 @@ fn spawn_receiver( } } Message::WriteCoil(addr, value) => { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); if runtime.config.output_coils.writable() { OutputCoil::async_write(&handle_for_action, &ctx, addr, value); } } Message::WriteRegister(addr, value) => { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); if runtime.config.output_registers.writable() { OutputRegister::async_write_register(&handle_for_action, &ctx, addr, value); } } Message::WriteRegisters(addr, values) => { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); if runtime.config.output_registers.writable() { OutputRegister::async_write_registers( &handle_for_action, @@ -389,7 +391,7 @@ fn spawn_timer( runtime: Arc>, ) -> impl Future { let interval = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); Duration::from_millis(runtime.config.read_interval as u64) }; let handle = handle.clone(); diff --git a/samples/modbus-server/src/opcua.rs b/samples/modbus-server/src/opcua.rs index 69b5cc631..a18b94acc 100644 --- a/samples/modbus-server/src/opcua.rs +++ b/samples/modbus-server/src/opcua.rs @@ -2,14 +2,10 @@ // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock -use std::{ - f32, f64, i16, i32, i64, i8, - path::PathBuf, - sync::{Arc, Mutex, RwLock}, - u16, -}; +use std::{f32, f64, i16, i32, i64, i8, path::PathBuf, sync::Arc, u16}; use opcua::server::prelude::*; +use opcua::sync::{Mutex, RwLock}; use crate::{ config::{Alias, AliasType, TableConfig}, @@ -27,7 +23,7 @@ pub fn run(runtime: Arc>, modbus: MODBUS) { let modbus = Arc::new(Mutex::new(modbus)); { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let nsidx = address_space.register_namespace("urn:MODBUS").unwrap(); add_variables(runtime, modbus, &mut address_space, nsidx); } @@ -89,7 +85,7 @@ fn add_input_coils( .unwrap(); let (start, end, values) = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); let (start, end) = start_end(&runtime.config.input_coils); let values = runtime.input_coils.clone(); (start, end, values) @@ -121,7 +117,7 @@ fn add_output_coils( .unwrap(); let (start, end, values) = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); let (start, end) = start_end(&runtime.config.output_coils); let values = runtime.output_coils.clone(); (start, end, values) @@ -153,7 +149,7 @@ fn add_input_registers( .unwrap(); // Add variables to the folder let (start, end, values) = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); let (start, end) = start_end(&runtime.config.input_registers); let values = runtime.input_registers.clone(); (start, end, values) @@ -184,7 +180,7 @@ fn add_output_registers( .unwrap(); // Add variables to the folder let (start, end, values) = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); let (start, end) = start_end(&runtime.config.output_registers); let values = runtime.output_registers.clone(); (start, end, values) @@ -211,7 +207,7 @@ fn add_aliases( parent_folder_id: &NodeId, ) { let aliases = { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); runtime.config.aliases.clone() }; if let Some(aliases) = aliases { @@ -278,7 +274,7 @@ fn make_variables( _name, _f| -> Result, StatusCode> { - let values = values.read().unwrap(); + let values = values.read(); let value = *values.get(i - start).unwrap(); Ok(Some(DataValue::new_now(value))) }, @@ -299,7 +295,7 @@ fn make_variables( Variant::Empty }; if let Variant::Boolean(value) = value { - let modbus = modbus.lock().unwrap(); + let modbus = modbus.lock(); modbus.write_to_coil(addr, value); Ok(()) } else { @@ -321,7 +317,7 @@ fn make_variables( Variant::Empty }; if let Variant::UInt16(value) = value { - let modbus = modbus.lock().unwrap(); + let modbus = modbus.lock(); modbus.write_to_register(addr, value); Ok(()) } else { @@ -412,7 +408,7 @@ impl AliasGetterSetter { data_type: AliasType, number: u16, ) -> Result, StatusCode> { - let runtime = runtime.read().unwrap(); + let runtime = runtime.read(); let (table, address) = Table::table_from_number(number); let value = match table { Table::OutputCoils => { @@ -448,7 +444,7 @@ impl AliasGetterSetter { Table::OutputCoils => { let value = value.cast(VariantTypeId::Boolean); if let Variant::Boolean(v) = value { - let modbus = modbus.lock().unwrap(); + let modbus = modbus.lock(); modbus.write_to_coil(addr, v); Ok(()) } else { @@ -462,7 +458,7 @@ impl AliasGetterSetter { // Write the words let (_, words) = Self::value_to_words(value).map_err(|_| StatusCode::BadUnexpectedError)?; - let modbus = modbus.lock().unwrap(); + let modbus = modbus.lock(); modbus.write_to_registers(addr, words); Ok(()) } @@ -484,7 +480,7 @@ impl AliasGetterSetter { address ); } - let values = values.read().unwrap(); + let values = values.read(); let idx = (address - base_address) as usize; Variant::from(*values.get(idx).unwrap()) } @@ -672,7 +668,7 @@ impl AliasGetterSetter { } let idx = (address - base_address) as usize; - let values = values.read().unwrap(); + let values = values.read(); if size == 1 { let w = *values.get(idx).unwrap(); diff --git a/samples/modbus-server/src/slave.rs b/samples/modbus-server/src/slave.rs index 2c0bc610a..d98b148a5 100644 --- a/samples/modbus-server/src/slave.rs +++ b/samples/modbus-server/src/slave.rs @@ -1,16 +1,15 @@ // OPCUA for Rust // SPDX-License-Identifier: MPL-2.0 // Copyright (C) 2017-2022 Adam Lock +use std::{sync::Arc, thread, time}; use futures::future::{self, FutureResult}; -use std::{ - sync::{Arc, RwLock}, - thread, time, -}; use tokio_service::Service; use tokio_modbus::prelude::*; +use opcua::sync::RwLock; + struct Data { pub input_coils: Vec, pub output_coils: Vec, @@ -51,7 +50,7 @@ struct MbServer { impl MbServer { fn update_values(&self) { - let mut data = self.data.write().unwrap(); + let mut data = self.data.write(); data.update_values(time::Instant::now() - self.start_time); } } @@ -66,14 +65,14 @@ impl Service for MbServer { self.update_values(); match req { Request::ReadInputRegisters(addr, cnt) => { - let data = self.data.read().unwrap(); + let data = self.data.read(); let start = addr as usize; let end = start + cnt as usize; let rsp = Response::ReadInputRegisters(data.input_registers[start..end].to_vec()); future::ok(rsp) } Request::ReadHoldingRegisters(addr, cnt) => { - let data = self.data.read().unwrap(); + let data = self.data.read(); let start = addr as usize; let end = start + cnt as usize; let rsp = @@ -81,33 +80,33 @@ impl Service for MbServer { future::ok(rsp) } Request::ReadDiscreteInputs(addr, cnt) => { - let data = self.data.read().unwrap(); + let data = self.data.read(); let start = addr as usize; let end = start + cnt as usize; let rsp = Response::ReadDiscreteInputs(data.input_coils[start..end].to_vec()); future::ok(rsp) } Request::ReadCoils(addr, cnt) => { - let data = self.data.read().unwrap(); + let data = self.data.read(); let start = addr as usize; let end = start + cnt as usize; let rsp = Response::ReadCoils(data.output_coils[start..end].to_vec()); future::ok(rsp) } Request::WriteSingleCoil(addr, value) => { - let mut data = self.data.write().unwrap(); + let mut data = self.data.write(); data.output_coils[addr as usize] = value; let rsp = Response::WriteSingleCoil(addr); future::ok(rsp) } Request::WriteSingleRegister(addr, value) => { - let mut data = self.data.write().unwrap(); + let mut data = self.data.write(); data.output_registers[addr as usize] = value; let rsp = Response::WriteSingleRegister(addr, value); future::ok(rsp) } Request::WriteMultipleRegisters(addr, words) => { - let mut data = self.data.write().unwrap(); + let mut data = self.data.write(); words .iter() .enumerate() diff --git a/samples/mqtt-client/src/main.rs b/samples/mqtt-client/src/main.rs index 5d109981f..7efc130e7 100644 --- a/samples/mqtt-client/src/main.rs +++ b/samples/mqtt-client/src/main.rs @@ -6,13 +6,14 @@ //! values before exiting. use std::{ path::PathBuf, - sync::{mpsc, Arc, Mutex, RwLock}, + sync::{mpsc, Arc}, thread, }; use rumqtt::{MqttClient, MqttOptions, QoS}; use opcua::client::prelude::*; +use opcua::sync::{Mutex, RwLock}; struct Args { help: bool, @@ -133,7 +134,7 @@ fn subscription_loop( // This scope is important - we don't want to session to be locked when the code hits the // loop below { - let session = session.read().unwrap(); + let session = session.read(); // Creates our subscription - one update every second. The update is sent as a message // to the MQTT thread to be published. @@ -147,7 +148,7 @@ fn subscription_loop( true, DataChangeCallback::new(move |items| { println!("Data change from server:"); - let tx = tx.lock().unwrap(); + let tx = tx.lock(); items.iter().for_each(|item| { let node_id = item.item_to_monitor().node_id.clone(); let value = item.last_value().clone(); diff --git a/samples/simple-client/src/main.rs b/samples/simple-client/src/main.rs index ea4d9f458..ffc698371 100644 --- a/samples/simple-client/src/main.rs +++ b/samples/simple-client/src/main.rs @@ -7,9 +7,10 @@ //! 1. Create a client configuration //! 2. Connect to an endpoint specified by the url with security None //! 3. Subscribe to values and loop forever printing out their values -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use opcua::client::prelude::*; +use opcua::sync::RwLock; struct Args { help: bool, @@ -84,7 +85,7 @@ fn main() -> Result<(), ()> { } fn subscribe_to_variables(session: Arc>, ns: u16) -> Result<(), StatusCode> { - let session = session.read().unwrap(); + let session = session.read(); // Creates a subscription with a data change callback let subscription_id = session.create_subscription( 2000.0, diff --git a/samples/simple-server/src/main.rs b/samples/simple-server/src/main.rs index 2f869ce23..ec11bf9b7 100644 --- a/samples/simple-server/src/main.rs +++ b/samples/simple-server/src/main.rs @@ -6,9 +6,10 @@ //! adds some variables to the address space and the listeners for connections. It also has //! a timer that updates those variables so anything monitoring variables sees the values changing. use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use opcua::server::prelude::*; +use opcua::sync::Mutex; fn main() { // This enables logging via env_logger & log crate macros. If you don't need logging or want @@ -20,7 +21,7 @@ fn main() { let ns = { let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); address_space .register_namespace("urn:simple-server") .unwrap() @@ -45,7 +46,7 @@ fn add_example_variables(server: &mut Server, ns: u16) { // The address space is guarded so obtain a lock to change it { - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); // Create a sample folder under objects folder let sample_folder_id = address_space @@ -71,7 +72,7 @@ fn add_example_variables(server: &mut Server, ns: u16) { // function. { let address_space = server.address_space(); - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); if let Some(ref mut v) = address_space.find_variable_mut(v3_node.clone()) { // Hello world's counter will increment with each get - slower interval == slower increment let mut counter = 0; @@ -112,10 +113,10 @@ fn add_example_variables(server: &mut Server, ns: u16) { // Store a counter and a flag in a tuple let data = Arc::new(Mutex::new((0, true))); server.add_polling_action(300, move || { - let mut data = data.lock().unwrap(); + let mut data = data.lock(); data.0 += 1; data.1 = !data.1; - let mut address_space = address_space.write().unwrap(); + let mut address_space = address_space.write(); let now = DateTime::now(); let _ = address_space.set_variable_value(v1_node.clone(), data.0 as i32, &now, &now); let _ = address_space.set_variable_value(v2_node.clone(), data.1, &now, &now); diff --git a/samples/web-client/src/main.rs b/samples/web-client/src/main.rs index 185b403df..a850fc927 100644 --- a/samples/web-client/src/main.rs +++ b/samples/web-client/src/main.rs @@ -8,7 +8,7 @@ extern crate serde_derive; use std::{ str::FromStr, - sync::{Arc, RwLock}, + sync::Arc, time::{Duration, Instant}, }; @@ -20,6 +20,7 @@ use actix_web::{ }; use opcua::client::prelude::*; +use opcua::sync::RwLock; struct Args { help: bool, @@ -198,7 +199,7 @@ impl OPCUASession { ) { Ok(session) => { { - let mut session = session.write().unwrap(); + let mut session = session.write(); let addr_for_connection_status_change = addr.clone(); session.set_connection_status_callback(ConnectionStatusCallback::new( move |connected| { @@ -236,7 +237,7 @@ impl OPCUASession { fn disconnect(&mut self, _ctx: &mut ::Context) { if let Some(ref mut session) = self.session { - let session = session.read().unwrap(); + let session = session.read(); if session.is_connected() { session.disconnect(); } @@ -288,7 +289,7 @@ impl OPCUASession { let select_criteria = args.get(2).unwrap(); if let Some(ref mut session) = self.session { - let session = session.read().unwrap(); + let session = session.read(); let event_node_id = NodeId::from_str(event_node_id); if event_node_id.is_err() { @@ -398,7 +399,7 @@ impl OPCUASession { // Create a subscription println!("Creating subscription"); - let session = session.read().unwrap(); + let session = session.read(); // Creates our subscription let addr_for_datachange = ctx.address();