1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#![allow(dead_code)]

use crate::Context;
use ockam_core::RelayMessage;

#[cfg(feature = "debugger")]
use ockam_core::{Address, Mailbox, Mailboxes};

#[cfg(feature = "debugger")]
use ockam_core::compat::{
    collections::BTreeMap,
    sync::{Arc, RwLock},
    vec::Vec,
};

#[cfg(feature = "debugger")]
use core::{
    mem::MaybeUninit,
    sync::atomic::{AtomicU32, Ordering},
};

#[cfg(feature = "debugger")]
#[derive(Default)]
struct Debugger {
    /// Map context inheritance from parent main `Mailbox` to child [`Mailboxes`]
    inherited_mb: Arc<RwLock<BTreeMap<Mailbox, Vec<Mailboxes>>>>,
    /// Map message destination to source
    incoming: Arc<RwLock<BTreeMap<Address, Vec<Address>>>>,
    /// Map message destination `Mailbox` to source [`Mailbox`]
    incoming_mb: Arc<RwLock<BTreeMap<Mailbox, Vec<Address>>>>,
    /// Map message source to destinations
    outgoing: Arc<RwLock<BTreeMap<Address, Vec<Address>>>>,
}

/// Return a mutable reference to the global debugger instance
/// TODO are there any better options for singletons yet that are also
/// no_std compatible?
#[cfg(feature = "debugger")]
#[allow(unsafe_code)]
fn instance() -> &'static Debugger {
    static mut INSTANCE: MaybeUninit<Debugger> = MaybeUninit::uninit();

    #[cfg(feature = "std")]
    {
        use std::sync::Once;
        static ONCE: Once = Once::new();
        ONCE.call_once(|| {
            let instance = Debugger::default();
            unsafe { INSTANCE.write(instance) };
        });
    }

    #[cfg(not(feature = "std"))]
    {
        use ockam_core::compat::sync::Mutex;
        static ONCE: Mutex<bool> = Mutex::new(true);
        if let Ok(mut once) = ONCE.lock() {
            if *once {
                let instance = Debugger::default();
                unsafe {
                    INSTANCE.write(instance);
                }
                *once = false;
            }
        } else {
            panic!("Failed to acquire initialization lock for debugger");
        }
    }

    unsafe { INSTANCE.assume_init_ref() }
}

/// Log incoming message traffic
///
/// This debug function builds a map of message traffic within a node.
///
/// Useful for:
///
/// 1. Figuring out the minimal set of access control rules for nodes
///    to communicate to each other.
/// 2. Understanding the ockam source code.
///
pub fn log_incoming_message(_receiving_ctx: &Context, _relay_msg: &RelayMessage) {
    #[cfg(feature = "debugger")]
    {
        static COUNTER: AtomicU32 = AtomicU32::new(0);

        tracing::trace!(
            "log_incoming_message #{:03}: {} -> {} ({})",
            COUNTER.fetch_add(1, Ordering::Relaxed),
            _relay_msg.source(),      // sending address
            _relay_msg.destination(), // receiving address
            _receiving_ctx.address(), // actual receiving context address
        );

        match instance().incoming.write() {
            Ok(mut incoming) => {
                let source = _relay_msg.source().clone();
                let destination = _relay_msg.destination().clone();
                incoming
                    .entry(destination)
                    .or_insert_with(Vec::new)
                    .push(source);
            }
            Err(e) => {
                tracing::error!("debugger panicked: {}", e);
                panic!("log_incoming_message");
            }
        }

        match instance().incoming_mb.write() {
            Ok(mut incoming_mb) => {
                let source = _relay_msg.source().clone();
                let destination = _relay_msg.destination().clone();
                if let Some(destination_mb) = _receiving_ctx.mailboxes().find_mailbox(&destination)
                {
                    incoming_mb
                        .entry(destination_mb.clone())
                        .or_insert_with(Vec::new)
                        .push(source);
                }
            }
            Err(e) => {
                tracing::error!("debugger panicked: {}", e);
                panic!("log_incoming_message");
            }
        }
    }
}

/// Log outgoing message traffic
pub fn log_outgoing_message(_sending_ctx: &Context, _relay_msg: &RelayMessage) {
    #[cfg(feature = "debugger")]
    {
        static COUNTER: AtomicU32 = AtomicU32::new(0);

        tracing::trace!(
            "log_outgoing_message #{:03}: {} ({}) -> {}",
            COUNTER.fetch_add(1, Ordering::Relaxed),
            _relay_msg.source(),      // sending address
            _sending_ctx.address(),   // actual sending context address
            _relay_msg.destination(), // receiving address
        );

        match instance().outgoing.write() {
            Ok(mut outgoing) => {
                let source = _relay_msg.source().clone();
                let destination = _relay_msg.destination().clone();
                outgoing
                    .entry(source)
                    .or_insert_with(Vec::new)
                    .push(destination);
            }
            Err(e) => {
                tracing::error!("debugger panicked: {}", e);
                panic!("log_incoming_message");
            }
        }
    }
}

