> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/fpp/2.9/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/components/fpp/2.9/memcap.md).

# VPP interface traffic capturing

You can use the MEMCAP plugin for traffic capturing.

MEMCAP is a framework that defines and implements a protocol for offloading the traffic capturing process using the memory-mapped interface. This approach reduces the operational overhead on the capturing component. Captured data is subsequently collected and processed by the MEMCAP Sink sub-component. By delegating resource-intensive tasks, such as I/O processing and system upgrades, to separate components, MEMCAP reduces resource requirements and improves scalability.

The Fast Path Provider (FPP) pod acts as a traffic collector and communicates with the MEMCAP Sink pod using a shared memory interface. Multiple FPP-based instances, such as FPP, Connectivity Gateway (CGW) or User Plane Gateway (UPG), located on a single node communicate with a single MEMCAP Sink pod located on the same node.

![MEMCAP diagram](https://docs.cennso.com/api/assets/components/fpp/2.9/assets/memcap-nats-diagram.svg)

MEMCAP allows for collecting PCAP files in a single place using [NATS](https://nats.io/) to aggregate traffic streams. You can configure the MEMCAP Sink component to send formatted PCAP data to the NATS server, either in publisher-subscriber ([NATS Core](https://docs.nats.io/nats-concepts/core-nats)) mode or in the [JetStream](https://docs.nats.io/nats-concepts/jetstream) mode. The MEMCAP Consumer component retrieves these PCAPs from the NATS server and merges traffic streams into one PCAP file. It can run in the same cluster or a central cluster to gather traffic from multiple Core Clusters. This setup provides a single access point for all PCAPs.

## Terminology

Here's the terminology used within this document:

- Collector - FPP pod which provides capture streams. It can provide multiple PCAP streams in parallel.
- Sink - a component that receives data from collectors, processes it, and either saves it as a local `.pcapng` file or sends it as a NATS message.
- Consumer - a component that connects to the NATS server, converts PCAP data from NATS messages into a `.pcapng` file, and provides an HTTP stream for traffic.
- Class - a traffic class which allows for different processing in MEMCAP Sink. For example, `hw_iface_l2` is a VPP interface-based L2 traffic capturing, and `upf_session_ip` is a UPG IMSI-based IP traffic capturing.
- Target - an arbitrary name used to direct traffic capture streams to destinations. On the collector side, different traffic capture streams can use the same target name. On the MEMCAP Sink side, different destinations can use the same target name as well. Target names can be chosen arbitrarily and do not require provisioning in advance.
- Stream - an instance of active traffic capture. For example, a stream of interface `eth0` to target `eth-if` with class `hw_iface_l2`.
- Destination - the endpoint for a PCAP stream, which can be a file, an HTTP stream, or a NATS cluster.

MEMCAP consists of the following sub-components:

- **VPP MEMCAP plugin** implements the collector side of the MEMCAP connection. It implements the `hw_iface_l2` collector, which allows you to collect traffic from L2 VPP interfaces. It also provides a framework for easy integration with other VPP plugins.

- **MEMCAP Sink** manages connections to collectors and processes the captured traffic data. It outputs the data in the `.pcapng` file format, which you can send over NATS or save to a disk with options for compression and rotation. Additionally, it allows streaming of `.pcapng` files over an HTTP connection for real-time analysis.

- **MEMCAP Consumer** connects to the NATS server, listens for PCAP data sent as NATS message payload, and combines traffic from multiple MEMCAP Sinks into a single `.pcapng` file. It provides a single access point for users to view aggregated data from one or more Core Clusters. It also offers an HTTP endpoint for real-time analysis.

This is a sample operational workflow:

![MEMCAP flow](https://docs.cennso.com/api/assets/components/fpp/2.9/assets/memcap-flow.svg)

A packet stream is generated inside a VPP instance (FPP node, CGW, or UPG) and identified by its target name (tag). The MEMCAP Sink aggregates traffic from multiple streams based on their target names (tags), converts it to PCAP, and forwards it to destinations, such as a local PCAP file, a NATS subject, or an HTTP endpoint for Wireshark attachment.

For a NATS destination, MEMCAP Sink sends the formatted PCAP as a NATS message payload using a subject. MEMCAP Consumer listens on a specific subject and saves the data to a PCAP file. End users can also connect to the HTTP endpoint with Wireshark.

## Installation

### VPP MEMCAP plugin

The MEMCAP plugin is included in FPP 2.4.0 or newer images. You must install the FPP deployment using at least 2.4.0 chart. It automatically enables the VPP traffic capturing with MEMCAP Sink running on the worker node. You can use the feature using VPPCTL after the deployment.

>**NOTE:** When using FPP operator version `v2.3.1` or older, you can install FPP-based deployment using the 2.4.0 or newer chart, which enables communication with MEMCAP by default.

### MEMCAP Sink and Consumer

MEMCAP is installed as a regular Helm chart. The chart includes MEMCAP Sink, running as a DaemonSet on all nodes with FPP workloads, and MEMCAP Consumer, deployed as a StatefulSet.

To install it, use the following command:

```bash
helm upgrade --install memcap cennso/memcap -f ./values/memcap.yaml  -n fpp --version 0.5.0
```

The `-n fpp` part of the command specifies a namespace where the MEMCAP sink will be deployed. For more details about the `memcap.yaml` file, read the Configuration section below.

## Configuration

### VPP MEMCAP plugin configuration

You can configure the VPP MEMCAP plugin included in the FPP image with these parameters:
- **memcapName** - adds the name of the MEMCAP collector. It is used to differentiate the source of the traffic stream. By default, it is set to the Kubernetes worker node name.
- **memcapSocketPath** - configures the MEMCAP Sink socket path used to connect from the plugin to the Sink. By default, it is set to `/run/vppswitch/sink.sock`.

See the configuration example in the FPP chart:

```yaml
vpp:
  memcapName: test
  memcapSocketPath: /some/test/path.sock
```

It will result in the following VPPDeployment CR:

```yaml
apiVersion: fpp-manager.cennso.com/v1alpha1
kind: VPPDeployment
metadata:
  name: fpp-node
spec:
  type: node
  containerOptions:
    ...
  podOptions:
    ...
  vppOptions:
    memcapName: test
    memcapSocketPath: /some/test/path.sock
```

### MEMCAP chart configuration

You can configure MEMCAP using Helm chart configurable parameters. Such configuration allows you to:
- Configure NATS connectivity, including server URL, cluster name, and JetStream management
- Define the stream’s source and destination
  - Memif socket and targets
  - NATS: subject, server URL override, mode (`jetstream` or `pubsub`)
  - PCAP file options: file prefix, rotation options (maximum number of packets, time, or size), and file compression
- Deploy Prometheus services for metrics capturing
- Configure RClone as a side-container for PCAP transferring

These are the general parameters that you can configure:

| Key | Type | Default | Description |
|---|---|---|---|
| annotations | object | `{}` | Additional annotations for all resources except for the DaemonSet's pods. |
| imagePullSecrets | list | `[]` | `imagePullSecrets` used for pulling the images. Sample value: `[{name: "regcred"}]`. |
| labels | object | `{}` | Additional labels for all resources except for the DaemonSet's pods | |
| podAnnotations | object | `{}` | Additional annotations for pods |
| podLabels | object | `{}` | Additional labels only for pods |
| prometheus.enabled | bool | `true` | Enables the Kubernetes service for the metrics endpoint |
| prometheus.servicemonitor.enabled | bool | `true` | Enables Kubernetes ServiceMonitor |
| rclone.enabled | bool | `false` | Enables Rclone data synchronization |
| rclone.image.pullPolicy | string | `"IfNotPresent"` | Image pull policy. The possible values are: `Always`, `IfNotPresent`, and `Never`. |
| rclone.image.repository | string | `"registry.cennso.com/cennso/docker-rclone"` | Repository where the Docker Rclone's image is stored |
| rclone.image.tag | string | `"v1.60.1-sec.2"` | Image tag |
| rclone.instances | list | `[]` | Rclone instances to deploy as additional containers |
| rclone.path | string | `"/data"` | Filesystem path where the PCAP volume is mounted |
| rclone.resources.limits.cpu | string | `"50m"` | CPU limit for the RClone container. |
| rclone.resources.limits.memory | string | `"256Mi"` | Memory limit for the RClone container. |
| rclone.resources.requests.cpu | string | `"50m"` | CPU request for the RClone container. |
| rclone.resources.requests.memory | string | `"64Mi"` | Memory request for the RClone container. |
| rclone.storageSpec | object | `{"emptyDir":{"sizeLimit":"10Gi"}}` | Specifies custom storage for MEMCAP Sink's PCAP files when `rclone.enabled=true`. This storage replaces the default PCAP storage. Ensure the configured size can hold all PCAP files for all targets. |

#### MEMCAP Sink configuration

You can configure MEMCAP Sink with these chart configuration parameters:

| Key | Type | Default | Description |
|---|---|---|---|
| memcapSink.additionalLabels | object | `{}` | Additional labels for all resources created for MEMCAP Sink |
| memcapSink.affinity | object | `{}` | Assigns custom affinity rules to MEMCAP Sink. For more information, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/). |
| memcapSink.enabled | bool | `true` | Enables MEMCAP Sink DaemonSet deployment |
| memcapSink.envs | list | `[]` | Custom environment variables for the MEMCAP container. Sample value: `[{"name":"APP_EXAMPLE_NAME","value":"APP_EXAMPLE_VALUE"}]` |
| memcapSink.image.pullPolicy | string | `"IfNotPresent"` | Image pull policy. The possible values are: `Always`, `IfNotPresent`, and `Never`. |
| memcapSink.image.repository | string | `"registry.cennso.com/cennso/memcap-sink"` | Repository where the MEMCAP Sink's image is stored |
| memcapSink.image.tag | string | `""` | Overrides the image tag, which defaults to the chart appVersion. |
| memcapSink.logLevel | string | `"info"` | Log level. The possible values: `panic`, `fatal`, `error`, `warn`, `info`, `debug`, `trace`. |
| memcapSink.nats | object | `{"clusterName":"","manageStream":false,"streamConfig":{},"streamName":"cdm-pcaps","url":"nats://test-url"}` | NATS configuration |
| memcapSink.nats.clusterName | string | `""` | Cluster name used for NATS subject generation. If empty, the cluster name is taken from the NATS connection info. |
| memcapSink.nats.manageStream | bool | `false` | Enables JetStream to create the stream specified in `streamConfig` |
| memcapSink.nats.streamConfig | object | `{}` | Stream configuration that contains all applicable parameters |
| memcapSink.nats.streamConfig.max_msgs | int | `-1` | Maximum number of messages stored in a JetStream. `-1` is unlimited. |
| memcapSink.nats.streamConfig.max_bytes | int | `10737418240` | Stream capacity in bytes |
| memcapSink.nats.streamName | string | `"cdm-pcaps"` | JetStream name used for PCAPs |
| memcapSink.nats.url | string | `"nats://test-url"` | Sets the connection URL unless the PCAP stream source or destination overrides it |
| memcapSink.nodeSelector | object | `{}` | Selects nodes where the MEMCAP Sink should run. For more information about nodeSelectors, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector/). |
| memcapSink.resources.cpu | string | `"500m"` | CPU assigned to the MEMCAP container. For more information about resource assignment, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). |
| memcapSink.resources.memory | string | `"256Mi"` | Memory assigned to the MEMCAP container. For more information about resource assignment, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). |
| memcapSink.streams | list | `[{"destinations":[],"source":{"memif":{"targets":["pfcp"]}}}]` | List of streams |
| memcapSink.streams[0] | object | `{"destinations":[],"source":{"memif":{"targets":["pfcp"]}}}` | Stream source from which data is fetched |
| memcapSink.streams[].destinations | list | `[]` | List of destinations where the stream source will be sent. A destination can include a PCAP file or NATS. |
| memcapSink.streams[0].destinations[].file | object | `{}` | Configuration of a PCAP destination file |
| memcapSink.streams[0].destinations[].file.compress | string | `""` | Defines compression algorithm, available options: `none`, `zstd`, `lz4`, `gzip`. |
| memcapSink.streams[0].destinations[].file.compressLevel | int | `0` | Defines comression level. The value depends on the algorithm defined in **memcapSink.streams[0].destinations[].file.compress**. |
| memcapSink.streams[0].destinations[].file.compressed | bool | `false` | Enables compression for files. `zstd` is used by default. |
| memcapSink.streams[0].destinations[].file.path_prefix | string | `""` | Prefix for autogenerated file names. |
| memcapSink.streams[0].destinations[].file.max_bytes | int | `0` | Total packet size limit that triggers file rotation |
| memcapSink.streams[0].destinations[].file.max_duration | string | `0m0s` | Time limit to trigger rotation. |
| memcapSink.streams[0].destinations[].file.max_files | int | `0` | Limit on the total number of files when rotation is enabled. |
| memcapSink.streams[0].destinations[].file.max_packets | int | `0` | Limit on the number of packets to trigger file rotation. |
| memcapSink.streams[0].destinations[].file.rotate | bool | `false` | Enables file rotation. |
| memcapSink.streams[0].destinations[].nats | object | `{}` | Configuration of NATS destination. |
| memcapSink.streams[0].destinations[].nats.batchSize | int | `0` | Defines the maximum number of packets in each NATS message. |
| memcapSink.streams[0].destinations[].nats.headers | string | `""` | A key/value pair included in the NATS header message. Example: `{apn: test.cennso.com, test-line: line-4}`. |
| memcapSink.streams[0].destinations[].nats.subject | string | `""` | Defines a subject for NATS message publishing. Example: `pcaps.{CLUSTER}.{TARGET}` |
| memcapSink.streams[0].destinations[].nats.url | string | `` | NATS connection URL. |
| memcapSink.streams[0].source.memif | object | `{"targets":["pfcp"]}` | If set, it specifies that the PCAP stream is collected from the connected VPP instance. |
| memcapSink.streams[0].source.memif.targets | list | `["pfcp"]` | List of targets defined in VPP instance that the stream will capture |
| memcapSink.tolerations | list | `[]` | Kubernetes tolerations. For more information, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). |

