aboutsummaryrefslogtreecommitdiffstats
path: root/docs/gettingstarted/developers/fib20/scale.rst
diff options
context:
space:
mode:
Diffstat (limited to 'docs/gettingstarted/developers/fib20/scale.rst')
-rw-r--r--docs/gettingstarted/developers/fib20/scale.rst68
1 files changed, 16 insertions, 52 deletions
diff --git a/docs/gettingstarted/developers/fib20/scale.rst b/docs/gettingstarted/developers/fib20/scale.rst
index 8cee1f1835c..4100f9aa7cf 100644
--- a/docs/gettingstarted/developers/fib20/scale.rst
+++ b/docs/gettingstarted/developers/fib20/scale.rst
@@ -4,20 +4,17 @@ Scale
-----
The only limiting factor on FIB scale is the amount of memory
-allocated to each heap the FIB uses, and there are 4:
+allocated to each heap the FIB uses, and there are 2:
-* The IP4 heap
-* The IP6 heap
* The main heap
* The stats heap
-IP4 Heap
---------
+Main Heap
+^^^^^^^^^
-The IPv4 heap is used to allocate the memory needed for the
-data-structures within which the IPv4 prefixes are stored. Each
-table, created by the user, i.e. with;
+The main heap is used to allocate all memory needed for the FIB
+data-structures. Each table, created by the user, i.e. with;
.. code-block:: console
@@ -36,18 +33,12 @@ To see the amount of memory consumed by the IPv4 tables use:
.. code-block:: console
vpp# sh ip fib mem
- ipv4-VRF:0 mtrie:333056 hash:3523
- ipv4-VRF:1 mtrie:333056 hash:3523
- totals: mtrie:666112 hash:7046 all:673158
-
- Mtrie Mheap Usage: total: 32.06M, used: 662.44K, free: 31.42M, trimmable: 31.09M
- free chunks 3 free fastbin blks 0
- max total allocated 32.06M
- no traced allocations
+ ipv4-VRF:0 mtrie:335744 hash:4663
+ ipv4-VRF:1 mtrie:333056 hash:3499
+ totals: mtrie:668800 hash:8162 all:676962
this output shows two 'empty' (i.e. no added routes) tables. Each
-mtrie uses about 150k of memory, so each table about 300k. the total
-heap usage statistics for the IP4 heap are shown at the end.
+mtrie uses about 150k of memory, so each table about 300k.
Below the output having added 1M, 2M and 4M routes respectively:
@@ -58,44 +49,23 @@ Below the output having added 1M, 2M and 4M routes respectively:
ipv4-VRF:0 mtrie:335744 hash:4695
totals: mtrie:335744 hash:4695 all:340439
- Mtrie Mheap Usage: total: 1.00G, used: 335.20K, free: 1023.74M, trimmable: 1023.72M
- free chunks 3 free fastbin blks 0
- max total allocated 1.00G
- no traced allocations
-
.. code-block:: console
vpp# sh ip fib mem
ipv4-VRF:0 mtrie:5414720 hash:41177579
totals: mtrie:5414720 hash:41177579 all:46592299
- Mtrie Mheap Usage: total: 1.00G, used: 46.87M, free: 977.19M, trimmable: 955.93M
- free chunks 61 free fastbin blks 0
- max total allocated 1.00G
- no traced allocations
-
.. code-block:: console
vpp# sh ip fib mem
ipv4-VRF:0 mtrie:22452608 hash:168544508
totals: mtrie:22452608 hash:168544508 all:190997116
- Mtrie Mheap Usage: total: 1.00G, used: 198.37M, free: 825.69M, trimmable: 748.24M
- free chunks 219 free fastbin blks 0
- max total allocated 1.00G
- no traced allocations
-
-VPP was started with a 1G IP4 heap.
-IP6 Heap
---------
-
-The IPv6 heap is used to allocate the memory needed for the
-data-structure within which the IPv6 prefixes are stored. IPv6 also
-has the concept of forwarding and non-forwarding entries, however for
-IPv6 all the forwarding entries are stored in a single hash table
-(same goes for the non-forwarding). The key to the hash table includes
-the IPv6 table-id.
+IPv6 also has the concept of forwarding and non-forwarding entries,
+however for IPv6 all the forwarding entries are stored in a single
+hash table (same goes for the non-forwarding). The key to the hash
+table includes the IPv6 table-id.
To see the amount of memory consumed by the IPv4 tables use:
@@ -191,14 +161,10 @@ and 1M:
arena: base 7fedba514000, next 3882740
used 59254592 b (56 Mbytes) of 1073741824 b (1024 Mbytes)
-as can be seen from the output the IPv6 heap in this case was scaled
+as can be seen from the output the IPv6 hash-table in this case was scaled
to 1GB and 1million prefixes has used 56MB of it.
-
-Main Heap
----------
-
-The main heap is used to allocate objects that represent the FIB
+The main heap is also used to allocate objects that represent the FIB
entries in the control and data plane (see :ref:`controlplane` and
:ref:`dataplane`) such as *fib_entry_t* and *load_balance_t*. These come
from the main heap because they are not protocol specific
@@ -263,7 +229,7 @@ requires will increase.
Stats Heap
-----------
+^^^^^^^^^^
VPP collects statistics for each route. For each route VPP collects
byte and packet counters for packets sent to the prefix (i.e. the
@@ -279,5 +245,3 @@ Below shows the size of the stats segment with 1M, 2M and 4M routes.
total: 1023.99M, used: 234.14M, free: 789.85M, trimmable: 668.15M
total: 1023.99M, used: 456.83M, free: 567.17M, trimmable: 388.91M
-VPP was started with a 1G stats heap.
-
/a> 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
# 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.

"""
"""

import plotly.graph_objects as go
import pandas as pd

import hdrh.histogram
import hdrh.codec

from datetime import datetime
from numpy import isnan

from ..jumpavg import classify


_ANOMALY_COLOR = {
    u"regression": 0.0,
    u"normal": 0.5,
    u"progression": 1.0
}
_COLORSCALE_TPUT = [
    [0.00, u"red"],
    [0.33, u"red"],
    [0.33, u"white"],
    [0.66, u"white"],
    [0.66, u"green"],
    [1.00, u"green"]
]
_TICK_TEXT_TPUT = [u"Regression", u"Normal", u"Progression"]
_COLORSCALE_LAT = [
    [0.00, u"green"],
    [0.33, u"green"],
    [0.33, u"white"],
    [0.66, u"white"],
    [0.66, u"red"],
    [1.00, u"red"]
]
_TICK_TEXT_LAT = [u"Progression", u"Normal", u"Regression"]
_VALUE = {
    "mrr": "result_receive_rate_rate_avg",
    "ndr": "result_ndr_lower_rate_value",
    "pdr": "result_pdr_lower_rate_value",
    "pdr-lat": "result_latency_forward_pdr_50_avg"
}
_UNIT = {
    "mrr": "result_receive_rate_rate_unit",
    "ndr": "result_ndr_lower_rate_unit",
    "pdr": "result_pdr_lower_rate_unit",
    "pdr-lat": "result_latency_forward_pdr_50_unit"
}
_LAT_HDRH = (  # Do not change the order
    "result_latency_forward_pdr_0_hdrh",
    "result_latency_reverse_pdr_0_hdrh",
    "result_latency_forward_pdr_10_hdrh",
    "result_latency_reverse_pdr_10_hdrh",
    "result_latency_forward_pdr_50_hdrh",
    "result_latency_reverse_pdr_50_hdrh",
    "result_latency_forward_pdr_90_hdrh",
    "result_latency_reverse_pdr_90_hdrh",
)
# This value depends on latency stream rate (9001 pps) and duration (5s).
# Keep it slightly higher to ensure rounding errors to not remove tick mark.
PERCENTILE_MAX = 99.999501

_GRAPH_LAT_HDRH_DESC = {
    u"result_latency_forward_pdr_0_hdrh": u"No-load.",
    u"result_latency_reverse_pdr_0_hdrh": u"No-load.",
    u"result_latency_forward_pdr_10_hdrh": u"Low-load, 10% PDR.",
    u"result_latency_reverse_pdr_10_hdrh": u"Low-load, 10% PDR.",
    u"result_latency_forward_pdr_50_hdrh": u"Mid-load, 50% PDR.",
    u"result_latency_reverse_pdr_50_hdrh": u"Mid-load, 50% PDR.",
    u"result_latency_forward_pdr_90_hdrh": u"High-load, 90% PDR.",
    u"result_latency_reverse_pdr_90_hdrh": u"High-load, 90% PDR."
}


def _get_color(idx: int) -> str:
    """
    """
    _COLORS = (
        "#1A1110", "#DA2647", "#214FC6", "#01786F", "#BD8260", "#FFD12A",
        "#A6E7FF", "#738276", "#C95A49", "#FC5A8D", "#CEC8EF", "#391285",
        "#6F2DA8", "#FF878D", "#45A27D", "#FFD0B9", "#FD5240", "#DB91EF",
        "#44D7A8", "#4F86F7", "#84DE02", "#FFCFF1", "#614051"
    )
    return _COLORS[idx % len(_COLORS)]


def _get_hdrh_latencies(row: pd.Series, name: str) -> dict:
    """
    """

    latencies = {"name": name}
    for key in _LAT_HDRH:
        try:
            latencies[key] = row[key]
        except KeyError:
            return None

    return latencies


def _classify_anomalies(data):
    """Process the data and return anomalies and trending values.

    Gather data into groups with average as trend value.
    Decorate values within groups to be normal,
    the first value of changed average as a regression, or a progression.

    :param data: Full data set with unavailable samples replaced by nan.
    :type data: OrderedDict
    :returns: Classification and trend values
    :rtype: 3-tuple, list of strings, list of floats and list of floats
    """
    # NaN means something went wrong.
    # Use 0.0 to cause that being reported as a severe regression.
    bare_data = [0.0 if isnan(sample) else sample for sample in data.values()]
    # TODO: Make BitCountingGroupList a subclass of list again?
    group_list = classify(bare_data).group_list
    group_list.reverse()  # Just to use .pop() for FIFO.
    classification = list()
    avgs = list()
    stdevs = list()
    active_group = None
    values_left = 0
    avg = 0.0
    stdv = 0.0
    for sample in data.values():
        if isnan(sample):
            classification.append(u"outlier")
            avgs.append(sample)
            stdevs.append(sample)
            continue
        if values_left < 1 or active_group is None:
            values_left = 0
            while values_left < 1:  # Ignore empty groups (should not happen).
                active_group = group_list.pop()
                values_left = len(active_group.run_list)
            avg = active_group.stats.avg
            stdv = active_group.stats.stdev
            classification.append(active_group.comment)
            avgs.append(avg)
            stdevs.append(stdv)
            values_left -= 1
            continue
        classification.append(u"normal")
        avgs.append(avg)
        stdevs.append(stdv)
        values_left -= 1
    return classification, avgs, stdevs


def select_trending_data(data: pd.DataFrame, itm:dict) -> pd.DataFrame:
    """
    """

    phy = itm["phy"].split("-")
    if len(phy) == 4:
        topo, arch, nic, drv = phy
        if drv == "dpdk":
            drv = ""
        else:
            drv += "-"
            drv = drv.replace("_", "-")
    else:
        return None

    core = str() if itm["dut"] == "trex" else f"{itm['core']}"
    ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
    dut_v100 = "none" if itm["dut"] == "trex" else itm["dut"]
    dut_v101 = itm["dut"]

    df = data.loc[(
        (
            (
                (data["version"] == "1.0.0") &
                (data["dut_type"].str.lower() == dut_v100)
            ) |
            (
                (data["version"] == "1.0.1") &
                (data["dut_type"].str.lower() == dut_v101)
            )
        ) &
        (data["test_type"] == ttype) &
        (data["passed"] == True)
    )]
    df = df[df.job.str.endswith(f"{topo}-{arch}")]
    df = df[df.test_id.str.contains(
        f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$",
        regex=True
    )].sort_values(by="start_time", ignore_index=True)

    return df


def _generate_trending_traces(ttype: str, name: str, df: pd.DataFrame,
    start: datetime, end: datetime, color: str) -> list:
    """
    """

    df = df.dropna(subset=[_VALUE[ttype], ])
    if df.empty:
        return list()
    df = df.loc[((df["start_time"] >= start) & (df["start_time"] <= end))]
    if df.empty:
        return list()

    x_axis = df["start_time"].tolist()

    anomalies, trend_avg, trend_stdev = _classify_anomalies(
        {k: v for k, v in zip(x_axis, df[_VALUE[ttype]])}
    )

    hover = list()
    customdata = list()
    for _, row in df.iterrows():
        d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
        hover_itm = (
            f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
            f"<prop> [{row[_UNIT[ttype]]}]: {row[_VALUE[ttype]]:,.0f}<br>"
            f"<stdev>"
            f"{d_type}-ref: {row['dut_version']}<br>"
            f"csit-ref: {row['job']}/{row['build']}<br>"
            f"hosts: {', '.join(row['hosts'])}"
        )
        if ttype == "mrr":
            stdev = (
                f"stdev [{row['result_receive_rate_rate_unit']}]: "
                f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
            )
        else:
            stdev = ""
        hover_itm = hover_itm.replace(
            "<prop>", "latency" if ttype == "pdr-lat" else "average"
        ).replace("<stdev>", stdev)
        hover.append(hover_itm)
        if ttype == "pdr-lat":
            customdata.append(_get_hdrh_latencies(row, name))

    hover_trend = list()
    for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
        d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
        hover_itm = (
            f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
            f"trend [pps]: {avg:,.0f}<br>"
            f"stdev [pps]: {stdev:,.0f}<br>"
            f"{d_type}-ref: {row['dut_version']}<br>"
            f"csit-ref: {row['job']}/{row['build']}<br>"
            f"hosts: {', '.join(row['hosts'])}"
        )
        if ttype == "pdr-lat":
            hover_itm = hover_itm.replace("[pps]", "[us]")
        hover_trend.append(hover_itm)

    traces = [
        go.Scatter(  # Samples
            x=x_axis,
            y=df[_VALUE[ttype]],
            name=name,
            mode="markers",
            marker={
                u"size": 5,
                u"color": color,
                u"symbol": u"circle",
            },
            text=hover,
            hoverinfo=u"text+name",
            showlegend=True,
            legendgroup=name,
            customdata=customdata
        ),
        go.Scatter(  # Trend line
            x=x_axis,
            y=trend_avg,
            name=name,
            mode="lines",
            line={
                u"shape": u"linear",
                u"width": 1,
                u"color": color,
            },
            text=hover_trend,
            hoverinfo=u"text+name",
            showlegend=False,
            legendgroup=name,
        )
    ]

    if anomalies:
        anomaly_x = list()
        anomaly_y = list()
        anomaly_color = list()
        hover = list()
        for idx, anomaly in enumerate(anomalies):
            if anomaly in (u"regression", u"progression"):
                anomaly_x.append(x_axis[idx])
                anomaly_y.append(trend_avg[idx])
                anomaly_color.append(_ANOMALY_COLOR[anomaly])
                hover_itm = (
                    f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
                    f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
                    f"classification: {anomaly}"
                )
                if ttype == "pdr-lat":
                    hover_itm = hover_itm.replace("[pps]", "[us]")
                hover.append(hover_itm)
        anomaly_color.extend([0.0, 0.5, 1.0])
        traces.append(
            go.Scatter(
                x=anomaly_x,
                y=anomaly_y,
                mode=u"markers",
                text=hover,
                hoverinfo=u"text+name",
                showlegend=False,
                legendgroup=name,
                name=name,
                marker={
                    u"size": 15,
                    u"symbol": u"circle-open",
                    u"color": anomaly_color,
                    u"colorscale": _COLORSCALE_LAT \
                        if ttype == "pdr-lat" else _COLORSCALE_TPUT,
                    u"showscale": True,
                    u"line": {
                        u"width": 2
                    },
                    u"colorbar": {
                        u"y": 0.5,
                        u"len": 0.8,
                        u"title": u"Circles Marking Data Classification",
                        u"titleside": u"right",
                        u"tickmode": u"array",
                        u"tickvals": [0.167, 0.500, 0.833],
                        u"ticktext": _TICK_TEXT_LAT \
                            if ttype == "pdr-lat" else _TICK_TEXT_TPUT,
                        u"ticks": u"",
                        u"ticklen": 0,
                        u"tickangle": -90,
                        u"thickness": 10
                    }
                }
            )
        )

    return traces


def graph_trending(data: pd.DataFrame, sel:dict, layout: dict,
    start: datetime, end: datetime) -> tuple:
    """
    """

    if not sel:
        return None, None

    fig_tput = None
    fig_lat = None
    for idx, itm in enumerate(sel):

        df = select_trending_data(data, itm)
        if df is None or df.empty:
            continue

        name = "-".join((itm["dut"], itm["phy"], itm["framesize"], itm["core"],
            itm["test"], itm["testtype"], ))
        traces = _generate_trending_traces(
            itm["testtype"], name, df, start, end, _get_color(idx)
        )
        if traces:
            if not fig_tput:
                fig_tput = go.Figure()
            fig_tput.add_traces(traces)

        if itm["testtype"] == "pdr":
            traces = _generate_trending_traces(
                "pdr-lat", name, df, start, end, _get_color(idx)
            )
            if traces:
                if not fig_lat:
                    fig_lat = go.Figure()
                fig_lat.add_traces(traces)

    if fig_tput:
        fig_tput.update_layout(layout.get("plot-trending-tput", dict()))
    if fig_lat:
        fig_lat.update_layout(layout.get("plot-trending-lat", dict()))

    return fig_tput, fig_lat


def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
    """
    """

    fig = None

    traces = list()
    for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
        try:
            decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
        except (hdrh.codec.HdrLengthException, TypeError) as err:
            continue
        previous_x = 0.0
        prev_perc = 0.0
        xaxis = list()
        yaxis = list()
        hovertext = list()
        for item in decoded.get_recorded_iterator():
            # The real value is "percentile".
            # For 100%, we cut that down to "x_perc" to avoid
            # infinity.
            percentile = item.percentile_level_iterated_to
            x_perc = min(percentile, PERCENTILE_MAX)
            xaxis.append(previous_x)
            yaxis.append(item.value_iterated_to)
            hovertext.append(
                f"<b>{_GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
                f"Direction: {(u'W-E', u'E-W')[idx % 2]}<br>"
                f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
                f"Latency: {item.value_iterated_to}uSec"
            )
            next_x = 100.0 / (100.0 - x_perc)
            xaxis.append(next_x)
            yaxis.append(item.value_iterated_to)
            hovertext.append(
                f"<b>{_GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
                f"Direction: {(u'W-E', u'E-W')[idx % 2]}<br>"
                f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
                f"Latency: {item.value_iterated_to}uSec"
            )
            previous_x = next_x
            prev_perc = percentile

        traces.append(
            go.Scatter(
                x=xaxis,
                y=yaxis,
                name=_GRAPH_LAT_HDRH_DESC[lat_name],
                mode=u"lines",
                legendgroup=_GRAPH_LAT_HDRH_DESC[lat_name],
                showlegend=bool(idx % 2),
                line=dict(
                    color=_get_color(int(idx/2)),
                    dash=u"solid",
                    width=1 if idx % 2 else 2
                ),
                hovertext=hovertext,
                hoverinfo=u"text"
            )
        )
    if traces:
        fig = go.Figure()
        fig.add_traces(traces)
        layout_hdrh = layout.get("plot-hdrh-latency", None)
        if lat_hdrh:
            fig.update_layout(layout_hdrh)

    return fig