/// Log Context creation
///
/// This debug function builds an inheritance tree of the contexts
/// within a node.
///
/// Useful for:
///
/// 1. Figuring out the access control inheritance structure for a
///    node.
/// 2. Getting a rough idea of the "worker context" for a group of
///    contexts created by a top-level worker or processor interface
/// 3. Tracking down "orphan" contexts that could be vulnerable to
///    hostile messages
pub fn log_inherit_context(_tag: &str, _parent: &Context, _child: &Context) {
    #[cfg(feature = "debugger")]
    {
        static COUNTER: AtomicU32 = AtomicU32::new(0);

        tracing::trace!(
            "log_inherit_context #{:03}\n{:?}\nBegat {}\n{:?}\n",
            COUNTER.fetch_add(1, Ordering::Relaxed),
            _parent.mailboxes(),
            _tag,
            _child.mailboxes(),
        );

        match instance().inherited_mb.write() {
            Ok(mut inherited_mb) => {
                let parent = _parent.mailboxes().main_mailbox().clone();
                let children = _child.mailboxes().clone();
                inherited_mb
                    .entry(parent)
                    .or_insert_with(Vec::new)
                    .push(children);
            }
            Err(e) => {
                tracing::error!("debugger panicked: {}", e);
                panic!("log_incoming_message");
            }
        }
    }
}

/// TODO
pub fn _log_start_worker() {
    #[cfg(feature = "debugger")]
    {}
}

/// TODO
pub fn _log_start_processor() {
    #[cfg(feature = "debugger")]
    {}
}

// ----------------------------------------------------------------------------

#[cfg(all(feature = "debugger", feature = "std"))]
use ockam_core::compat::io::{self, BufWriter, Write};

/// Generate diagrams of the data logged by the Debugger
///
/// Diagram files can be rendered using graphviz, for example:
///
///    dot 07-inlet.dot -Tpdf -O
///    dot 07-inlet.dot -Tpdf -o 07-inlet.pdf
#[cfg(all(feature = "debugger", feature = "std"))]
pub fn generate_graphs<W: Write>(w: &mut BufWriter<W>) -> io::Result<()> {
    fn id(mailbox: &Mailbox) -> String {
        mailbox.address().address().replace('.', "_")
    }

    fn write_mailbox<W: Write>(
        w: &mut BufWriter<W>,
        mailbox: &Mailbox,
        tag: &str,
    ) -> io::Result<()> {
        write!(
            w,
            "    {}{} [label=\"{{ {} | in: {:?} | out: {:?}  }} \"]",
            tag,
            id(mailbox),
            mailbox.address(),
            mailbox.incoming_access_control(),
            mailbox.outgoing_access_control(),
        )?;
        writeln!(w)?;
        Ok(())
    }

    // generate mailboxes set
    use ockam_core::compat::collections::BTreeSet;
    let mut mailboxes = BTreeSet::new();
    if let Ok(inherited_mb) = instance().inherited_mb.read() {
        for (parent, children) in inherited_mb.iter() {
            for child in children.iter() {
                mailboxes.insert(parent.clone());
                mailboxes.insert(child.main_mailbox().clone());
                for mailbox in child.additional_mailboxes().iter() {
                    mailboxes.insert(mailbox.clone());
                }
            }
        }
    }

    writeln!(w, "digraph ockam_node {{")?;
    writeln!(w, "  fontname=Arial;")?;
    writeln!(w, "  rankdir=TB;")?;

    // - inheritance ----------------------------------------------------------
    writeln!(w, "  subgraph cluster_Inheritance {{")?;
    writeln!(w, "    label=\"Inheritance\";")?;
    writeln!(w, "    fontsize=24.0;")?;
    writeln!(w, "    labelloc=\"t\";")?;
    writeln!(w, "    rankdir=TB;")?;
    writeln!(w, "    edge [fillcolor=\"#a6cee3\"];")?;
    writeln!(w, "    edge [color=\"#1f78b4\"];")?;
    writeln!(w, "    node [shape=record];")?;
    writeln!(w, "    node [fontname=Arial];")?;
    writeln!(w, "    node [fontsize=12.0];")?;
    // metadata
    for mailbox in mailboxes.iter() {
        write_mailbox(w, mailbox, "")?;
    }
    // topology
    match instance().inherited_mb.read() {
        Ok(inherited_mb) => {
            for (parent, children) in inherited_mb.iter() {
                for child in children.iter() {
                    let mut child_ids = vec![id(child.main_mailbox())];
                    for mailbox in child.additional_mailboxes().iter() {
                        let child_id = id(mailbox);
                        child_ids.push(child_id);
                    }
                    for child_id in child_ids.iter() {
                        writeln!(w, "    {} -> {};", id(parent), child_id,)?;
                    }
                }
            }
        }
        Err(e) => {
            tracing::error!("debugger panicked: {}", e);
            panic!("display_log");
        }
    }
    writeln!(w, "  }}\n")?;

    // - message flow ---------------------------------------------------------
    writeln!(w, "  subgraph cluster_MessageFlow {{")?;
    writeln!(w, "    label=\"MessageFlow\";")?;
    writeln!(w, "    fontsize=24.0;")?;
    writeln!(w, "    fontname=Arial;")?;
    writeln!(w, "    labelloc=\"t\";")?;
    writeln!(w, "    rankdir=TB;")?;
    writeln!(w, "    edge [fillcolor=\"#a60000\"];")?;
    writeln!(w, "    edge [color=\"#1f0000\"];")?;
    writeln!(w, "    node [shape=Mrecord];")?;
    writeln!(w, "    node [fontname=Arial];")?;
    writeln!(w, "    node [fontsize=12.0];")?;
    // metadata
    for mailbox in mailboxes.iter() {
        write_mailbox(w, mailbox, "MF_")?;
    }
    match instance().incoming_mb.read() {
        Ok(incoming_mb) => {
            for (destination, sources) in incoming_mb.iter() {
                let mut sources = sources.clone();
                sources.sort();
                sources.dedup();
                for source in sources.iter() {
                    writeln!(
                        w,
                        "    MF_{} -> MF_{};",
                        //"    {} -> {};",
                        source.address().replace('.', "_"),
                        id(destination),
                    )?;
                }
            }
        }
        Err(e) => {
            tracing::error!("debugger panicked: {}", e);
            panic!("display_log");
        }
    }
    writeln!(w, "  }}")?;

    writeln!(w, "}}")?;
    w.flush()?;

    Ok(())
}