You can reload the MEMCAP Sink configuration at runtime. The configuration is stored in a ConfigMap. When you apply a new configuration, the ConfigMap content is updated inside the MEMCAP pod. It can take up to 1 minute for changes to propagate. MEMCAP checks the local file at regular intervals. If the content has changed since the last update, MEMCAP parses the new configuration and restarts the affected threads to apply the changes.

See the MEMACAP Sink configuration example that creates four threads, one for each pair of source and destination:

```yaml
imagePullSecrets:
- name: cur-secret
memcapSink:
  enabled: true
  logLevel: trace
  hostSocketDirectory: /run/vppswitch
  nats:
    url: "nats://cdm-local.cennso-system:4222"
    clusterName: "test-cluster"
  streams:
  - source:
      memif:
        targets: [pgw-pfcp]
    destinations:
    - file:
        path_prefix: "pfcp"
        rotate: true
        max_packets: 100000
        max_files: 2
        compressed: true
    - nats:
        enabled: true
        headers:
          apn: test.cennso.com
          test-line: line-4
  - source:
      memif:
        targets: [sgi]
    destinations:
    - nats:
        subject: "pcaps.{CLUSTER}.{TARGET}"
  - source:
      memif:
        targets: [cgw-apn]
    destinations:
    - file:
        path_prefix: "cgw-apn"
        max_packets: 100000
        compressed: true
  tolerations:
  - effect: NoSchedule
    key: node-role.cennso.net/dataplane
    value: "true"
```

