Skip to main content

capsule/batch/
mod.rs

1/*
2* Copyright 2019 Comcast Cable Communications Management, LLC
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*
16* SPDX-License-Identifier: Apache-2.0
17*/
18
19//! Combinators that can be applied to batches of packets within a pipeline.
20
21mod emit;
22mod filter;
23mod filter_map;
24mod for_each;
25mod group_by;
26mod inspect;
27mod map;
28mod poll;
29mod replace;
30mod rxtx;
31mod send;
32
33pub use self::emit::*;
34pub use self::filter::*;
35pub use self::filter_map::*;
36pub use self::for_each::*;
37pub use self::group_by::*;
38pub use self::inspect::*;
39pub use self::map::*;
40pub use self::poll::*;
41pub use self::replace::*;
42pub use self::rxtx::*;
43pub use self::send::*;
44
45use crate::packets::Packet;
46use crate::Mbuf;
47use anyhow::{Error, Result};
48use std::collections::HashMap;
49use std::hash::Hash;
50
51/// Way to categorize the packets of a batch inside a processing pipeline.
52/// The disposition instructs the combinators how to process a packet.
53#[allow(missing_debug_implementations)]
54pub enum Disposition<T: Packet> {
55    /// Indicating the packet should be processed.
56    Act(T),
57
58    /// Indicating the packet has already been sent, possibly through a
59    /// different [`PacketTx`].
60    ///
61    /// [`PacketTx`]: crate::batch::PacketTx
62    Emit,
63
64    /// Indicating the packet is intentionally dropped from the output.
65    Drop(Mbuf),
66
67    /// Indicating an error has occurred during processing. The packet will
68    /// be dropped from the output. Aborted packets are not bulk freed.
69    /// The packet is returned to mempool when it goes out of scope.
70    Abort(Error),
71}
72
73impl<T: Packet> Disposition<T> {
74    /// Easy way to map a `Disposition<T>` to a `Disposition<U>` by reducing
75    /// it down to a map from `T` to `Disposition<U>`.
76    fn map<U: Packet, F>(self, f: F) -> Disposition<U>
77    where
78        F: FnOnce(T) -> Disposition<U>,
79    {
80        match self {
81            Disposition::Act(packet) => f(packet),
82            Disposition::Emit => Disposition::Emit,
83            Disposition::Drop(mbuf) => Disposition::Drop(mbuf),
84            Disposition::Abort(err) => Disposition::Abort(err),
85        }
86    }
87
88    /// Returns whether the disposition is `Act`.
89    pub fn is_act(&self) -> bool {
90        matches!(self, Disposition::Act(_))
91    }
92
93    /// Returns whether the disposition is `Emit`.
94    pub fn is_emit(&self) -> bool {
95        matches!(self, Disposition::Emit)
96    }
97
98    /// Returns whether the disposition is `Drop`.
99    pub fn is_drop(&self) -> bool {
100        matches!(self, Disposition::Drop(_))
101    }
102
103    /// Returns whether the disposition is `Abort`.
104    pub fn is_abort(&self) -> bool {
105        matches!(self, Disposition::Abort(_))
106    }
107}
108
109/// Types that can receive packets.
110pub trait PacketRx {
111    /// Receives a batch of packets.
112    fn receive(&mut self) -> Vec<Mbuf>;
113}
114
115/// Types that can trasmit packets.
116pub trait PacketTx {
117    /// Transmits a batch of packets.
118    fn transmit(&mut self, packets: Vec<Mbuf>);
119}
120
121/// Common behaviors to apply on batches of packets.
122pub trait Batch {
123    /// The packet type.
124    type Item: Packet;
125
126    /// Replenishes the batch with new packets from the source.
127    fn replenish(&mut self);
128
129    /// Returns the disposition of the next packet in the batch.
130    ///
131    /// A value of `None` indicates that the batch is exhausted. To start
132    /// the next cycle, call [`replenish`] first.
133    ///
134    /// [`replenish`]: Batch::replenish
135    fn next(&mut self) -> Option<Disposition<Self::Item>>;
136
137    /// Creates a batch that transmits all packets through the specified
138    /// [`PacketTx`].
139    ///
140    /// Use when packets need to be delivered to a destination different
141    /// from the pipeline's main outbound queue. The send is immediate and
142    /// is not in batch. Packets sent with `emit` will be out of order
143    /// relative to other packets in the batch.
144    ///
145    /// # Example
146    ///
147    /// ```
148    /// let (tx, _) = mpsc::channel();
149    /// let mut batch = batch.emit(tx);
150    /// ```
151    ///
152    /// [`PacketTx`]: crate::batch::PacketTx
153    fn emit<Tx: PacketTx>(self, tx: Tx) -> Emit<Self, Tx>
154    where
155        Self: Sized,
156    {
157        Emit::new(self, tx)
158    }
159
160    /// Creates a batch that uses a predicate to determine if a packet
161    /// should be processed or dropped. If the predicate evaluates to `false`,
162    /// the packet is marked as dropped.
163    ///
164    /// # Example
165    ///
166    /// ```
167    /// let mut batch = batch.filter(|packet| {
168    ///     let v4 = packet.parse::<Ethernet>()?.parse::<Ipv4>()?;
169    ///     v4.ttl() > 0
170    /// });
171    /// ```
172    #[inline]
173    fn filter<P>(self, predicate: P) -> Filter<Self, P>
174    where
175        P: FnMut(&Self::Item) -> bool,
176        Self: Sized,
177    {
178        Filter::new(self, predicate)
179    }
180
181    /// Creates a batch that both [`filters`] and [`maps`].
182    ///
183    /// # Example
184    ///
185    /// ```
186    /// let mut batch = batch.filter_map(|packet| {
187    ///     let v4 = packet.parse::<Ethernet>()?.parse::<Ipv4>()?;
188    ///     if v4.protocol() == ProtocolNumbers::Udp {
189    ///         Ok(Either::Keep(v4))
190    ///     } else {
191    ///         Ok(Either::Drop(v4.reset()))
192    ///     }
193    /// });
194    /// ```
195    ///
196    /// [`filters`]: Batch::filter
197    /// [`maps`]: Batch::map
198    #[inline]
199    fn filter_map<T: Packet, F>(self, f: F) -> FilterMap<Self, T, F>
200    where
201        F: FnMut(Self::Item) -> Result<Either<T>>,
202        Self: Sized,
203    {
204        FilterMap::new(self, f)
205    }
206
207    /// Creates a batch that maps the packets to another packet type.
208    ///
209    /// # Example
210    ///
211    /// ```
212    /// let mut batch = batch.map(|packet| {
213    ///     packet.parse::<Ethernet>()?.parse::<Ipv4>()
214    /// });
215    /// ```
216    #[inline]
217    fn map<T: Packet, F>(self, f: F) -> Map<Self, T, F>
218    where
219        F: FnMut(Self::Item) -> Result<T>,
220        Self: Sized,
221    {
222        Map::new(self, f)
223    }
224
225    /// Calls a closure on each packet of the batch.
226    ///
227    /// Can be use for side-effect actions without the need to mutate the
228    /// packet. However, an error will abort the packet.
229    ///
230    /// # Example
231    ///
232    /// ```
233    /// let mut batch = batch.for_each(|packet| {
234    ///     println!("{:?}", packet);
235    ///     Ok(())
236    /// });
237    /// ````
238    #[inline]
239    fn for_each<F>(self, f: F) -> ForEach<Self, F>
240    where
241        F: FnMut(&Self::Item) -> Result<()>,
242        Self: Sized,
243    {
244        ForEach::new(self, f)
245    }
246
247    /// Calls a closure on each packet of the batch, including ones that are
248    /// already dropped, emitted or aborted.
249    ///
250    /// Unlike [`for_each`], `inspect` does not affect the packet disposition.
251    /// Useful as a debugging tool.
252    ///
253    /// # Example
254    ///
255    /// ```
256    /// let mut batch = batch.inspect(|disp| {
257    ///     if let Disposition::Act(v6) = disp {
258    ///         if v6.hop_limit() > A_HOP_LIMIT {
259    ///             debug!(...);
260    ///         }
261    ///     }
262    /// });
263    /// ```
264    ///
265    /// [`for_each`]: Batch::for_each
266    #[inline]
267    fn inspect<F>(self, f: F) -> Inspect<Self, F>
268    where
269        F: FnMut(&Disposition<Self::Item>),
270        Self: Sized,
271    {
272        Inspect::new(self, f)
273    }
274
275    /// Splits the packets into multiple sub batches. Each sub batch runs
276    /// through a separate pipeline, and are then merged back together.
277    ///
278    /// `selector` is a closure that receives a reference to the packet and
279    /// evaluates to a discriminator value. The underlying batch will be split
280    /// into sub batches based on this value.
281    ///
282    /// `composer` is a closure that constructs a hash map of batch pipeline
283    /// builders for each individual sub pipeline. The [`compose!`] macro is an
284    /// ergonomic way to write the composer closure. The syntax of the macro
285    /// loosely resembles the std `match` expression. Each match arm consists of
286    /// a single discriminator value mapped to a builder closure.
287    ///
288    /// If a packet does not match with an arm, it will be passed through to
289    /// the next combinator. Use the catch all arm `_` to make the matching
290    /// exhaustive.
291    ///
292    /// # Example
293    ///
294    /// ```
295    /// let mut batch = batch.group_by(
296    ///     |packet| packet.protocol(),
297    ///     |groups| {
298    ///         compose!( groups {
299    ///             ProtocolNumbers::Tcp => |group| {
300    ///                 group.map(do_tcp)
301    ///             }
302    ///             ProtocolNumbers::Udp => |group| {
303    ///                 group.map(do_udp)
304    ///             }
305    ///             _ => |group| {
306    ///                 group.map(unmatched)
307    ///             }
308    ///         })
309    ///     },
310    /// );
311    /// ```
312    ///
313    /// [`compose!`]: macro@compose
314    #[inline]
315    fn group_by<D, S, C>(self, selector: S, composer: C) -> GroupBy<Self, D, S>
316    where
317        D: Eq + Clone + Hash,
318        S: Fn(&Self::Item) -> D,
319        C: FnOnce(&mut HashMap<Option<D>, Box<GroupByBatchBuilder<Self::Item>>>),
320        Self: Sized,
321    {
322        GroupBy::new(self, selector, composer)
323    }
324
325    /// A batch that replaces each packet with another packet.
326    ///
327    /// Use for pipelines that generate new outbound packets based on inbound
328    /// packets and drop the inbound.
329    ///
330    /// # Example
331    ///
332    /// ```
333    /// let mut batch = batch.replace(|request| {
334    ///     let reply = Mbuf::new()?;
335    ///     let ethernet = request.peek::<Ethernet>()?;
336    ///     let mut reply = reply.push::<Ethernet>()?;
337    ///     reply.set_src(ethernet.dst());
338    ///     reply.set_dst(ethernet.src());
339    ///
340    ///     ...
341    ///
342    ///     Ok(reply)
343    /// });
344    fn replace<T: Packet, F>(self, f: F) -> Replace<Self, T, F>
345    where
346        F: FnMut(&Self::Item) -> Result<T>,
347        Self: Sized,
348    {
349        Replace::new(self, f)
350    }
351
352    /// Turns the batch pipeline into an executable task with default name.
353    ///
354    /// Send marks the end of the batch pipeline. No more combinators can be
355    /// appended after send.
356    ///
357    /// To give the pipeline a unique name, use
358    /// [`send_named`] instead.
359    ///
360    /// # Example
361    /// ```
362    /// Poll::new(q.clone()).map(map_fn).send(q);
363    /// ```
364    ///
365    /// [`send_named`]: Batch::send_named
366    #[inline]
367    fn send<Tx: PacketTx>(self, tx: Tx) -> Send<Self, Tx>
368    where
369        Self: Sized,
370    {
371        Batch::send_named(self, "default", tx)
372    }
373
374    /// Turns the batch pipeline into an executable task.
375    ///
376    /// `name` is used for logging and metrics. It does not need to be unique.
377    /// Multiple pipeline instances with the same name are aggregated together
378    /// into one set of metrics. Give each pipeline a different name to keep
379    /// metrics separated.
380    #[inline]
381    fn send_named<Tx: PacketTx>(self, name: &str, tx: Tx) -> Send<Self, Tx>
382    where
383        Self: Sized,
384    {
385        Send::new(name.to_owned(), self, tx)
386    }
387}
388
389/// Trait bound for batch pipelines. Can be used as a convenience for writing
390/// pipeline installers.
391///
392/// # Example
393///
394/// ```
395/// fn install(q: PortQueue) -> impl Pipeline {
396///     // install logic
397/// }
398/// ```
399pub trait Pipeline: futures::Future<Output = ()> {
400    /// Returns the name of the pipeline.
401    fn name(&self) -> &str;
402
403    /// Runs the pipeline once to process one batch of packets.
404    fn run_once(&mut self);
405}
406
407/// Splices a [`PacketRx`] directly to a [`PacketTx`] without any intermediary
408/// combinators.
409///
410/// Useful for pipelines that perform simple forwarding without any packet
411/// processing.
412///
413/// # Example
414///
415/// ```
416/// Runtime::build(config)?
417///     .add_pipeline_to_port("kni0", |q| {
418///         batch::splice(q.clone(), q.kni().unwrap().clone())
419///     });
420/// ```
421///
422/// [`PacketRx`]: crate::batch::PacketRx
423/// [`PacketTx`]: crate::batch::PacketTx
424pub fn splice<Rx: PacketRx + Unpin, Tx: PacketTx + Unpin>(rx: Rx, tx: Tx) -> impl Pipeline {
425    Poll::new(rx).send(tx)
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431    use crate::compose;
432    use crate::packets::ip::v4::Ipv4;
433    use crate::packets::ip::ProtocolNumbers;
434    use crate::packets::Ethernet;
435    use crate::testils::byte_arrays::{ICMPV4_PACKET, IPV4_TCP_PACKET, IPV4_UDP_PACKET};
436    use std::sync::mpsc::{self, TryRecvError};
437
438    fn new_batch(data: &[&[u8]]) -> impl Batch<Item = Mbuf> {
439        let packets = data
440            .iter()
441            .map(|bytes| Mbuf::from_bytes(bytes).unwrap())
442            .collect::<Vec<_>>();
443
444        let (mut tx, rx) = mpsc::channel();
445        tx.transmit(packets);
446        let mut batch = Poll::new(rx);
447        batch.replenish();
448        batch
449    }
450
451    #[capsule::test]
452    fn emit_batch() {
453        let (tx, mut rx) = mpsc::channel();
454
455        let mut batch = new_batch(&[&IPV4_UDP_PACKET])
456            .map(|p| p.parse::<Ethernet>())
457            .emit(tx)
458            .for_each(|_| panic!("emit broken!"));
459
460        assert!(batch.next().unwrap().is_emit());
461
462        // sent to the tx
463        assert_eq!(1, rx.receive().len());
464    }
465
466    #[capsule::test]
467    fn filter_batch() {
468        let mut batch = new_batch(&[&IPV4_UDP_PACKET]).filter(|_| true);
469        assert!(batch.next().unwrap().is_act());
470
471        let mut batch = new_batch(&[&IPV4_UDP_PACKET]).filter(|_| false);
472        assert!(batch.next().unwrap().is_drop());
473    }
474
475    #[capsule::test]
476    fn filter_map_batch() {
477        let mut batch = new_batch(&[&IPV4_UDP_PACKET, &ICMPV4_PACKET]).filter_map(|p| {
478            let v4 = p.parse::<Ethernet>()?.parse::<Ipv4>()?;
479            if v4.protocol() == ProtocolNumbers::Udp {
480                Ok(Either::Keep(v4))
481            } else {
482                Ok(Either::Drop(v4.reset()))
483            }
484        });
485
486        // udp is let through
487        assert!(batch.next().unwrap().is_act());
488        // icmp is dropped
489        assert!(batch.next().unwrap().is_drop());
490        // at the end
491        assert!(batch.next().is_none());
492    }
493
494    #[capsule::test]
495    fn map_batch() {
496        let mut batch = new_batch(&[&IPV4_UDP_PACKET]).map(|p| p.parse::<Ethernet>());
497        assert!(batch.next().unwrap().is_act());
498
499        // can't shrink the mbuf that much
500        let mut batch = new_batch(&[&IPV4_UDP_PACKET]).map(|mut p| {
501            p.shrink(0, 999_999)?;
502            Ok(p)
503        });
504        assert!(batch.next().unwrap().is_abort());
505    }
506
507    #[capsule::test]
508    fn for_each_batch() {
509        let mut side_effect = false;
510
511        let mut batch = new_batch(&[&IPV4_UDP_PACKET]).for_each(|_| {
512            side_effect = true;
513            Ok(())
514        });
515
516        assert!(batch.next().unwrap().is_act());
517        assert!(side_effect);
518    }
519
520    #[capsule::test]
521    fn inspect_batch() {
522        let mut side_effect = false;
523
524        let mut batch = new_batch(&[&IPV4_UDP_PACKET]).inspect(|_| {
525            side_effect = true;
526        });
527
528        assert!(batch.next().unwrap().is_act());
529        assert!(side_effect);
530    }
531
532    #[capsule::test]
533    fn group_by_batch() {
534        let mut batch = new_batch(&[&IPV4_TCP_PACKET, &IPV4_UDP_PACKET, &ICMPV4_PACKET])
535            .map(|p| p.parse::<Ethernet>()?.parse::<Ipv4>())
536            .group_by(
537                |p| p.protocol(),
538                |groups| {
539                    compose!( groups {
540                        ProtocolNumbers::Tcp => |group| {
541                            group.map(|mut p| {
542                                p.set_ttl(1);
543                                Ok(p)
544                            })
545                        }
546                        ProtocolNumbers::Udp => |group| {
547                            group.map(|mut p| {
548                                p.set_ttl(2);
549                                Ok(p)
550                            })
551                        }
552                        _ => |group| {
553                            group.filter(|_| {
554                                false
555                            })
556                        }
557                    })
558                },
559            );
560
561        // first one is the tcp arm
562        let disp = batch.next().unwrap();
563        assert!(disp.is_act());
564        if let Disposition::Act(pkt) = disp {
565            assert_eq!(1, pkt.ttl());
566        }
567
568        // next one is the udp arm
569        let disp = batch.next().unwrap();
570        assert!(disp.is_act());
571        if let Disposition::Act(pkt) = disp {
572            assert_eq!(2, pkt.ttl());
573        }
574
575        // last one is the catch all arm
576        assert!(batch.next().unwrap().is_drop());
577    }
578
579    #[capsule::test]
580    fn group_by_no_catchall() {
581        let mut batch = new_batch(&[&ICMPV4_PACKET])
582            .map(|p| p.parse::<Ethernet>()?.parse::<Ipv4>())
583            .group_by(
584                |p| p.protocol(),
585                |groups| {
586                    compose!( groups {
587                        ProtocolNumbers::Tcp => |group| {
588                            group.filter(|_| false)
589                        }
590                    })
591                },
592            );
593
594        // did not match, passes through
595        assert!(batch.next().unwrap().is_act());
596    }
597
598    #[capsule::test]
599    fn group_by_or() {
600        let mut batch = new_batch(&[&IPV4_TCP_PACKET, &IPV4_UDP_PACKET, &ICMPV4_PACKET])
601            .map(|p| p.parse::<Ethernet>()?.parse::<Ipv4>())
602            .group_by(
603                |p| p.protocol(),
604                |groups| {
605                    compose!( groups {
606                        ProtocolNumbers::Tcp, ProtocolNumbers::Udp => |group| {
607                            group.map(|mut p| {
608                                p.set_ttl(1);
609                                Ok(p)
610                            })
611                        }
612                        _ => |group| {
613                            group.filter(|_| {
614                                false
615                            })
616                        }
617                    })
618                },
619            );
620
621        // first one is the tcp arm
622        let disp = batch.next().unwrap();
623        assert!(disp.is_act());
624        if let Disposition::Act(pkt) = disp {
625            assert_eq!(1, pkt.ttl());
626        }
627
628        // next one is the udp arm
629        let disp = batch.next().unwrap();
630        assert!(disp.is_act());
631        if let Disposition::Act(pkt) = disp {
632            assert_eq!(1, pkt.ttl());
633        }
634
635        // last one is the catch all arm
636        assert!(batch.next().unwrap().is_drop());
637    }
638
639    #[capsule::test]
640    fn group_by_or_no_catchall() {
641        let mut batch = new_batch(&[&IPV4_TCP_PACKET, &IPV4_UDP_PACKET])
642            .map(|p| p.parse::<Ethernet>()?.parse::<Ipv4>())
643            .group_by(
644                |p| p.protocol(),
645                |groups| {
646                    compose!( groups {
647                        ProtocolNumbers::Tcp, ProtocolNumbers::Udp => |group| {
648                            group.map(|mut p| {
649                                p.set_ttl(1);
650                                Ok(p)
651                            })
652                        }
653                    })
654                },
655            );
656
657        // first one is the tcp arm
658        let disp = batch.next().unwrap();
659        assert!(disp.is_act());
660        if let Disposition::Act(pkt) = disp {
661            assert_eq!(1, pkt.ttl());
662        }
663
664        // next one is the udp arm
665        let disp = batch.next().unwrap();
666        assert!(disp.is_act());
667        if let Disposition::Act(pkt) = disp {
668            assert_eq!(1, pkt.ttl());
669        }
670    }
671
672    #[capsule::test]
673    fn group_by_fanout() {
674        let mut batch = new_batch(&[&IPV4_TCP_PACKET])
675            .map(|p| p.parse::<Ethernet>()?.parse::<Ipv4>())
676            .group_by(
677                |p| p.protocol(),
678                |groups| {
679                    compose!( groups {
680                        ProtocolNumbers::Tcp => |group| {
681                            group.replace(|_| {
682                                Mbuf::from_bytes(&IPV4_UDP_PACKET)?
683                                    .parse::<Ethernet>()?
684                                    .parse::<Ipv4>()
685                            })
686                        }
687                    })
688                },
689            );
690
691        // replace inside group_by will produce a new UDP packet
692        // and marks the original TCP packet as dropped.
693        assert!(batch.next().unwrap().is_act());
694        assert!(batch.next().unwrap().is_drop());
695        assert!(batch.next().is_none());
696    }
697
698    #[capsule::test]
699    fn replace_batch() {
700        let mut batch =
701            new_batch(&[&IPV4_UDP_PACKET]).replace(|_| Mbuf::from_bytes(&IPV4_TCP_PACKET));
702
703        // first one is the replacement
704        assert!(batch.next().unwrap().is_act());
705        // next one is the original
706        assert!(batch.next().unwrap().is_drop());
707        // at the end
708        assert!(batch.next().is_none());
709    }
710
711    #[capsule::test]
712    fn poll_fn_batch() {
713        let mut batch = poll_fn(|| vec![Mbuf::new().unwrap()]);
714        batch.replenish();
715
716        assert!(batch.next().unwrap().is_act());
717        assert!(batch.next().is_none());
718    }
719
720    #[capsule::test]
721    fn splice_pipeline() {
722        let (mut tx1, rx1) = mpsc::channel();
723        let (tx2, rx2) = mpsc::channel();
724
725        // no packet yet
726        let mut pipeline = splice(rx1, tx2);
727        pipeline.run_once();
728        assert_eq!(TryRecvError::Empty, rx2.try_recv().unwrap_err());
729
730        // send one packet
731        let packet = Mbuf::from_bytes(&IPV4_UDP_PACKET).unwrap();
732        tx1.transmit(vec![packet]);
733        pipeline.run_once();
734        assert!(rx2.try_recv().is_ok());
735    }
736}