/// Displays a summary of the data logged by the Debugger
#[cfg(feature = "debugger")]
pub fn display_log() {
    tracing::info!("======================================================================");
    tracing::info!("  Contexts Inherited");
    tracing::info!("----------------------------------------------------------------------");
    match instance().inherited_mb.read() {
        Ok(inherited_mb) => {
            for (parent, children) in inherited_mb.iter() {
                tracing::info!("{:?}", parent);
                for child in children.iter() {
                    tracing::info!("    =>  {:?}", child);
                }
            }
        }
        Err(e) => {
            tracing::error!("debugger panicked: {}", e);
            panic!("display_log");
        }
    }

    tracing::info!("----------------------------------------------------------------------");
    tracing::info!("  Incoming Messages Received");
    tracing::info!("----------------------------------------------------------------------");
    /*match instance().incoming.read() {
        Ok(incoming) => {
            for (destination, sources) in incoming.iter() {
                let mut sources = sources.clone();
                sources.sort();
                sources.dedup();
                tracing::info!("{:40}  <=  {:?}", format!("{}", destination), sources);
            }
        }
        Err(e) => {
            tracing::error!("debugger panicked: {}", e);
            panic!("display_log");
        }
    }
    tracing::info!("----------------------------------------------------------------------");*/
    match instance().incoming_mb.read() {
        Ok(incoming_mb) => {
            for (destination, sources) in incoming_mb.iter() {
                tracing::info!("{:?}", destination);
                let mut sources = sources.clone();
                sources.sort();
                sources.dedup();
                for source in sources.iter() {
                    tracing::info!("    <=  {:?}", source);
                }
            }
        }
        Err(e) => {
            tracing::error!("debugger panicked: {}", e);
            panic!("display_log");
        }
    }

    /*tracing::info!("----------------------------------------------------------------------");
    tracing::info!("  Outgoing Messages Sent");
    tracing::info!("----------------------------------------------------------------------");
    match instance().outgoing.read() {
        Ok(outgoing) => {
            for (origin, destinations) in outgoing.iter() {
                let mut destinations = destinations.clone();
                destinations.sort();
                destinations.dedup();
                tracing::info!("{:40}  =>  {:?}", format!("{}", origin), destinations);
            }
        }
        Err(e) => {
            tracing::error!("debugger panicked: {}", e);
            panic!("display_log");
        }
    }*/
}