In the example above, traffic from the target `pgw-pfcp` is saved to a PCAP file and sent to NATS. The PCAP file is stored in the MEMCAP Sink pod, in the location specified in the **path_prefix** field. Each PCAP file can hold 100,000 packets; a new file is created once this limit is reached. Rotation is enabled, so only two files will be kept. When the limit is reached, the older file is deleted. This means that traffic is collected continuously, but data is lost after 200,000 packets. NATS messages are sent with the subject `pcaps.test-cluster.pgw-pfcp`; the NATS URL is defined in the global configuration **memcapSink.nats.url** as `nats://cdm-local.cennso-system:4222`.

Target `sgi` is sent only through NATS to MEMCAP Consumer.

The last target, `cgw-apn`, is saved only to the local disk. The PCAP file is stored in the MEMCAP Sink pod at the location specified by the **path_prefix** field. It will collect up to 100,000 packets; after that, traffic will not be saved.

You can copy a PCAP file from the pod to an external machine for further analysis. For example, you can use this command:

```bash
kubectl cp -n fpp ${memcap-sink}:/root/dumps/pfcp_2024-11-13T16:35:19.961206426Z.pcapng.zstd ./trace-file.pcapng.zstd
```

#### MEMCAP Consumer configuration

You can configure MEMCAP Consumer with these chart configuration parameters:

