summaryrefslogtreecommitdiffstats
path: root/src/vlib
diff options
context:
space:
mode:
authorDave Barach <dave@barachs.net>2018-11-27 16:52:59 -0500
committerFlorin Coras <florin.coras@gmail.com>2018-11-30 20:18:54 +0000
commit7fff3d205463d5e0a95d6bdd337100988ef323a3 (patch)
tree7743d004b00a2e674e95c4d1593ae94c09b8a8b5 /src/vlib
parent8861c1a1f229b4727fea48bfe5990808bb30f871 (diff)
Metadata / opaque formatting belongs in vpp
VPP graph dispatch trace record description: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Major Version | Minor Version | NStrings | ProtoHint | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Buffer index (big endian) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + VPP graph node name ... ... | NULL octet | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Buffer Metadata ... ... | NULL octet | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Buffer Opaque ... ... | NULL octet | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Buffer Opaque 2 ... ... | NULL octet | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | VPP ASCII packet trace (if NStrings > 4) | NULL octet | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Packet data (up to 16K) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Graph dispatch records comprise a version stamp, an indication of how many NULL-terminated strings will follow the record header, and a protocol hint. The buffer index allows downstream consumers of these data to easily filter/track single packets as they traverse the forwarding graph. FWIW, the 32-bit buffer index is stored in big endian format. As of this writing, major version = 1, minor version = 0. Nstrings will be either 4 or 5. Here is the current set of protocol hints: typedef enum { VLIB_NODE_PROTO_HINT_NONE = 0, VLIB_NODE_PROTO_HINT_ETHERNET, VLIB_NODE_PROTO_HINT_IP4, VLIB_NODE_PROTO_HINT_IP6, VLIB_NODE_PROTO_HINT_TCP, VLIB_NODE_PROTO_HINT_UDP, VLIB_NODE_N_PROTO_HINTS, } vlib_node_proto_hint_t; Example: VLIB_NODE_PROTO_HINT_IP6 means that the first octet of packet data SHOULD be 0x60, and should begin an ipv6 packet header. Change-Id: Idf310bad80cc0e4207394c80f18db5f77c378741 Signed-off-by: Dave Barach <dave@barachs.net>
Diffstat (limited to 'src/vlib')
-rw-r--r--src/vlib/main.c147
-rw-r--r--src/vlib/main.h1
-rw-r--r--src/vlib/node.c1
-rw-r--r--src/vlib/node.h17
4 files changed, 109 insertions, 57 deletions
diff --git a/src/vlib/main.c b/src/vlib/main.c
index d1babdb9da6..949a77d3d71 100644
--- a/src/vlib/main.c
+++ b/src/vlib/main.c
@@ -945,25 +945,69 @@ add_trajectory_trace (vlib_buffer_t * b, u32 node_index)
#endif
}
+u8 *format_vnet_buffer_flags (u8 * s, va_list * args) __attribute__ ((weak));
+u8 *
+format_vnet_buffer_flags (u8 * s, va_list * args)
+{
+ s = format (s, "BUG STUB %s", __FUNCTION__);
+ return s;
+}
+
+u8 *format_vnet_buffer_opaque (u8 * s, va_list * args) __attribute__ ((weak));
+u8 *
+format_vnet_buffer_opaque (u8 * s, va_list * args)
+{
+ s = format (s, "BUG STUB %s", __FUNCTION__);
+ return s;
+}
+
+u8 *format_vnet_buffer_opaque2 (u8 * s, va_list * args)
+ __attribute__ ((weak));
+u8 *
+format_vnet_buffer_opaque2 (u8 * s, va_list * args)
+{
+ s = format (s, "BUG STUB %s", __FUNCTION__);
+ return s;
+}
+
+static u8 *
+format_buffer_metadata (u8 * s, va_list * args)
+{
+ vlib_buffer_t *b = va_arg (*args, vlib_buffer_t *);
+
+ s = format (s, "flags: %U\n", format_vnet_buffer_flags, b);
+ s = format (s, "current_data: %d, current_length: %d\n",
+ (i32) (b->current_data), (i32) (b->current_length));
+ s = format (s, "current_config_index: %d, flow_id: %x, next_buffer: %x\n",
+ b->current_config_index, b->flow_id, b->next_buffer);
+ s = format (s, "error: %d, n_add_refs: %d, buffer_pool_index: %d\n",
+ (u32) (b->error), (u32) (b->n_add_refs),
+ (u32) (b->buffer_pool_index));
+ s = format (s,
+ "trace_index: %d, recycle_count: %d, len_not_first_buf: %d\n",
+ b->trace_index, b->recycle_count,
+ b->total_length_not_including_first_buffer);
+ s = format (s, "free_list_index: %d\n", (u32) (b->free_list_index));
+ return s;
+}
+
+#define A(x) vec_add1(vm->pcap_buffer, (x))
+
static void
dispatch_pcap_trace (vlib_main_t * vm,
vlib_node_runtime_t * node, vlib_frame_t * frame)
{
int i;
vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **bufp, *b;
- u8 name_tlv[64];
pcap_main_t *pm = &vm->dispatch_pcap_main;
vlib_trace_main_t *tm = &vm->trace_main;
u32 capture_size;
vlib_node_t *n;
- u8 *packet_trace = 0;
i32 n_left;
f64 time_now = vlib_time_now (vm);
u32 *from;
- u32 name_length;
- u16 trace_length;
- u8 version[2];
u8 *d;
+ u8 string_count;
/* Input nodes don't have frames yet */
if (frame == 0 || frame->n_vectors == 0)
@@ -973,15 +1017,7 @@ dispatch_pcap_trace (vlib_main_t * vm,
vlib_get_buffers (vm, from, bufs, frame->n_vectors);
bufp = bufs;
- /* Create a node name TLV, since WS can't possibly guess */
n = vlib_get_node (vm, node->node_index);
- name_length = vec_len (n->name);
- name_length = name_length < ARRAY_LEN (name_tlv) - 2 ?
- name_length : ARRAY_LEN (name_tlv) - 2;
-
- name_tlv[0] = (u8) name_length;
- clib_memcpy_fast (name_tlv + 1, n->name, name_length);
- name_tlv[name_length + 1] = 0;
for (i = 0; i < frame->n_vectors; i++)
{
@@ -989,10 +1025,34 @@ dispatch_pcap_trace (vlib_main_t * vm,
{
b = bufp[i];
- version[0] = VLIB_PCAP_MAJOR_VERSION;
- version[1] = VLIB_PCAP_MINOR_VERSION;
-
- vec_reset_length (packet_trace);
+ vec_reset_length (vm->pcap_buffer);
+ string_count = 0;
+
+ /* Version, flags */
+ A ((u8) VLIB_PCAP_MAJOR_VERSION);
+ A ((u8) VLIB_PCAP_MINOR_VERSION);
+ A (0 /* string_count */ );
+ A (n->protocol_hint);
+
+ /* Buffer index (big endian) */
+ A ((from[i] >> 24) & 0xff);
+ A ((from[i] >> 16) & 0xff);
+ A ((from[i] >> 8) & 0xff);
+ A ((from[i] >> 0) & 0xff);
+
+ /* Node name, NULL-terminated ASCII */
+ vm->pcap_buffer = format (vm->pcap_buffer, "%v%c", n->name, 0);
+ string_count++;
+
+ vm->pcap_buffer = format (vm->pcap_buffer, "%U%c",
+ format_buffer_metadata, b, 0);
+ string_count++;
+ vm->pcap_buffer = format (vm->pcap_buffer, "%U%c",
+ format_vnet_buffer_opaque, b, 0);
+ string_count++;
+ vm->pcap_buffer = format (vm->pcap_buffer, "%U%c",
+ format_vnet_buffer_opaque2, b, 0);
+ string_count++;
/* Is this packet traced? */
if (PREDICT_FALSE (b->flags & VLIB_BUFFER_IS_TRACED))
@@ -1000,55 +1060,29 @@ dispatch_pcap_trace (vlib_main_t * vm,
vlib_trace_header_t **h
= pool_elt_at_index (tm->trace_buffer_pool, b->trace_index);
- packet_trace = format (packet_trace, "%U%c",
- format_vlib_trace, vm, h[0], 0);
+ vm->pcap_buffer = format (vm->pcap_buffer, "%U%c",
+ format_vlib_trace, vm, h[0], 0);
+ string_count++;
}
- /* Figure out how many bytes we're capturing */
- /* *INDENT-OFF* */
- capture_size = (sizeof (vlib_buffer_t) - VLIB_BUFFER_PRE_DATA_SIZE)
- + sizeof (version)
- + vlib_buffer_length_in_chain (vm, b)
- + sizeof (u32) + (name_length + 2) /* +2: count plus NULL byte */
- + (vec_len (packet_trace) + 2); /* +2: trace count */
- /* *INDENT-ON* */
+ /* Save the string count */
+ vm->pcap_buffer[2] = string_count;
+
+ /* Figure out how many bytes in the pcap trace */
+ capture_size = vec_len (vm->pcap_buffer) +
+ +vlib_buffer_length_in_chain (vm, b);
clib_spinlock_lock_if_init (&pm->lock);
n_left = clib_min (capture_size, 16384);
d = pcap_add_packet (pm, time_now, n_left, capture_size);
- /* Copy the (major, minor) version numbers */
- clib_memcpy_fast (d, version, sizeof (version));
- d += sizeof (version);
-
- /* Copy the buffer index */
- clib_memcpy_fast (d, &from[i], sizeof (u32));
- d += 4;
-
- /* Copy the name TLV */
- clib_memcpy_fast (d, name_tlv, name_length + 2);
- d += name_length + 2;
-
- /* Copy the buffer metadata, but not the rewrite space */
- clib_memcpy_fast (d, b, sizeof (*b) - VLIB_BUFFER_PRE_DATA_SIZE);
- d += sizeof (*b) - VLIB_BUFFER_PRE_DATA_SIZE;
-
- trace_length = vec_len (packet_trace);
- /* Copy the trace data length (may be zero) */
- clib_memcpy_fast (d, &trace_length, sizeof (trace_length));
- d += 2;
-
- /* Copy packet trace data (if any) */
- if (vec_len (packet_trace))
- clib_memcpy_fast (d, packet_trace, vec_len (packet_trace));
-
- d += vec_len (packet_trace);
+ /* Copy the header */
+ clib_memcpy_fast (d, vm->pcap_buffer, vec_len (vm->pcap_buffer));
+ d += vec_len (vm->pcap_buffer);
n_left = clib_min
(vlib_buffer_length_in_chain (vm, b),
- 16384 -
- ((sizeof (*b) - VLIB_BUFFER_PRE_DATA_SIZE) +
- (trace_length + 2)));
+ (16384 - vec_len (vm->pcap_buffer)));
/* Copy the packet data */
while (1)
{
@@ -1064,7 +1098,6 @@ dispatch_pcap_trace (vlib_main_t * vm,
clib_spinlock_unlock_if_init (&pm->lock);
}
}
- vec_free (packet_trace);
}
static_always_inline u64
diff --git a/src/vlib/main.h b/src/vlib/main.h
index 9fa294e96f5..474756bebd6 100644
--- a/src/vlib/main.h
+++ b/src/vlib/main.h
@@ -134,6 +134,7 @@ typedef struct vlib_main_t
/* Pcap dispatch trace main */
pcap_main_t dispatch_pcap_main;
uword dispatch_pcap_enable;
+ u8 *pcap_buffer;
/* Error handling. */
vlib_error_main_t error_main;
diff --git a/src/vlib/node.c b/src/vlib/node.c
index 88185ce921f..69f505143b2 100644
--- a/src/vlib/node.c
+++ b/src/vlib/node.c
@@ -350,6 +350,7 @@ register_node (vlib_main_t * vm, vlib_node_registration_t * r)
clib_memset (n, 0, sizeof (n[0]));
n->index = vec_len (nm->nodes);
n->node_fn_registrations = r->node_fn_registrations;
+ n->protocol_hint = r->protocol_hint;
vec_add1 (nm->nodes, n);
diff --git a/src/vlib/node.h b/src/vlib/node.h
index fb2a83bc400..f41eb60aa2c 100644
--- a/src/vlib/node.h
+++ b/src/vlib/node.h
@@ -57,6 +57,17 @@ typedef uword (vlib_node_function_t) (struct vlib_main_t * vm,
typedef enum
{
+ VLIB_NODE_PROTO_HINT_NONE = 0,
+ VLIB_NODE_PROTO_HINT_ETHERNET,
+ VLIB_NODE_PROTO_HINT_IP4,
+ VLIB_NODE_PROTO_HINT_IP6,
+ VLIB_NODE_PROTO_HINT_TCP,
+ VLIB_NODE_PROTO_HINT_UDP,
+ VLIB_NODE_N_PROTO_HINTS,
+} vlib_node_proto_hint_t;
+
+typedef enum
+{
/* An internal node on the call graph (could be output). */
VLIB_NODE_TYPE_INTERNAL,
@@ -134,6 +145,9 @@ typedef struct _vlib_node_registration
/* Node flags. */
u16 flags;
+ /* protocol at b->data[b->current_data] upon entry to the dispatch fn */
+ u8 protocol_hint;
+
/* Size of scalar and vector arguments in bytes. */
u16 scalar_size, vector_size;
@@ -320,6 +334,9 @@ typedef struct vlib_node_t
/* Number of bytes of run time data. */
u8 runtime_data_bytes;
+ /* protocol at b->data[b->current_data] upon entry to the dispatch fn */
+ u8 protocol_hint;
+
/* Number of error codes used by this node. */
u16 n_errors;
ghlight .cs { color: #75715e } /* Comment.Special */ .highlight .gd { color: #f92672 } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gi { color: #a6e22e } /* Generic.Inserted */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #75715e } /* Generic.Subheading */ .highlight .kc { color: #66d9ef } /* Keyword.Constant */ .highlight .kd { color: #66d9ef } /* Keyword.Declaration */ .highlight .kn { color: #f92672 } /* Keyword.Namespace */ .highlight .kp { color: #66d9ef } /* Keyword.Pseudo */ .highlight .kr { color: #66d9ef } /* Keyword.Reserved */ .highlight .kt { color: #66d9ef } /* Keyword.Type */ .highlight .ld { color: #e6db74 } /* Literal.Date */ .highlight .m { color: #ae81ff } /* Literal.Number */ .highlight .s { color: #e6db74 } /* Literal.String */ .highlight .na { color: #a6e22e } /* Name.Attribute */ .highlight .nb { color: #f8f8f2 } /* Name.Builtin */ .highlight .nc { color: #a6e22e } /* Name.Class */ .highlight .no { color: #66d9ef } /* Name.Constant */ .highlight .nd { color: #a6e22e } /* Name.Decorator */ .highlight .ni { color: #f8f8f2 } /* Name.Entity */ .highlight .ne { color: #a6e22e } /* Name.Exception */ .highlight .nf { color: #a6e22e } /* Name.Function */ .highlight .nl { color: #f8f8f2 } /* Name.Label */ .highlight .nn { color: #f8f8f2 } /* Name.Namespace */ .highlight .nx { color: #a6e22e } /* Name.Other */ .highlight .py { color: #f8f8f2 } /* Name.Property */ .highlight .nt { color: #f92672 } /* Name.Tag */ .highlight .nv { color: #f8f8f2 } /* Name.Variable */ .highlight .ow { color: #f92672 } /* Operator.Word */ .highlight .w { color: #f8f8f2 } /* Text.Whitespace */ .highlight .mb { color: #ae81ff } /* Literal.Number.Bin */ .highlight .mf { color: #ae81ff } /* Literal.Number.Float */ .highlight .mh { color: #ae81ff } /* Literal.Number.Hex */ .highlight .mi { color: #ae81ff } /* Literal.Number.Integer */ .highlight .mo { color: #ae81ff } /* Literal.Number.Oct */ .highlight .sa { color: #e6db74 } /* Literal.String.Affix */ .highlight .sb { color: #e6db74 } /* Literal.String.Backtick */ .highlight .sc { color: #e6db74 } /* Literal.String.Char */ .highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */ .highlight .sd { color: #e6db74 } /* Literal.String.Doc */ .highlight .s2 { color: #e6db74 } /* Literal.String.Double */ .highlight .se { color: #ae81ff } /* Literal.String.Escape */ .highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */ .highlight .si { color: #e6db74 } /* Literal.String.Interpol */ .highlight .sx { color: #e6db74 } /* Literal.String.Other */ .highlight .sr { color: #e6db74 } /* Literal.String.Regex */ .highlight .s1 { color: #e6db74 } /* Literal.String.Single */ .highlight .ss { color: #e6db74 } /* Literal.String.Symbol */ .highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #a6e22e } /* Name.Function.Magic */ .highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */ .highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */ .highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */ .highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */ .highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */ } @media (prefers-color-scheme: light) { .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
# Copyright (c) 2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Constants used in CSIT.

"Constant" means a value that keeps its value since initialization. The value
does not need to be hard coded here, but can be read from environment variables.
"""


import os


def get_str_from_env(env_var_names, default_value):
    """Attempt to read string from environment variable, return that or default.

    If environment variable exists, but is empty (and default is not),
    empty string is returned.

    Several environment variable names are examined, as CSIT currently supports
    a mix of naming conventions.
    Here "several" means there are hard coded prefixes to try,
    and env_var_names itself can be single name, or a list or a tuple of names.

    :param env_var_names: Base names of environment variable to attempt to read.
    :param default_value: Value to return if the env var does not exist.
    :type env_var_names: str, or list of str, or tuple of str
    :type default_value: str
    :returns: The value read, or default value.
    :rtype: str
    """
    prefixes = (u"FDIO_CSIT_", u"CSIT_", u"")
    if not isinstance(env_var_names, (list, tuple)):
        env_var_names = [env_var_names]
    for name in env_var_names:
        for prefix in prefixes:
            value = os.environ.get(prefix + name, None)
            if value is not None:
                return value
    return default_value


def get_int_from_env(env_var_names, default_value):
    """Attempt to read int from environment variable, return that or default.

    String value is read, default is returned also if conversion fails.

    :param env_var_names: Base names of environment variable to attempt to read.
    :param default_value: Value to return if read or conversion fails.
    :type env_var_names: str, or list of str, or tuple of str
    :type default_value: int
    :returns: The value read, or default value.
    :rtype: int
    """
    env_str = get_str_from_env(env_var_names, u"")
    try:
        return int(env_str)
    except ValueError:
        return default_value


def get_float_from_env(env_var_names, default_value):
    """Attempt to read float from environment variable, return that or default.

    String value is read, default is returned also if conversion fails.

    :param env_var_names: Base names of environment variable to attempt to read.
    :param default_value: Value to return if read or conversion fails.
    :type env_var_names: str, or list of str, or tuple of str
    :type default_value: float
    :returns: The value read, or default value.
    :rtype: float
    """
    env_str = get_str_from_env(env_var_names, u"")
    try:
        return float(env_str)
    except ValueError:
        return default_value


def get_pessimistic_bool_from_env(env_var_names):
    """Attempt to read bool from environment variable, assume False by default.

    Conversion is lenient and pessimistic, only few strings are considered true.

    :param env_var_names: Base names of environment variable to attempt to read.
    :type env_var_names: str, or list of str, or tuple of str
    :returns: The value read, or False.
    :rtype: bool
    """
    env_str = get_str_from_env(env_var_names, u"").lower()
    return bool(env_str in (u"true", u"yes", u"y", u"1"))


def get_optimistic_bool_from_env(env_var_names):
    """Attempt to read bool from environment variable, assume True by default.

    Conversion is lenient and optimistic, only few strings are considered false.

    :param env_var_names: Base names of environment variable to attempt to read.
    :type env_var_names: str, or list of str, or tuple of str
    :returns: The value read, or True.
    :rtype: bool
    """
    env_str = get_str_from_env(env_var_names, u"").lower()
    return bool(env_str not in (u"false", u"no", u"n", u"0"))


class Constants:
    """Constants used in CSIT."""

    # Version for CSIT data model. See docs/model/.
    MODEL_VERSION = u"1.0.0"

    # Global off-switch in case JSON export is large or slow.
    EXPORT_JSON = get_optimistic_bool_from_env(u"EXPORT_JSON")

    # OpenVPP testing directory location at topology nodes
    REMOTE_FW_DIR = u"/tmp/openvpp-testing"

    # shell scripts location
    RESOURCES_LIB_SH = u"resources/libraries/bash"

    # python scripts location
    RESOURCES_LIB_PY = u"resources/libraries/python"

    # shell scripts location
    RESOURCES_TOOLS = u"resources/tools"

    # Python API provider location
    RESOURCES_PAPI_PROVIDER = u"resources/tools/papi/vpp_papi_provider.py"

    # Templates location
    RESOURCES_TPL = u"resources/templates"

    # vat templates location
    RESOURCES_TPL_VAT = u"resources/templates/vat"

    # Kubernetes templates location
    RESOURCES_TPL_K8S = u"resources/templates/kubernetes"

    # Container templates location
    RESOURCES_TPL_CONTAINER = u"resources/templates/container"

    # VPP Communications Library templates location
    RESOURCES_TPL_VCL = u"resources/templates/vcl"

    # VPP Communications Library templates location
    RESOURCES_TPL_TELEMETRY = u"resources/templates/telemetry"

    # VPP Communications Library LD_PRELOAD library
    VCL_LDPRELOAD_LIBRARY = u"/usr/lib/x86_64-linux-gnu/libvcl_ldpreload.so"

    # OpenVPP VAT binary name
    VAT_BIN_NAME = u"vpp_api_test"

    # VPP service unit name
    VPP_UNIT = u"vpp"

    # Number of system CPU cores.
    CPU_CNT_SYSTEM = 1

    # Number of vswitch main thread CPU cores.
    CPU_CNT_MAIN = 1

    # QEMU binary path
    QEMU_BIN_PATH = u"/usr/bin"

    # QEMU VM kernel image path
    QEMU_VM_KERNEL = u"/opt/boot/vmlinuz"

    # QEMU VM kernel initrd path
    QEMU_VM_KERNEL_INITRD = u"/opt/boot/initrd.img"

    # QEMU VM nested image path
    QEMU_VM_IMAGE = u"/var/lib/vm/image.iso"

    # QEMU VM DPDK path
    QEMU_VM_DPDK = u"/opt/dpdk-21.11"

    # Docker container SUT image
    DOCKER_SUT_IMAGE_UBUNTU = u"csit_sut-ubuntu2004:local"

    # Docker container arm SUT image
    DOCKER_SUT_IMAGE_UBUNTU_ARM = u"csit_sut-ubuntu2004:local"

    # TRex install directory
    TREX_INSTALL_DIR = u"/opt/trex-core-2.88"

    # TRex pcap files directory
    TREX_PCAP_DIR = f"{TREX_INSTALL_DIR}/scripts/avl"

    # TRex limit memory.
    TREX_LIMIT_MEMORY = get_int_from_env(u"TREX_LIMIT_MEMORY", 8192)

    # TRex number of cores
    TREX_CORE_COUNT = get_int_from_env(u"TREX_CORE_COUNT", 8)

    # TRex set number of RX/TX descriptors
    # Set to 0 to use default values
    TREX_TX_DESCRIPTORS_COUNT = get_int_from_env(
        u"TREX_TX_DESCRIPTORS_COUNT", 0
    )
    TREX_RX_DESCRIPTORS_COUNT = get_int_from_env(
        u"TREX_RX_DESCRIPTORS_COUNT", 0
    )

    # Trex force start regardless ports state
    TREX_SEND_FORCE = get_pessimistic_bool_from_env(u"TREX_SEND_FORCE")

    # TRex extra commandline arguments
    TREX_EXTRA_CMDLINE = get_str_from_env(
        u"TREX_EXTRA_CMDLINE", u"--mbuf-factor 32")

    # Graph node variant value
    GRAPH_NODE_VARIANT = get_str_from_env(u"GRAPH_NODE_VARIANT", u"")

    # Default memory page size in case multiple configured in system
    DEFAULT_HUGEPAGE_SIZE = get_str_from_env(u"DEFAULT_HUGEPAGE_SIZE", u"2M")

    # Sysctl kernel.core_pattern
    KERNEL_CORE_PATTERN = u"/tmp/%p-%u-%g-%s-%t-%h-%e.core"

    # Core dump directory
    CORE_DUMP_DIR = u"/tmp"

    # Perf stat events (comma separated).
    PERF_STAT_EVENTS = get_str_from_env(
        u"PERF_STAT_EVENTS",
        u"cpu-clock,context-switches,cpu-migrations,page-faults,"
        u"cycles,instructions,branches,branch-misses,L1-icache-load-misses")

    # Equivalent to ~0 used in vpp code
    BITWISE_NON_ZERO = 0xffffffff

    # Default path to VPP API socket.
    SOCKSVR_PATH = u"/run/vpp/api.sock"

    # Number of trials to execute in MRR test.
    PERF_TRIAL_MULTIPLICITY = get_int_from_env(u"PERF_TRIAL_MULTIPLICITY", 10)

    # Duration [s] of one trial in MRR test.
    PERF_TRIAL_DURATION = get_float_from_env(u"PERF_TRIAL_DURATION", 1.0)

    # Whether to use latency streams in main search trials.
    PERF_USE_LATENCY = get_pessimistic_bool_from_env(u"PERF_USE_LATENCY")

    # Duration of one latency-specific trial in NDRPDR test.
    PERF_TRIAL_LATENCY_DURATION = get_float_from_env(
        u"PERF_TRIAL_LATENCY_DURATION", 5.0)

    # For some testbeds TG takes longer than usual to start sending traffic.
    # This constant [s] allows longer wait, without affecting
    # the approximate duration. For example, use 0.098 for AWS.
    PERF_TRIAL_STL_DELAY = get_float_from_env(u"PERF_TRIAL_STL_DELAY", 0.0)

    # ASTF usually needs a different value for the delay.
    PERF_TRIAL_ASTF_DELAY = get_float_from_env(
        u"PERF_TRIAL_ASTF_DELAY", 0.112
    )

    # Extended debug (incl. vpp packet trace, linux perf stat, ...).
    # Full list is available as suite variable (__init__.robot) or is
    # override by test.
    EXTENDED_DEBUG = get_pessimistic_bool_from_env(u"EXTENDED_DEBUG")

    # UUID string of DUT1 /tmp volume created outside of the
    # DUT1 docker in case of vpp-device test. ${EMPTY} value means that
    #  /tmp directory is inside the DUT1 docker.
    DUT1_UUID = get_str_from_env(u"DUT1_UUID", u"")

    # Default path to VPP API Stats socket.
    SOCKSTAT_PATH = u"/run/vpp/stats.sock"

    # Global "kill switch" for CRC checking during runtime.
    FAIL_ON_CRC_MISMATCH = get_pessimistic_bool_from_env(
        u"FAIL_ON_CRC_MISMATCH"
    )

    # Default IP4 prefix length (if not defined in topology file)
    DEFAULT_IP4_PREFIX_LENGTH = u"24"

    # Maximum number of interfaces in a data path
    DATAPATH_INTERFACES_MAX = 100

    # Mapping from NIC name to its bps limit.
    NIC_NAME_TO_BPS_LIMIT = {
        u"Intel-X520-DA2": 10000000000,
        u"Intel-X553": 10000000000,
        u"Intel-X710": 10000000000,
        u"Intel-XL710": 24500000000,
        u"Intel-XXV710": 24500000000,
        u"Intel-E810CQ": 100000000000,
        u"Mellanox-CX556A": 100000000000,
        u"Amazon-Nitro-50G": 10000000000,
        u"virtual": 100000000,
    }

    # Mapping from NIC name to its pps limit.
    NIC_NAME_TO_PPS_LIMIT = {
        u"Intel-X520-DA2": 14880952,
        u"Intel-X553": 14880952,
        u"Intel-X710": 14880952,
        u"Intel-XL710": 18750000,
        u"Intel-XXV710": 18750000,
        u"Intel-E810CQ": 58500000,
        # 2n-clx testbeds show duration stretching on high rates,
        # depending on encapsulation TRex has to generate.
        # 40 Mpps is still too much for dot1q (~8% stretching).
        # 36 Mpps is around the maximal VPP throughput (l2patch 4c8t).
        # Vxlan traffic will still show stretching at 36 Mpps (>12%),
        # but we do not care about those tests that much.
        u"Mellanox-CX556A": 36000000, # 148809523,
        u"Amazon-Nitro-50G": 1200000,
        u"virtual": 14880952,
    }

    # Suite file names use codes for NICs.
    NIC_NAME_TO_CODE = {
        u"Intel-X520-DA2": u"10ge2p1x520",
        u"Intel-X553": u"10ge2p1x553",
        u"Intel-X710": u"10ge2p1x710",
        u"Intel-XL710": u"40ge2p1xl710",
        u"Intel-XXV710": u"25ge2p1xxv710",
        u"Intel-E810CQ": u"100ge2p1e810cq",
        u"Amazon-Nitro-50G": u"50ge1p1ena",
        u"Mellanox-CX556A": u"100ge2p1cx556a",
    }

    # Shortened lowercase NIC model name, useful for presentation.
    NIC_CODE_TO_SHORT_NAME = {
        u"10ge2p1x520": u"x520",
        u"10ge2p1x553": u"x553",
        u"10ge2p1x710": u"x710",
        u"40ge2p1xl710": u"xl710",
        u"25ge2p1xxv710": u"xxv710",
        u"100ge2p1e810cq": u"e810cq",
        u"50ge1p1ena": u"ena",
        u"100ge2p1cx556a": u"cx556a",
    }

    # Not each driver is supported by each NIC.
    NIC_NAME_TO_DRIVER = {
        u"Intel-X520-DA2": [u"vfio-pci", u"af_xdp"],
        u"Intel-X553": [u"vfio-pci", u"af_xdp"],
        u"Intel-X710": [u"vfio-pci", u"avf", u"af_xdp"],
        u"Intel-XL710": [u"vfio-pci", u"avf", u"af_xdp"],
        u"Intel-XXV710": [u"vfio-pci", u"avf", u"af_xdp"],
        u"Intel-E810CQ": [u"vfio-pci", u"avf", u"af_xdp"],
        u"Amazon-Nitro-50G": [u"vfio-pci"],
        u"Mellanox-CX556A": [u"rdma-core", u"af_xdp"],
    }

    # Each driver needs different prugin to work.
    NIC_DRIVER_TO_PLUGINS = {
        u"vfio-pci": u"dpdk_plugin.so",
        u"avf": u"avf_plugin.so",
        u"rdma-core": u"rdma_plugin.so",
        u"af_xdp": u"af_xdp_plugin.so",
    }

    # Tags to differentiate tests for different NIC driver.
    NIC_DRIVER_TO_TAG = {
        u"vfio-pci": u"DRV_VFIO_PCI",
        u"avf": u"DRV_AVF",
        u"rdma-core": u"DRV_RDMA_CORE",
        u"af_xdp": u"DRV_AF_XDP",
    }

    # Suite names have to be different, add prefix.
    NIC_DRIVER_TO_SUITE_PREFIX = {
        u"vfio-pci": u"",
        u"avf": u"avf-",
        u"rdma-core": u"rdma-",
        u"af_xdp": u"af-xdp-",
    }

    # Number of virtual functions of physical nic.
    NIC_DRIVER_TO_VFS = {
        u"vfio-pci": u"nic_vfs}= | 0",
        u"avf": u"nic_vfs}= | 1",
        u"rdma-core": u"nic_vfs}= | 0",
        u"af_xdp": u"nic_vfs}= | 0",
    }

    # Not each driver is supported by each NIC.
    DPDK_NIC_NAME_TO_DRIVER = {
        u"Intel-X520-DA2": [u"vfio-pci"],
        u"Intel-X553": [u"vfio-pci"],
        u"Intel-X710": [u"vfio-pci"],
        u"Intel-XL710": [u"vfio-pci"],
        u"Intel-XXV710": [u"vfio-pci"],
        u"Intel-E810CQ": [u"vfio-pci"],
        u"Amazon-Nitro-50G": [u"vfio-pci"],
        u"Mellanox-CX556A": [u"mlx5_core"],
    }

    # Tags to differentiate tests for different NIC driver.
    DPDK_NIC_DRIVER_TO_TAG = {
        u"vfio-pci": u"DRV_VFIO_PCI",
        u"mlx5_core": u"DRV_MLX5_CORE",
    }

    # Suite names have to be different, add prefix.
    DPDK_NIC_DRIVER_TO_SUITE_PREFIX = {
        u"vfio-pci": u"",
        u"mlx5_core": u"mlx5-",
    }

    # Some identifiers constructed from suite names
    # have to be independent of NIC driver used.
    # In order to remove or reject the NIC driver part,
    # it is useful to have a list of such prefixes precomputed.
    FORBIDDEN_SUITE_PREFIX_LIST = [
        prefix for prefix in NIC_DRIVER_TO_SUITE_PREFIX.values() if prefix
    ]
    FORBIDDEN_SUITE_PREFIX_LIST += [
        prefix for prefix in DPDK_NIC_DRIVER_TO_SUITE_PREFIX.values() if prefix
    ]

    # TODO CSIT-1481: Crypto HW should be read from topology file instead.
    NIC_NAME_TO_CRYPTO_HW = {
        u"Intel-X553": u"HW_C3xxx",
        u"Intel-X710": u"HW_DH895xcc",
        u"Intel-XL710": u"HW_DH895xcc",
    }

    DEVICE_TYPE_TO_KEYWORD = {
        u"scapy": None
    }

    PERF_TYPE_TO_KEYWORD = {
        u"mrr": u"Traffic should pass with maximum rate",
        u"ndrpdr": u"Find NDR and PDR intervals using optimized search",
        u"soak": u"Find critical load using PLRsearch",
    }

    PERF_TYPE_TO_SUITE_DOC_VER = {
        u"mrr": u'''fication:** In MaxReceivedRate tests TG sends traffic at \\
| ... | line rate and reports total received packets over trial period. \\''',
        u"ndrpdr": u'''rification:** TG finds and reports throughput NDR (Non \\
| ... | Drop Rate) with zero packet loss tolerance and throughput PDR \\
| ... | (Partial Drop Rate) with non-zero packet loss tolerance (LT) \\
| ... | expressed in percentage of packets transmitted. NDR and PDR are \\
| ... | discovered for different Ethernet L2 frame sizes using MLRsearch \\
| ... | library.''',
        u"soak": u'''rification:** TG sends traffic at dynamically computed \\
| ... | rate as PLRsearch algorithm gathers data and improves its estimate \\
| ... | of a rate at which a prescribed small fraction of packets \\
| ... | would be lost. After set time, the serarch stops \\
| ... | and the algorithm reports its current estimate. \\''',
    }

    PERF_TYPE_TO_TEMPLATE_DOC_VER = {
        u"mrr": u'''Measure MaxReceivedRate for ${frame_size}B frames \\
| | ... | using burst trials throughput test. \\''',
        u"ndrpdr": u"Measure NDR and PDR values using MLRsearch algorithm.",
        u"soak": u"Estimate critical rate using PLRsearch algorithm. \\",
    }