#![allow(unsafe_code)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use iec61850_kit::common::{Instant, Quality, TimeQuality, UtcTime};
use iec61850_kit::proto::data::Value;
use iec61850_kit::proto::ethernet::{ETHERTYPE_GOOSE, ETHERTYPE_SV, FrameHeader, MacAddr, VlanTag};
use iec61850_kit::proto::goose::{
Publisher as GoosePublisher, PublisherConfig as GooseConfig, Retransmission, Subscriber as GooseSubscriber, SubscriberConfig, SubscriptionKey,
};
use iec61850_kit::proto::sv::le::PhsMeas1;
use iec61850_kit::proto::sv::{
ChannelType, Publisher as SvPublisher, PublisherConfig as SvConfig, SampleLayout, SmpSynch, StreamConfig, StreamKey, Subscriber as SvSubscriber, SvProfile,
};
struct Counting;
thread_local! {
static MEASURING: Cell<bool> = const { Cell::new(false) };
static ALLOCATIONS: Cell<u64> = const { Cell::new(0) };
static BYTES: Cell<u64> = const { Cell::new(0) };
}
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
count(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
count(new_size.saturating_sub(layout.size()));
unsafe { System.realloc(ptr, layout, new_size) }
}
}
fn count(bytes: usize) {
let _ = MEASURING.try_with(|m| {
if m.get() {
let _ = ALLOCATIONS.try_with(|c| c.set(c.get().saturating_add(1)));
let _ = BYTES.try_with(|c| c.set(c.get().saturating_add(bytes as u64)));
}
});
}
#[global_allocator]
static ALLOC: Counting = Counting;
fn allocations(f: impl FnOnce()) -> u64 {
measure(f).0
}
fn measure(f: impl FnOnce()) -> (u64, u64) {
ALLOCATIONS.with(|c| c.set(0));
BYTES.with(|c| c.set(0));
MEASURING.with(|m| m.set(true));
f();
MEASURING.with(|m| m.set(false));
(ALLOCATIONS.with(Cell::get), BYTES.with(Cell::get))
}
fn goose_header() -> FrameHeader {
FrameHeader {
dst: MacAddr::GOOSE_BASE,
src: MacAddr([2, 0, 0, 0, 0, 1]),
vlan: Some(VlanTag::DEFAULT),
ethertype: ETHERTYPE_GOOSE,
appid: 1,
reserved1: 0,
reserved2: 0,
}
}
fn sv_header() -> FrameHeader {
FrameHeader {
dst: MacAddr::SV_BASE,
src: MacAddr([2, 0, 0, 0, 0, 2]),
vlan: Some(VlanTag::DEFAULT),
ethertype: ETHERTYPE_SV,
appid: 0x4000,
reserved1: 0,
reserved2: 0,
}
}
#[test]
#[allow(clippy::too_many_lines)]
fn the_steady_state_allocates_nothing() {
let values = [Value::Boolean(true), Value::quality(Quality::GOOD), Value::Integer(-7), Value::Float32(1.5)];
let cfg = GooseConfig {
header: goose_header(),
gocb_ref: "IED1LD0/LLN0$GO$gcbTrip".into(),
dat_set: "IED1LD0/LLN0$dsTrip".into(),
go_id: Some("IED1".into()),
conf_rev: 1,
retransmission: Retransmission::DEFAULT,
simulation: false,
nds_com: false,
};
let mut pubr = GoosePublisher::new(cfg, &values, UtcTime::default()).unwrap();
let mut now = Instant::ZERO;
for _ in 0..4 {
pubr.on_timeout(now).unwrap();
assert!(pubr.poll_transmit().is_some());
now = pubr.next_timeout().unwrap();
}
let n = allocations(|| {
for _ in 0..1000 {
pubr.on_timeout(now).unwrap();
let frame = pubr.poll_transmit().expect("a frame is due");
std::hint::black_box(frame.len());
now = pubr.next_timeout().unwrap();
}
});
assert_eq!(n, 0, "a GOOSE publisher retransmitting must not allocate");
let changed = [Value::Boolean(false), Value::quality(Quality::GOOD), Value::Integer(9), Value::Float32(-1.5)];
let n = allocations(|| {
for i in 0..1000 {
let v = if i % 2 == 0 { &changed } else { &values };
pubr.publish(now, v, UtcTime::default()).unwrap();
std::hint::black_box(pubr.poll_transmit().expect("a state change always produces a frame").len());
now = now.plus_millis(1);
}
});
assert_eq!(n, 0, "a GOOSE state change must not allocate either");
let n = allocations(|| {
for i in 0..1000 {
let v = if i % 100 == 0 { &changed } else { &values };
std::hint::black_box(pubr.publish_if_changed(now, v, UtcTime::default()).unwrap());
pubr.poll_transmit();
now = now.plus_millis(1);
}
});
assert_eq!(n, 0, "comparing the data set against the one on the wire must not allocate");
let mut mu = SvPublisher::new(SvConfig::new(sv_header(), "MU01", SvProfile::F4800S2I4U4).with_time_fields(true, true)).unwrap();
mu.set_smp_synch(SmpSynch::Global).unwrap();
let sample = PhsMeas1 { currents: [1, 2, 3, 4], current_quality: [Quality::GOOD; 4], voltages: [5, 6, 7, 8], voltage_quality: [Quality::GOOD; 4] }.encode();
mu.publish_repeating(Instant::ZERO, &sample).unwrap();
mu.poll_transmit();
let n = allocations(|| {
for i in 0..2400u64 {
mu.publish_repeating(Instant(i), &sample).unwrap();
std::hint::black_box(mu.poll_transmit().expect("a frame is pending").len());
}
});
assert_eq!(n, 0, "publishing one repeated block per ASDU must not allocate");
let n = allocations(|| {
let blocks: [&[u8]; 2] = [&sample, &sample];
for i in 0..2400u64 {
mu.set_refr_tm(UtcTime::from_unix(1_700_000_000, (i * 416_666) as u32, TimeQuality::SYNCHRONIZED));
mu.publish(Instant(i), &blocks).unwrap();
std::hint::black_box(mu.poll_transmit().expect("a frame is pending").len());
}
});
assert_eq!(n, 0, "one second of IEC 61869-9 publishing must not allocate");
let frames: Vec<Vec<u8>> = (0..64u64)
.map(|i| {
mu.publish(Instant(i), &[&sample, &sample]).unwrap();
mu.poll_transmit().unwrap().to_vec()
})
.collect();
let mut channels = Vec::new();
for name in ["Ia", "Ib", "Ic", "In", "Ua", "Ub", "Uc", "Un"] {
channels.push((format!("{name}.instMag.i"), ChannelType::Int(4)));
channels.push((format!("{name}.q"), ChannelType::Quality));
}
let mut sub = SvSubscriber::new(vec![
StreamConfig::new(StreamKey { dst: MacAddr::SV_BASE, appid: 0x4000, sv_id: "MU01".into() })
.with_samples_per_second(4800)
.with_layout(SampleLayout::new(channels)),
]);
sub.on_frame(Instant::ZERO, &frames[0], |_| {});
while sub.poll_event().is_some() {}
let mut seen = 0u64;
let n = allocations(|| {
for (i, f) in frames.iter().enumerate().skip(1) {
sub.on_frame(Instant(i as u64), f, |s| {
seen += u64::from(s.asdu.smp_cnt);
for (_, v) in s.channels() {
seen += v.as_i64().unwrap_or(0).unsigned_abs();
}
});
}
});
std::hint::black_box(seen);
assert_eq!(n, 0, "the sampled-value receive path must not allocate");
assert_eq!(sub.state(0).unwrap().gaps, 0, "the run must have been a clean stream, or it measured nothing");
let mut gsub =
GooseSubscriber::new(SubscriberConfig::new(SubscriptionKey { dst: MacAddr::GOOSE_BASE, appid: 1, gocb_ref: "IED1LD0/LLN0$GO$gcbTrip".into() }));
pubr.publish(now, &values, UtcTime::default()).unwrap();
let first = pubr.poll_transmit().unwrap().to_vec();
let repeats: Vec<Vec<u8>> = (0..100)
.map(|_| {
now = pubr.next_timeout().unwrap();
pubr.on_timeout(now).unwrap();
pubr.poll_transmit().unwrap().to_vec()
})
.collect();
gsub.on_frame(Instant::ZERO, &first);
while gsub.poll_event().is_some() {}
let n = allocations(|| {
for (i, f) in repeats.iter().enumerate() {
gsub.on_frame(Instant::ZERO.plus_millis(i as u64 + 1), f);
while gsub.poll_event().is_some() {}
}
});
let stats = gsub.stats();
assert_eq!((stats.state_changes, stats.retransmissions, stats.expiries), (1, 100, 0), "{stats:?}");
assert_eq!(n, 0, "a GOOSE retransmission must not allocate; only a state change may");
}
#[test]
#[cfg(all(feature = "server", feature = "std"))]
fn opening_a_large_file_does_not_allocate_it() {
use iec61850_kit::common::Instant;
use iec61850_kit::proto::mms::ConfirmedRequest;
use iec61850_kit::proto::mms::file::FileNameBuf;
use iec61850_kit::server::{Acsi, Answer, DirectoryStore, Ied};
const RECORD: usize = 4 << 20;
let dir = std::env::temp_dir().join(format!("iec61850-bigfile-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("rec.dat"), vec![0x5Au8; RECORD]).unwrap();
let mut acsi = Acsi::new(Ied::from_scl(MODEL, Some("IED1")).unwrap());
acsi.set_file_store(Box::new(DirectoryStore::new(&dir)));
let path = FileNameBuf::from_path("rec.dat").unwrap();
let name = path.as_name();
let warm = acsi.request(1, Instant::ZERO, &ConfirmedRequest::FileOpen { name, position: 0 });
let Answer::FileOpen { frsm_id, size, .. } = warm else { panic!("not an open: {warm:?}") };
assert_eq!(size as usize, RECORD);
acsi.request(1, Instant::ZERO, &ConfirmedRequest::FileClose(frsm_id));
let chunk = acsi.config().file_chunk;
let mut frsm = 0;
let (_, open_bytes) = measure(|| {
let a = acsi.request(1, Instant::ZERO, &ConfirmedRequest::FileOpen { name, position: 0 });
if let Answer::FileOpen { frsm_id, .. } = a {
frsm = frsm_id;
}
});
let (_, read_bytes) = measure(|| {
acsi.request(1, Instant::ZERO, &ConfirmedRequest::FileRead(frsm));
});
assert!(open_bytes < 64 * 1024, "an open must not allocate the file: {open_bytes} octets for a {RECORD}-octet record");
assert!(read_bytes < (chunk as u64) * 8, "a read must cost a chunk ({chunk}), not a file: {read_bytes} octets");
let mut total = 0usize;
loop {
match acsi.request(1, Instant::ZERO, &ConfirmedRequest::FileRead(frsm)) {
Answer::FileRead { data, more } => {
assert!(data.iter().all(|b| *b == 0x5A), "the octets are the file's");
total += data.len();
if !more {
break;
}
}
other => panic!("not a read: {other:?}"),
}
assert!(total <= RECORD, "the reads must terminate");
}
assert_eq!(total, RECORD - chunk, "the warm read above already took the first chunk");
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(all(feature = "server", feature = "std"))]
const MODEL: &str = r#"<?xml version="1.0"?>
<SCL xmlns="http://www.iec.ch/61850/2003/SCL" version="2007" revision="B" release="4">
<Header id="f"/>
<IED name="IED1"><AccessPoint name="P1"><Server><LDevice inst="LD0">
<LN0 lnClass="LLN0" inst="" lnType="LLN0_T"/>
</LDevice></Server></AccessPoint></IED>
<DataTypeTemplates>
<LNodeType id="LLN0_T" lnClass="LLN0"><DO name="Mod" type="INC_T"/></LNodeType>
<DOType id="INC_T" cdc="INC"><DA name="stVal" fc="ST" bType="INT32"/></DOType>
</DataTypeTemplates>
</SCL>"#;
#[test]
#[cfg(all(feature = "server", feature = "std"))]
fn receiving_a_file_costs_a_chunk_not_the_file() {
use iec61850_kit::common::Instant;
use iec61850_kit::proto::mms::file::{FileAttributes, FileNameBuf};
use iec61850_kit::proto::mms::{ConfirmedRequest, ConfirmedResponse, Mms};
use iec61850_kit::server::{Acsi, AcsiConfig, Answer, DirectoryStore, FileWritePolicy, Ied};
const CHUNK: usize = 4096;
const CHUNKS: u32 = 64;
let dir = std::env::temp_dir().join(format!("iec61850-receive-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let cfg = AcsiConfig { file_write: FileWritePolicy::Anyone, ..AcsiConfig::default() };
let mut acsi = Acsi::with_config(Ied::from_scl(MODEL, Some("IED1")).unwrap(), cfg);
acsi.set_file_store(Box::new(DirectoryStore::new(&dir).writable()));
let source = FileNameBuf::from_path("big.bin").unwrap();
let dest = FileNameBuf::from_path("big.bin").unwrap();
let answer = acsi.request(1, Instant::ZERO, &ConfirmedRequest::ObtainFile { source_server: None, source: source.as_name(), destination: dest.as_name() });
assert!(matches!(answer, Answer::Deferred), "{answer:?}");
acsi.obtain_bind(1, 1);
let size = CHUNKS * u32::try_from(CHUNK).unwrap();
let open =
Mms::ConfirmedResponse { invoke_id: 0, service: ConfirmedResponse::FileOpen { frsm_id: 3, attributes: FileAttributes { size, last_modified: None } } }
.to_vec()
.unwrap();
let data = vec![0xA5u8; CHUNK];
let answer_once = |acsi: &mut Acsi, invoke: i64, pdu: &[u8]| {
assert!(acsi.obtain_call(1).is_some(), "a call is due");
acsi.obtain_issued(1, invoke);
let mms = Mms::parse(pdu, &iec61850_kit::common::Limits::DEFAULT).unwrap();
acsi.obtain_response(1, invoke, &mms)
};
let mut invoke = 10;
assert!(answer_once(&mut acsi, invoke, &open).is_none());
let mut worst = 0u64;
for n in 0..CHUNKS {
let read =
Mms::ConfirmedResponse { invoke_id: 0, service: ConfirmedResponse::FileRead { data: &data, more_follows: n + 1 < CHUNKS } }.to_vec().unwrap();
let mms = Mms::parse(&read, &iec61850_kit::common::Limits::DEFAULT).unwrap();
assert!(acsi.obtain_call(1).is_some());
invoke += 1;
acsi.obtain_issued(1, invoke);
let (_, bytes) = measure(|| {
let _ = acsi.obtain_response(1, invoke, &mms);
});
worst = worst.max(bytes);
}
assert!(worst < (CHUNK as u64) * 4, "a chunk received costs {worst} octets, more than a few chunks of {CHUNK}");
let close = Mms::ConfirmedResponse { invoke_id: 0, service: ConfirmedResponse::FileClose }.to_vec().unwrap();
let done = answer_once(&mut acsi, invoke + 1, &close).expect("the ObtainFile is answered");
assert!(matches!(Mms::parse(&done, &iec61850_kit::common::Limits::DEFAULT), Ok(Mms::ConfirmedResponse { service: ConfirmedResponse::ObtainFile, .. })));
assert_eq!(std::fs::metadata(dir.join("big.bin")).unwrap().len(), u64::from(size));
let _ = std::fs::remove_dir_all(&dir);
}