| Key | Type | Default | Description |
|---|---|---|---|
| memcapConsumer.additionalLabels | object | `{}` | Additional labels for all resources created for MEMCAP Consumer |
| memcapConsumer.affinity | object | `{}` | Assigns custom affinity rules to MEMCAP Consumer. For more information, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/). |
| memcapConsumer.enabled | bool | `true` | Enables the MEMCAP Consumer StatefulSet |
| memcapConsumer.envs | list | `[]` | Custom environment variables for the MEMCAP container. Sample value: `[{"name":"APP_EXAMPLE_NAME","value":"APP_EXAMPLE_VALUE"}]` |
| memcapConsumer.image.pullPolicy | string | `"IfNotPresent"` | Image pull policy. The possible values are: `Always`, `IfNotPresent`, and `Never`. |
| memcapConsumer.image.repository | string | `"registry.cennso.com/cennso/memcap-sink"` | Repository where the MEMCAP-Sink's image is stored |
| memcapConsumer.image.tag | string | `""` | Overrides the image tag, which defaults to the chart appVersion. |
| memcapConsumer.logLevel | string | `"info"` | Log level. The possible values: `panic`, `fatal`, `error`, `warn`, `info`, `debug`, `trace`. |
| memcapConsumer.nats | object | `{"clusterName":"test-cluster","manageStream":false,"streamConfig":{},"streamName":"cdm-pcaps","url":"nats://test-url"}` | NATS configuration |
| memcapConsumer.nats.clusterName | string | `"test-cluster"` | Explicit name of the cluster, used for cluster identification for the [durable consumer](https://docs.nats.io/nats-concepts/jetstream/consumers#persistence-durable-ephemeral) |
| memcapConsumer.nats.manageStream | bool | `false` | Enables JetStream to create the stream specified in `nats.streamConfig` |
| memcapConsumer.nats.streamConfig | object | `{}` | Stream configuration that contains all applicable parameters |
| memcapConsumer.nats.streamConfig.max_msgs | int | `-1` | Maximum number of messages stored in a JetStream. `-1` is unlimited. |
| memcapConsumer.nats.streamConfig.max_bytes | int | `10737418240` | Stream capacity in bytes |
| memcapConsumer.nats.streamName | string | `"cdm-pcaps"` | JetStream name used for PCAPs |
| memcapConsumer.nats.url | string | `"nats://test-url"` | Sets the connection URL unless the PCAP stream source or destination overrides it |
| memcapConsumer.nodeSelector | object | `{}` | Selects nodes where MEMCAP Sink should run. For more information about nodeSelectors, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector/). |
| memcapConsumer.resources.cpu | string | `"500m"` | CPU assigned to the MEMCAP container. For more information about resource assignment, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). |
| memcapConsumer.resources.memory | string | `"256Mi"` | Memory assigned to the MEMCAP container. For more information about resource assignment, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). |
| memcapConsumer.streams | list | `[{"destinations":[],"source":{"nats":{"mode":"pubsub","name":"debug","subject":"pcaps.*","url":"nats://nats.default"}}}]` | List of streams |
| memcapConsumer.streams[] | object | `{"destinations":[],"source":{"nats":{"mode":"pubsub","name":"debug","subject":"pcaps.*","url":"nats://nats.default"}}}` | Stream source from which data is fetched |
| memcapConsumer.streams[].destinations | list | `[]` | List of destinations where the stream source will be sent. Destinations can include a PCAP file. |
| memcapConsumer.streams[0].destinations[].file | object | `{}` | Configuration of a PCAP destination file |
| memcapConsumer.streams[0].destinations[].file.compress | string | `""` | Defines compression algorithm, available options: `none`, `zstd`, `lz4`, `gzip`. |
| memcapConsumer.streams[0].destinations[].file.compressLevel | int | `0` | Defines comression level. The value depends on the algorithm defined in **memcapConsumer.streams[0].destinations[].file.compress**. |
| memcapConsumer.streams[0].destinations[].file.compressed | bool | `false` | Enables compression for files. `zstd` is used by default. |
| memcapConsumer.streams[0].destinations[].file.path_prefix | string | `""` | Prefix for autogenerated file names. |
| memcapConsumer.streams[0].destinations[].file.max_bytes | int | `0` | Total packet size limit that triggers file rotation |
| memcapConsumer.streams[0].destinations[].file.max_duration | string | `0m0s` | Time limit to trigger file rotation |
| memcapConsumer.streams[0].destinations[].file.max_files | int | `0` | Limit on the total number of files before triggering rotation |
| memcapConsumer.streams[0].destinations[].file.max_packets | int | `0` | Limit on the number of packets to trigger file rotation. |
| memcapConsumer.streams[0].destinations[].file.rotate | bool | `false` | Enables file rotation. |
| memcapConsumer.streams[0].source.nats | object | `{"mode":"pubsub","name":"debug","subject":"pcaps.*","url":"nats://nats.default"}` | If specified, a PCAP stream is fetched from NATS. |
| memcapConsumer.streams[0].source.nats.mode | string | `"pubsub"` | Specifies a NATS mode, either `pubsub` or `jetstream`. |
| memcapConsumer.streams[0].source.nats.name | string | `"debug"` | Name of the aggregated PCAP stream, used for attaching an HTTP endpoint |
| memcapConsumer.streams[0].source.nats.subject | string | `"pcaps.*"` | In the `pubsub` mode, MEMCAP Consumer listens to messages on the specified subject, which can include wildcards (`*` or `>`). The subject is also used for attaching an HTTP endpoint. |
| memcapConsumer.streams[0].source.nats.url | string | `"nats://nats.default"` | NATS connection URL |
| memcapConsumer.tolerations | list | `[]` | Kubernetes tolerations. For more information, read the official [Kubernetes documentation](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). |

See the MEMACAP Consumer configuration example that creates one thread for fetching the PCAP data from NATS to the `.pcapng` file:

```yaml
imagePullSecrets:
- name: cur-secret
memcapConsumer:
  enabled: true
  logLevel: trace
  nats:
    clusterName: test-cluster
    url: "nats://cdm-local.cennso-system:4222"
    streamName: pcaps-test-cluster
    manageStream: true
    streamConfig:
      subjects:
        - pcaps.test-cluster.>
      max_bytes: 1073741824
  streams:
  - source:
      nats:
        name: debug
        mode: jetstream
        subject: "pcaps.test-cluster.*"
    destinations:
    - file:
        path_prefix: "pfcp"
        rotate: true
        max_packets: 100000
        max_files: 10
        compressed: true
  tolerations:
  - effect: NoSchedule
    key: node-role.cennso.net/dataplane
    value: "true"
```

MEMCAP Consumer has JetStream management enabled, so it will create a JetStream named `pcaps-test-cluster` with the following settings:

- Messages sent to the subject `pcaps.test-cluster.>` will be stored in the stream.
- The maximum size for stored messages is 1 GiB (1,073,741,824 bytes).

The source is configured to use NATS in the JetStream mode, which means that MEMCAP Consumer creates a [durable NATS consumer](https://docs.nats.io/nats-concepts/jetstream/consumers#persistence-durable-ephemeral). This allows the Consumer to fetch all stored messages from the NATS server, even if the MEMCAP Consumer is offline. In the `pubsub` mode, the Consumer can only fetch messages sent while it is online, so any previous data is lost.

The `source.nats.name` is used to identify the HTTP endpoint attachment. The name must be unique in the MEMCAP Consumer configuration; otherwise, only the first matching source will be used when attaching with Wireshark. To live-debug the PCAPs, use Wireshark:

```bash
curl --compressed localhost:9999/pcap/debug -N | wireshark -k -i - -o 'gui.window_title:memcap-stream' -o 'capture.no_interface_load:TRUE'
```

The destination is of `file` type, typically used to store PCAPs sent over NATS to a file.

#### NATS subject configuration

MEMCAP Sink supports automatic subject generation based on traffic metadata.

The available metadata:
- VPP name (token **{POD}**) - Custom name assigned in **startup.conf** or a pod name if not defined
- Namespace (token **{NAMESPACE}**) - Namespace of the VPP pod (CGW/FPP/UPG)
- Stream labels (for example token **{apn}** for `MEMCAP_APN`) - Environment variables defined in the VPP pod (CGW/FPP/UPG) starting with `MEMCAP_`, which are attached to traffic metadata
- Filter (token **{FILTER}**) - Libpcap-based filters that are the same as in the tcpdump utility
- IMSI (token **{IMSI}**) - IMSI attached to UPG session traffic
- Interface (token **{INTERFACE}**) - Name of the interface where the traffic is captured
- NWI (token **{NWI}**) - Name of the network instance for the captured traffic (Available in future MEMCAP release, 0.6.1 or later)
- Target (token **{TARGET}**) - Traffic tag

> **NOTE**: To get new metadata, use FPP 2.8.0 and UPG 2.16.0 or newer.

Subjects in the NATS destination configuration can:
- be explicitly defined, using available tokens (`{CLUSTER`, `{TARGET}`, and so on) to generate the subject
  - `pcaps.cluster.{CLUSTER}.{apn}.{TARGET}`, where `{apn}` is defined in the environmental variables in the VPP pod (`MEMCAP_APN=test.cennso.com`)
- use default subject layout (`com.cennso.memcap.v1alpha1.pcaps.cluster...`) with the **streams[].destinations[].nats.enabled** configuration value
  - the default subject evaluation is explained below:

```yaml
memcapSink:
  enabled: true
  logLevel: trace
  nats:
    url: "nats://nats.default"
    clusterName: test-cluster # can be taken from NATS connection info if not defined
  streams:
  - source:
      memif:
        targets: [pgw-pfcp]
    destinations:
    - nats:
        enabled: true
  - source:
      memif:
        targets: [sgi]
    destinations:
    - nats:
        subject: "pcaps.{CLUSTER}.{apn}.{TARGET}"
```

If subject is not defined by the user, the default one is used:

```
com.cennso.memcap.v1alpha1.pcaps.cluster.{CLUSTER}.namespace.{NAMESPACE}.pod.{POD}.interface.{INTERFACE}.nwi.{NWI}.imsi.{IMSI}.filter.{FILTER}.target.{TARGET}
```

This can be extended at the end with an arbitrary `key:value` pair defined in the CGW/FPP/UPG deployment as an environmental variable or in **startup.conf**.

If, for example, the CGW/UPG pod contains the `MEMCAP_APN="test.cennso.com"` environmental variable, the `apn:test.cennso.com` is attached to the subject. Example of a generated subject:

```
com.cennso.memcap.v1alpha1.pcaps.cluster.test-cluster.namespace.pgw-ocs.pod.upg-prox01-5c99cf67b4-bldbq.interface.sxb.nwi.not_available.imsi.not_available.filter.not_available.target.pgw-pfcp.apn.test_cennso_com
```

If, for example, the user has defined a `pcaps.{CLUSTER}.{apn}.{TARGET}` subject, and it contains the `MEMCAP_APN="test.cennso.com"` pod environmental variable , the rendered subject is:

```
pcaps.test-cluster.test_cennso_com.sgi
```

> **INFO**: A subject name cannot contain characters such as a space, `.`, `*`, and `>`. Each forbidden character is replaced by `_`.

The subject includes  the`not_available` values if some metadata is unavailable.

Wildcards available for the NATS subjects:
- **\*** - to match a single token, for example `pcaps.*.pfcp` will match `pcaps.test1.pfcp` and `pcaps.test2.pfcp`
- **>** - to match multiple tokens, for example `pcaps.>` will match `pcaps.test1.pfcp` and `pcaps.test2.sgi`

### Rotation schedule

MEMCAP 0.6 enables the definition of a rotation schedule using cron expressions.

The new configuration adds the **schedule** field, where the following time rotation periods are available:

- `schedule: 10` - Performs rotation every declared number of seconds after the start of traffic capturing, <number> s
- `schedule: 10s` - Performs rotation every declared interval after the start of traffic capturing, <number><unit> (example: 10s, 10.5m, 10h10m)
- `schedule: "@every 1h30m"` - Performs PCAP file rotation every declared interval after the start of traffic capturing, @every <number><unit> (example: @every 1h30m)
- `schedule: @hourly` - Performs rotation every declared period (`@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`) at the full minute (xx:00), not aligned with the start of traffic capturing but with the clock time
- `schedule: "30 * * * "` - Performs rotation every hour on the half hour (yy:30), not aligned with the start of traffic capturing but with the clock time

All formats are available in the [Cronv3 Golang library documentation](https://pkg.go.dev/github.com/robfig/cron/v3).

Sample MEMCAP configuration:

```yaml
imagePullSecrets:
- name: cccc-pull-secret
memcapSink:
  enabled: true
  logLevel: info
  streams:
  - source:
      memif:
        targets: [test, pgw-pfcp]
    destinations:
    - file:
        path_prefix: "pfcp"
        rotate: true
        max_packets: 100000
        max_files: 10
        schedule: "@hourly" # rotation at the beginning of every hour
        #schedule: 15m  # rotation every 15 minutes after start of traffic capturing
        #max_duration: 1h  # rotation every 1 hour after start of traffic capturing
        compressed: true
```

The old **max_duration** parameter is broken in the MEMCAP 0.5 release, but in 0.6, it has the following meaning:
- `max_duration: 10` - Seconds of traffic capturing if the integer is passed
- `max_duration: 1h` - Available values: 10s, 10m, 10h, and so on

### Compression formats

MEMCAP 0.6 introduces new compression formats: **lz4** and **gzip**.

The old parameter **compressed** is still supported, meaning **zstd**.

The new **streams[0].destinations[].file.compress** parameter can contain:
- none - no compression
- zstd
- lz4
- gzip

The compression level can also be defined in **streams[0].destinations[].file.compressLevel**. The integer number can tune the compression algorithms as follows:
- for **gzip** - available values 1-9:
  - `1` - best speed
  - `9` - best compression
- for **zstd** - available values 1-20:
  - `1` - best speed
  - `20` - best compression
- for **lz4** - available values 1-9:
  - `1` - best speed
  - `9` - best compression

Sample configuration:

```yaml
imagePullSecrets:
- name: cccc-pull-secret
memcapConsumer:
  enabled: true
  logLevel: info
  nats:
    url: "nats://nats.default"
    clusterName: test-cluster
    streamName: pcaps-memcap-cdm-test
  streams:
  - source:
      memif:
        targets: [test, pgw-pfcp]
    destinations:
    - file:
        path_prefix: "pfcp"
        rotate: true
        max_packets: 100000
        max_files: 10
        compress: "lz4"
        compressLevel: 7
```

### Use only MEMCAP Sink

In a cluster where NATS is not enabled, you can configure MEMCAP Sink to store pcaps locally on the Data Plane node.

In this case, **memcapSink.streams[].destinations** should include only **file** objects. The MEMCAP Consumer can be disabled by setting **memcapConsumer.enabled** to `false`. Sample configuration:

```yaml
imagePullSecrets:
- name: cccc-pull-secret
memcapSink:
  enabled: true
  logLevel: info
  streams:
  - source:
      memif:
        targets: [test, pgw-pfcp]
    destinations:
    - file:
        path_prefix: "pfcp"
        rotate: true
        max_packets: 100000
        max_files: 10
        compress: "lz4"
        compressLevel: 7
memcapConsumer:
  enabled: false
```

## Usage

### Enable traffic capturing

To initiate traffic capturing on a specific interface, use this command:
```
vppctl set interface memcap ${INTERFACE_NAME} target ${TARGET_NAME} [filter {tcpdump filter}] [packet_max_bytes 9000] [rx] [tx]
```
- `filter {tcpdump filter}` - allows you to define libpcap-based filters that are the same as in the tcpdump utility. The filter format is described in the libpcap documentation `man pcap-filter`. Examples: `filter {arp or icmp}`, `filter {src net 192.0.2.0/24 and port 2020}`.
- `packet_max_bytes` is an optional parameter which allows you to limit the size of collected data to reduce memory usage of a traffic capture
- `rx` and `tx` allow you to specify the direction in which traffic should be collected. Leaving those flags out collects traffic in both directions.

Note that you can create multiple captures for the same interface when using different capture targets. This is useful if you want to simultaneously collect differently filtered traffic to separate files from a single interface.

Each active stream on the interface may slow down the entire interface performance. To reduce performance degradation, it's best to keep the number of streams attached to interfaces low. This can be done by combining filters using the libpcap `or` operator.

### Disable traffic capturing

To disable traffic capturing on a specific interface, use this command:
```
vppctl set interface memcap ${INTERFACE_NAME} target ${TARGET_NAME} disable
```

### Monitor traffic capture

To view the created interface captures, use the command:
```
vppctl show interface memcap
```
See the output example:
```
Interface "left" [1] streams: 1
- target "dp" max_bytes 100 memcap id 3 rx tx jit_fn 0x0
Interface "right" [2] streams: 1
- target "dp" max_bytes 100 memcap id 2 rx tx jit_fn 0x0
Interface "sx" [3] streams: 3
- target "sx" max_bytes 9000 memcap id 0 rx tx jit_fn 0x7ffff7ffb000
  filter: {arp or icmp}
- target "sx-ipv6" max_bytes 9000 memcap id 1 tx jit_fn 0x7ffff7fc8000
  filter: { ip6 }
- target "sx-ipv4" max_bytes 9000 memcap id 8 rx tx jit_fn 0x7ffff7fc7000
  filter: { ip }
```

To view all the created MEMCAP streams from all plugins, use the command:
```
vppctl show memcap streams
```
See the output example:
```
DBGvpp# show memcap streams
Streams: 7
 [0] "sx" class: [0]hw_iface_l2 target: "sx" state: stopped
 [1] "left" class: [0]hw_iface_l2 target: "dp" state: stopped
 [2] "right" class: [0]hw_iface_l2 target: "dp" state: stopped
 [3] "imsi 001010100000000" class: [1]upf_session_ip target: "ue-1" state: stopped
```

To view MEMCAP connection state, use the command:
```
vppctl show memcap status
```
See the output example:
```
DBGvpp# show memcap status
Name: "unnamed memcap v0.3.0"
Connection:
  Path: /var/run/memcap/sink.sock
  State: sink active
  FD: 7
  Remote Name: "sink test example"
  Memory region
    Size: 0x201000
    Address: 0x81a01000
    MemFD: 16
Registered classes:
  [0] hw_iface_l2 (packet metadata: 0, stream metadata: 4)
  [1] upf_session_ip (packet metadata: 0, stream metadata: 0)
```

## Capture information

You can use the additional metadata provided in a `.pcapng` file for advanced filters in tools like Wireshark:

| Name | Description |
|:---|:---|
| `frame.interface_name` | Interface name. |
| `frame.interface_description` | Additional information that includes a target name. |
| `frame.interface_queue` | Worker index where packet capture happened. |
| `frame.packet_flags_direction` | Direction of a packet relative to VPP. |
| `frame.time` | Time of packet capture. Multiple packets can have the same capture time when they share the same vector in VPP. |
| `frame.cap_len` | Capture length. It can be different from packet length when additional capture limiter parameters are provided. |
| `frame.drop_count` | Number of dropped packets for the packet interface. This field is optional. It exists when slow IO causes packet loss. |

## Simultaneous streaming through HTTP

Currently, MEMCAP Sink does not support simultaneous streaming from multiple nodes through a single connection. For simultaneous streaming on multiple nodes, you must repeat these steps for every node:

1. Set up port forwarding to one of MEMCAP Sink pods. The pod must be located on the node where you want to capture traffic.

   ```bash
   kubectl port-forward pod/memcap-memcap-sink-xyzwq 9999:9999
   ```

   This command maps port `9999` on your local machine, allowing direct access to the streaming service.

2. To start streaming the `.pcapng` file to Wireshark, create an HTTP request and redirect it as a stream to Wireshark. You can specify multiple target names in the URL, separated by commas, to select the traffic capture as required.

   ```bash
   curl --compressed localhost:9999/pcap/TARGET1,TARGET2,TARGET3 -N | wireshark -k -i - -o 'gui.window_title:memcap-stream' -o 'capture.no_interface_load:TRUE'
   ```

   This command performs the following actions:
   - `curl --compressed` - starts a cURL and requests a server to perform the request compression and decompression before writing data to a pipe.
   - `localhost:9999/pcap/TARGET1,TARGET2,TARGET3` - URL to the forwarded MEMCAP Sink API port with a comma-separated list of target names.
   - `-N` - disables pipe buffering to ensure real-time updates in Wireshark.
   - `| wireshark -k -i -` - sends (pipes) the output from curl directly into Wireshark, which starts analyzing the stream immediately.
   - `-o 'gui.window_title:memcap-stream'` - sets the Wireshark window title for easy identification.
   - `-o 'capture.no_interface_load:TRUE'` - prevents Wireshark from listing local interfaces, which speeds up the startup.

As a result, you should see live traffic in Wireshark.

## Performance impact

### Test environment configuration

The System Under Test (SUT) container contains three sequential instances of CGW (FPP instance mode). The capture streams are attached to the left interface of CGW-central.

![CGW2 capture benchmark scheme](https://docs.cennso.com/api/assets/components/fpp/2.9/assets/cgw2-memcap-benchmark.svg)

Hardware configuration:
* CPU: 1x Intel Xeon Gold 6314U Processor 32-Core @ 2.30GHz
* RAM: 512GB RAM
* Net: 4x E810-C 25Gbps

FPP switch resources:
* CPU: 18
* Memory: 4Gi
* Hugepages-2Mi: 9Gi

CGW instances resources:
* CPU: 6
* Memory: 16Gi
* Hugepages-2Mi: 1Gi

Test parameters:
* Benchmark: Throughput Binary Search
* Sessions: 256000
* Acceptable loss: 0.3%
* Traffic profile: PPS, packets from 20 to 24 bytes

### Results

It is not recommended to use more than 4 streams simultaneously:

| Number of streams | Upload, pps | Download, pps | Total, pps | Total Drop Rate | Performance loss from baseline |
|---|---|---|---|---|---|
| No streams | 2.94 Mpps | 2.95 Mpps | 5.89 Mpps | 0.28% | - |
| Interface stream without filter | 2.93 Mpps | 2.92 Mpps | 5.85 Mpps | 0.30% | -0.67% |
| 1 | 2.85 Mpps | 2.85 Mpps | 5.70 Mpps | 0.10% | -3.22% |
| 2 | 2.80 Mpps | 2.80 Mpps | 5.60 Mpps | 0.14% | -4.92% |
| 3 | 2.89 Mpps | 2.89 Mpps | 5.77 Mpps | 0.42% | -2.03% |
| 4 | 2.89 Mpps | 2.89 Mpps | 5.79 Mpps | 0.27% | -1.69% |
| 5 | 2.47 Mpps | 2.47 Mpps | 4.94 Mpps | 0.18% | -16.12% |
| 6 | 1.82 Mpps | 1.82 Mpps | 3.64 Mpps | 0.16% | -38.20% |
| 7 | 1.56 Mpps | 1.56 Mpps | 3.12 Mpps | 0.07% | -47.02% |
| 8 | 1.31 Mpps | 1.31 Mpps | 2.61 Mpps | 0.09% | -55.68% |
| 12 | 522.03 Kpps | 520.60 Kpps | 1.04 Mpps | 0.37% | -82.34% |
| 16 | 337.75 Kpps | 337.46 Kpps | 675.21 Kpps | 0.03% | -88.53% |
| 20 | 229.70 Kpps | 230.53 Kpps | 460.23 Kpps | 0.18% | -92.19% |
| 24 | 106.21 Kpps | 106.29 Kpps | 212.50 Kpps | 0.02% | -96.40% |
| 32 | 43.71 Kpps | 43.59 Kpps | 87.31 Kpps | 0.00% | -98.52% |
